diff --git a/docs/evaluation/input-failure-replay-20261024.md b/docs/evaluation/input-failure-replay-20261024.md new file mode 100644 index 00000000..bee35927 --- /dev/null +++ b/docs/evaluation/input-failure-replay-20261024.md @@ -0,0 +1,64 @@ +# Selection failure and durable input replay + +The installed default-model catalog read timed out during an actual input +preflight. A subsequent bounded read recovered without restarting the shared +router. The raw timeout reached model selection before an adapter existed. +At that boundary the input path returned a generic failure, and an independent +installed-code regression reproduced loss of even a recognized error reason on +request replay: the initial receipt had the reason but durable generation +evidence did not, so replay omitted it. + +The catalog now maps transport failures to bounded typed reasons: timeout or +connection failure to `routed_llm_unavailable`, HTTP401/403 to +`routed_llm_authentication`, HTTP429 to `routed_llm_quota`. It does not retain +provider bodies/URLs, retry, change the chosen model or treat a failed catalog +read as evidence about inference availability. The routed adapter also preserves +this reason if its own selection-stage catalog read fails before transport. + +The input failure handler computes the safe code before persisting cancellation. +If there is no more specific bound adapter error, it retains only a code already +accepted by the generation metadata allowlist. It invents no selected/observed +model, response, usage, timing or verified context when selection failed before +an adapter existed. Existing sanitized adapter observations remain authoritative. +Unknown or decorated provider strings stay generic and are never echoed. + +Failed-ID replay returns the original durable result; it does not select, +parse attachments, fetch links or generate again. Successful replay likewise +preserves the original receipt. The model setting, request identity, attachment +bytes and source references remain unchanged. No database schema change is +required and historical failed records are not retroactively rewritten. + +```mermaid +stateDiagram-v2 + [*] --> ReservedInput + ReservedInput --> Selection + Selection --> Generation: catalog and model selection accepted + Selection --> SafeFailure: timeout / authentication / quota + Generation --> BoundAdapterFailure: observed adapter error + Generation --> Completed: current turn and evidence verified + SafeFailure --> FailedReceipt: persist exact safe code without invented observations + BoundAdapterFailure --> FailedReceipt: preserve bound adapter evidence + FailedReceipt --> ReplayFailed: original request ID + Completed --> ReplayCompleted: original request ID + ReplayFailed --> [*] + ReplayCompleted --> [*] +``` + +This is a projection of the implemented control flow and bounded regressions, +not a theorem about all provider failures, asynchronous execution or OS state. +Tests cover both catalog reads, reason-specific replay, no generation after +selection rejection, no false provider-health write, and no secret/URL echo. + +Separate installed-runtime verification used an isolated private conversation +store, the exact copied current Flash/high setting and the production abort +epoch. Synthetic image/text-file inputs, previous attachments, a public SQLite +page and its saved followup, cross-conversation isolation, completed replay and +late-response supersession all reached the actual selected routed model. +The supersession case holds a real provider result at an owned post-generation, +pre-commit barrier; it is not natural timing or a physical UI/gesture test. + +These runtime results are task evidence, not checked-in source data or a broad +accuracy benchmark. The task's private reports retain original request IDs, +response stamps, bytes/digests and ledger readback. Native composer interaction, +physical voice, broad file formats/visual understanding, independent semantic +gold, actual backend reasoning effort and normal release remain distinct gates. diff --git a/scripts/alden_chat.py b/scripts/alden_chat.py index 121bf89b..85337da8 100644 --- a/scripts/alden_chat.py +++ b/scripts/alden_chat.py @@ -454,17 +454,26 @@ def bind_context(): 'conversation_id': ticket['conversation_id'] if ticket else value['conversation_id'], 'error_code': 'assistant_input_superseded'} except Exception as error: - if ticket: cancel_turn(state_root, ticket, reason='failed', generation=failure_generation(selection,ticket,'failed')) from alden_chat_metrics import generation_error_code reason = str(error) code = reason if reason in KNOWN_INPUT_ERRORS else generation_error_code(reason) or 'assistant_input_failed' + if ticket: cancel_turn(state_root, ticket, reason='failed', + generation=failure_generation(selection,ticket,'failed',error_code=code)) return {'ok': False, 'state': 'failed', 'request_id': value['request_id'], 'conversation_id': ticket['conversation_id'] if ticket else value['conversation_id'], 'error_code': code} -def failure_generation(selection, ticket, state): +def failure_generation(selection, ticket, state, *, error_code=None): try: - return generation_evidence(selection, ticket.get('adapter_metrics', {}), ticket, state) + result = generation_evidence(selection, ticket.get('adapter_metrics', {}), ticket, state) + # Model selection can fail before an adapter exists. Preserve only an + # exact safe reason, without inventing response/model/timing evidence + # or replacing a more specific bound adapter error. + from alden_chat_metrics import generation_error_code + safe = generation_error_code(error_code) + if state == 'failed' and safe is not None and 'error_code' not in result: + result['error_code'] = safe + return result except ValueError: # Preserve the cancellation/failure itself, without attributing unsafe # or mismatched observations to this request. diff --git a/scripts/alden_model_routes.py b/scripts/alden_model_routes.py index 7cf3def8..a6212ed0 100644 --- a/scripts/alden_model_routes.py +++ b/scripts/alden_model_routes.py @@ -13,6 +13,7 @@ import stat import tempfile import time +import urllib.error import urllib.request ROUTER = "http://127.0.0.1:10101/v1" @@ -22,6 +23,13 @@ MODEL_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._/:-]{0,199}\Z") MAX_BYTES = 4 * 1024 * 1024 +class ModelCatalogError(RuntimeError): + """Safe transport reason; catalog/provider payloads never become the code.""" + def __init__(self, code): + if code not in ('routed_llm_authentication','routed_llm_quota','routed_llm_unavailable'): + raise ValueError('model_catalog_error_invalid') + super().__init__(code) + class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): raise RuntimeError("model_router_redirect_rejected") @@ -100,7 +108,14 @@ def host_workspace(): def catalog(root, *, fetcher=_read, now=None, memory_reader=host_workspace): stamp = time.time() if now is None else now - raw = fetcher(ROUTER + "/models") + try: + raw = fetcher(ROUTER + "/models") + except urllib.error.HTTPError as error: + code = ('routed_llm_authentication' if error.code in {401,403} + else 'routed_llm_quota' if error.code == 429 else 'routed_llm_unavailable') + raise ModelCatalogError(code) from error + except (OSError, urllib.error.URLError) as error: + raise ModelCatalogError('routed_llm_unavailable') from error rows = raw.get("models", raw.get("data", [])) if isinstance(raw, dict) else [] if not isinstance(rows, list) or len(rows) > 256: raise RuntimeError("model_catalog_invalid") diff --git a/scripts/alden_routed_llm.py b/scripts/alden_routed_llm.py index cec07c75..4021e734 100644 --- a/scripts/alden_routed_llm.py +++ b/scripts/alden_routed_llm.py @@ -11,7 +11,7 @@ import urllib.request import uuid from alden_local_http import CancellableLocalResponse -from alden_model_routes import ROUTER, find_model, catalog, record_result +from alden_model_routes import ROUTER, find_model, catalog, record_result, ModelCatalogError MAX_RESPONSE_BYTES = 1024 * 1024 MAX_IMAGE_BYTES = 8 * 1024 * 1024 @@ -186,7 +186,7 @@ def _generate(self, text, token, *, history, turn=None, system_prompt=None, imag cancelled = token.is_cancelled() self.last_metrics["request"].update(state="cancelled" if cancelled else "failed", cancelled=cancelled) code = "cancelled" if cancelled else "quota" if isinstance(error, urllib.error.HTTPError) and error.code == 429 else "authentication" if isinstance(error, urllib.error.HTTPError) and error.code in {401, 403} else "unavailable" - reason = str(error) if isinstance(error, RoutedGenerationError) else "routed_llm_" + code + reason = str(error) if isinstance(error, (RoutedGenerationError, ModelCatalogError)) else "routed_llm_" + code self.last_metrics.update(stage=stage, error_code=reason) # A missing image, bad prompt or context failure says nothing about # provider readiness and must not poison the model picker indicator. diff --git a/tests/test_alden_chat.py b/tests/test_alden_chat.py index cdadee15..a63c2643 100644 --- a/tests/test_alden_chat.py +++ b/tests/test_alden_chat.py @@ -33,6 +33,64 @@ def chunk(kind, data): class AssistantInputTests(unittest.TestCase): + def test_pre_adapter_selection_failure_keeps_its_exact_reason_on_replay(self): + from alden_chat_turns import get_request + for number,code in [(81,'routed_llm_unavailable'),(82,'routed_llm_authentication'), + (83,'routed_llm_quota'),(84,'model_effort_not_supported')]: + with self.subTest(code=code): + select=unittest.mock.Mock(side_effect=RuntimeError(code)) + generate=unittest.mock.Mock(side_effect=AssertionError('generation must not start')) + value=request(number) + first=chat.process_input(self.root,value,self.token,select_model=select,generate=generate) + self.assertEqual(first['error_code'],code) + replay=chat.process_input(self.root,value,self.token,select_model=select,generate=generate) + self.assertEqual(replay.get('error_code'),code) + self.assertEqual(get_request(self.root,value['request_id'])['generation']['error_code'],code) + self.assertNotIn('response',replay['generation']) + self.assertEqual(replay['generation']['selection'],{}) + self.assertNotIn('reply',replay) + select.assert_called_once();generate.assert_not_called() + + def test_catalog_transport_failures_are_safe_selection_errors_with_durable_replay(self): + import alden_model_routes as routes + from urllib.error import HTTPError,URLError + cases=[(TimeoutError('private endpoint timed out'),'routed_llm_unavailable'), + (URLError('private endpoint unavailable'),'routed_llm_unavailable'), + (HTTPError('http://user:secret@127.0.0.1/private',401,'private',{},None),'routed_llm_authentication'), + (HTTPError('http://127.0.0.1/private',429,'private',{},None),'routed_llm_quota')] + for number,(failure,code) in enumerate(cases,90): + with self.subTest(code=code): + fetch=unittest.mock.Mock(side_effect=failure) + def select(root):return routes.catalog(root,fetcher=fetch) + generate=unittest.mock.Mock(side_effect=AssertionError('generation must not start')) + first=chat.process_input(self.root,request(number),self.token,select_model=select,generate=generate) + self.assertEqual(first['error_code'],code) + replay=chat.process_input(self.root,request(number),self.token,select_model=select,generate=generate) + self.assertEqual(replay.get('error_code'),code) + self.assertNotIn('private',json.dumps(first)+json.dumps(replay)) + fetch.assert_called_once();generate.assert_not_called() + + def test_adapter_catalog_rejection_keeps_its_reason_without_response_or_provider_health_write(self): + import alden_model_routes as routes + from urllib.error import HTTPError + for number,status,code in [(96,401,'routed_llm_authentication'),(97,429,'routed_llm_quota'),(98,503,'routed_llm_unavailable')]: + with self.subTest(status=status): + def catalog(root): + def fetch(url):raise HTTPError(url,status,'private-provider-body',{},None) + return routes.catalog(root,fetcher=fetch) + with patch('alden_routed_llm.catalog',side_effect=catalog), \ + patch('alden_routed_llm.CancellableLocalResponse') as transport, \ + patch('alden_routed_llm.record_result') as health: + value=request(number) + first=self.run_input(value,generate=chat.generate_input) + self.assertEqual(first['error_code'],code) + replay=self.run_input(value,generate=chat.generate_input) + self.assertEqual(replay.get('error_code'),code) + self.assertEqual(replay['generation']['request']['stage'],'selection') + self.assertNotIn('response',replay['generation']) + transport.assert_not_called();health.assert_not_called() + + def test_advertised_max_route_completes_and_replays_without_losing_effort(self): import alden_model_routes as routes from functools import partial