Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): classify by machine codes; an unnamed stream error spares the Source (#2463)
Call Whited11332a1a2dd
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex fb11879a8..c08d2b474 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -145,7 +145,9 @@ class RawCallOutcome:kind: RawOutcomeKindhttp_status: int | Noneerror_code: str | None # upstream machine code if parseable, else None- redacted_message: str | None # L1 guarantees no credential material+ # L1's own account of how the call ended, never upstream text; classification+ # does not read it. L1 guarantees no credential material.+ redacted_message: str | Nonestream_started: boolmodel_id: strsource_id: strdiff --git a/core/handlers/model_hub/classification.py b/core/handlers/model_hub/classification.pyindex b28d1020d..dcd955e0a 100644--- a/core/handlers/model_hub/classification.py+++ b/core/handlers/model_hub/classification.py@@ -129,6 +129,8 @@ _MACHINE_ERROR_TAXONOMY: Final[Mapping[str, _MachineErrorRule]] = {"overloaded": _MachineErrorRule("transient", True, 80, "fallback", "server_error", None, 30, None),"overloaded_error": _MachineErrorRule("transient", True, 80, "fallback", "server_error", None, 30, None),"server_error": _MachineErrorRule("server", True, 70, "fallback", "server_error", None, 30, None),+ # CLIProxyAPI's Claude type for an upstream 504, and since v8 for a 408.+ "timeout_error": _MachineErrorRule("server", True, 70, "fallback", "server_error", None, 30, None),"internal_error": _MachineErrorRule("server", True, 70, "fallback", "server_error", None, 30, None),"api_error": _MachineErrorRule("server", True, 10, "fallback", "server_error", None, 30, None),"service_unavailable_error": _MachineErrorRule(@@ -192,7 +194,11 @@ def terminal_outcome_category(def _error_text(outcome: RawCallOutcome) -> str:- return " ".join((*machine_error_codes(outcome), outcome.redacted_message or ""))+ # Machine codes only. ``redacted_message`` is the engine client's own account+ # of how the call ended, not upstream text, so its wording must not decide a+ # class: "upstream returned a protocol error event" once read as a rejected+ # request.+ return " ".join(machine_error_codes(outcome))def machine_error_codes(outcome: RawCallOutcome) -> tuple[str, ...]:diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 0203b838c..e2ecd4f0e 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -8019,6 +8019,18 @@ class ModelHubService:settlement_rule = source_settlement_rule(event_reason)if decision.reason == "network" and outcome is not None and outcome.stream_started:return event_reason, False+ if (+ decision.reason == "unclassified_error"+ and outcome is not None+ and outcome.http_status is not None+ and 200 <= outcome.http_status < 300+ ):+ # An error frame no machine code names, inside a response the upstream+ # accepted, is ambiguous evidence: the relay, the engine, or a transient+ # fault. It ends this attempt and never writes Source health, but a+ # half-open attempt still gives its slot back.+ self.recovery.release(source.id, settlement_generation)+ return event_reason, False# Generations are minted at attempt start and nowhere else. A settlement# that carries none cannot prove it is not superseded, so it does not# write Source health; minting one here would let any stale attemptdiff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex fb11879a8..c08d2b474 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -145,7 +145,9 @@ class RawCallOutcome:kind: RawOutcomeKindhttp_status: int | Noneerror_code: str | None # upstream machine code if parseable, else None- redacted_message: str | None # L1 guarantees no credential material+ # L1's own account of how the call ended, never upstream text; classification+ # does not read it. L1 guarantees no credential material.+ redacted_message: str | Nonestream_started: boolmodel_id: strsource_id: strdiff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 9cf4e9f99..db5ecdf96 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1755,7 +1755,7 @@ contract harness and API-boundary tests enforce:| tier resolution chooses the first applicable `upstream > catalog > user > null` rung; upstream uses only valid OpenRouter-shape capability metadata and protocol defaults, catalog uses each exact row without filtering, OAuth/import reuse the same resolver, and older persisted rows infer `user` for non-empty tiers or null for empty tiers | catalog contract, ladder unit tests, config load fixture, and materialization tests || model tier PATCH and add-model upsert refuse managed `upstream`/`catalog` rows with `source_model_tiers_managed` and an exact provenance sibling, while `user`/null rows remain editable; refresh emits one redacted override event only after a committed replacement of a non-empty user declaration | API mutation, refresh, and event tests || a stripped effort and the exact hop declaration consulted appear as a pair only on the attempt where stripping occurred, in turn provenance and a redacted logger line | gateway/provenance unit and D10 e2e tests |-| network fixtures cover shaped/transport × `stream_started: false/true`, where the boundary is the first user-visible model-output byte: shaped results at either phase enter only their existing non-permanent Source classifier; unclassified pre-output connection failure creates bounded live backoff with no config write; only later output from that same Source clears its streak, while another Source's successful fallback does not; the API/read assembler emits a future deadline for a live overlay and normalizes an expired overlay before serialization; concurrent cooldown/needs-action/error/missing-Source/unsupported-model facts suppress the overlay and keep stronger projections, so waiting never hides a durable blocker; simultaneous native-process unavailability alone preserves backoff health/deadline while taking reason precedence and yielding interrupted; probe `connection_failed` requires the exact Hub/unreachable/null-latency shape | clocked table-driven resolver/API/event, AgentChain precedence, ProbeResult relation, and concurrent-transition tests |+| network fixtures cover shaped/transport × `stream_started: false/true`, where the boundary is the first user-visible model-output byte: shaped results at either phase enter only their existing non-permanent Source classifier; an error frame no machine-code row names, inside a 2xx response, writes no Source health at either phase (before output it is this turn's fallback only, recorded as `unclassified_error`; orchestrator decision 2026-10-11); unclassified pre-output connection failure creates bounded live backoff with no config write; only later output from that same Source clears its streak, while another Source's successful fallback does not; the API/read assembler emits a future deadline for a live overlay and normalizes an expired overlay before serialization; concurrent cooldown/needs-action/error/missing-Source/unsupported-model facts suppress the overlay and keep stronger projections, so waiting never hides a durable blocker; simultaneous native-process unavailability alone preserves backoff health/deadline while taking reason precedence and yielding interrupted; probe `connection_failed` requires the exact Hub/unreachable/null-latency shape | clocked table-driven resolver/API/event, AgentChain precedence, ProbeResult relation, and concurrent-transition tests || every `GuardRefusal` validates against `guard-refusal.schema.json` and has a nonempty current plan; fixtures cover every guard-decision row, including unforced refusal, exact echoed-plan confirmation, missing/different echo returning the new plan, and old-echo empty-plan ordinary success without a fabricated 409 | API payload and concurrent-mutation test || `PUT /sources/<id>/credential` success contains exactly the standard `{source, removed_hops, interrupted}` mutation tail; `{recovered, interrupted_pairs}` is absent there and remains owned only by terminal OAuth `intent: "reauth"` | contract negative fixture and API payload test || OAuth status/submit covers every `oauth_terminal.*` row; a native re-auth materialization error with a nonempty acquired-side-effect report emits that exact `interrupted_pairs`, while the same error with no report and every non-materialization error omit the field rather than sending `[]` | contract totality fixture plus positive/negative API and client payload tests |diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex 5914c8afd..d73695e06 100644--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json@@ -209,6 +209,7 @@"overloaded","overloaded_error","server_error",+ "timeout_error","internal_error","api_error","service_unavailable_error",diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.mdindex a8e276fb2..a8716e319 100644--- a/docs/plans/model-hub-implementation.md+++ b/docs/plans/model-hub-implementation.md@@ -984,7 +984,7 @@ external resolver importers.| **FC-09** | `resolution-event.schema.json` | Removes `mapping_applied` and its `mapping` reason: an explicit model mapping is stored configuration, not a runtime resolution event. Remaining events carry exact Source/model attribution with mechanically mirrored reason/detail/severity fields. The feed is a pull surface; event descriptions contain no proactive-delivery or recipient-resolution contract. No mapping field, route-rewrite event, or internal-version conversion state exists. || **FC-10** | `adapter-interface.py` | Defines the three protocols, response-backed protocol observation, connectivity classification, credential refresh capability, discovery, all-inventory reasoning-efforts validation, transient credential cleanup on every unsaved-flow exit, and durable reconciliation on revoke failure. `invoke(reasoning_effort: str | None)` stays singular because §4.3 passes zero or one exact member. Runtime-local `engine_down` is distinct from Source failure. The checked-in interface and runtime adapter are byte-identical. || **FC-11** | `opencode-overlay.md` | OpenCode menu identity is bare canonical model id with server-owned native_protocol. The overlay generates one provider per downstream protocol. The shared planner uses literal inventory matching or unchanged-id Hub API-key passthrough, and invocation pins the selected effective Source/model pair; manual mappings remain exact. Overlay identity does not encode current Source, route origin, health or credentials. |-| **FC-12** | `api.md` | **Revised 2026-08-11 by the owner-authorized K4 completion; guard/nonce simplified by the 20:35 owner subtraction ruling, with deletion/recreate, process-local reservation, direct-Route scope, guard error/plan relations, canonical plan order, blocker/Probe/credential-response ownership, both-channel re-auth acknowledgement, OAuth explicit-cancel totality, and terminal materialization-error response ownership closed through 2026-08-12 01:28.** Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, discovered-model retirement, and manual deletion, the explicit backend Source-order PUT, effective route GET/list, manual PUT, DELETE Restore and POST preview, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`; an optional nonce is reserved only in process before work and persisted on the Source only at commit, while committed retries conflict and reconcile through the ordinary Source list. Nonce uniqueness covers only live-process reservations and live Sources: clients read before retry, and restart or deletion plus list miss makes a same-nonce request a fresh create. OAuth start claims its nonce/vendor/channel tuple before provider work and coalesces a concurrent retry; failure or task cancellation before a flow exists releases after cleanup, while explicit cancellation of a nonce-bearing committed flow retains that same terminal `cancelled` flow until its existing expiry and never starts the provider on a delayed retry. A no-nonce cancel still forgets. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes. Every guard lead error requires its corresponding nonempty evidence array; both plan arrays are duplicate-free and `would_interrupt` uses canonical outer `(backend, model_id)` plus inner stable-Agent-id order; every nonempty forced guarded-impact plan requires exact echoes of the refusal's `would_remove_hops` and `would_interrupt`. A missing or changed echo returns the same 409 family with the new plan and never removes an unconfirmed hop, while an empty recomputed plan follows ordinary success with force/echo inert. API-key credential success uses only `{source, removed_hops, interrupted}` and exposes repair through `Source.state`. Successful terminal OAuth re-auth alone owns the complete `{recovered, interrupted_pairs}` tail and may report an empty array; a terminal materialization error instead uses the standard error envelope and carries nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation has already stranded supply, otherwise omitting the field. A visible noninterrupting nonempty `route_replace` removal is ordinary success; empty PUT instead uses DELETE Restore and its exact effective-removal/supply guards. The network totality table uses `stream_started` at the first user-visible model-output byte: it admits shaped errors before or after that boundary to existing Source classifications, gives an unclassified pre-output connection failure bounded live backoff, clears the streak only on later output from that same Source, normalizes an expired overlay before API serialization, and makes an unclassified post-output interruption event-only. A live overlay applies only over a healthy capability-present hop; cooldown, needs-action, error, missing Source, and unsupported model keep their stronger projections, while native-process unavailability is the sole reason-priority exception. Probe `connection_failed` is confined to the Hub/unreachable/null-latency shape. Forced Source/manual-model deletion preserves survivor order; discovered-model DELETE instead persists `retired: true`, retains the row through refresh, and uses the same exact-hop and protected-supply guards. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, second persisted route policy, separate mapping, takeover, experimental-consent, observation-evidence detail, durable pre-create claim, receipt/digest, or vendor-guessed protocol surface exists. |+| **FC-12** | `api.md` | **Revised 2026-08-11 by the owner-authorized K4 completion; guard/nonce simplified by the 20:35 owner subtraction ruling, with deletion/recreate, process-local reservation, direct-Route scope, guard error/plan relations, canonical plan order, blocker/Probe/credential-response ownership, both-channel re-auth acknowledgement, OAuth explicit-cancel totality, and terminal materialization-error response ownership closed through 2026-08-12 01:28.** Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, discovered-model retirement, and manual deletion, the explicit backend Source-order PUT, effective route GET/list, manual PUT, DELETE Restore and POST preview, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`; an optional nonce is reserved only in process before work and persisted on the Source only at commit, while committed retries conflict and reconcile through the ordinary Source list. Nonce uniqueness covers only live-process reservations and live Sources: clients read before retry, and restart or deletion plus list miss makes a same-nonce request a fresh create. OAuth start claims its nonce/vendor/channel tuple before provider work and coalesces a concurrent retry; failure or task cancellation before a flow exists releases after cleanup, while explicit cancellation of a nonce-bearing committed flow retains that same terminal `cancelled` flow until its existing expiry and never starts the provider on a delayed retry. A no-nonce cancel still forgets. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes. Every guard lead error requires its corresponding nonempty evidence array; both plan arrays are duplicate-free and `would_interrupt` uses canonical outer `(backend, model_id)` plus inner stable-Agent-id order; every nonempty forced guarded-impact plan requires exact echoes of the refusal's `would_remove_hops` and `would_interrupt`. A missing or changed echo returns the same 409 family with the new plan and never removes an unconfirmed hop, while an empty recomputed plan follows ordinary success with force/echo inert. API-key credential success uses only `{source, removed_hops, interrupted}` and exposes repair through `Source.state`. Successful terminal OAuth re-auth alone owns the complete `{recovered, interrupted_pairs}` tail and may report an empty array; a terminal materialization error instead uses the standard error envelope and carries nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation has already stranded supply, otherwise omitting the field. A visible noninterrupting nonempty `route_replace` removal is ordinary success; empty PUT instead uses DELETE Restore and its exact effective-removal/supply guards. The network totality table uses `stream_started` at the first user-visible model-output byte: it admits shaped errors before or after that boundary to existing Source classifications, gives an unclassified pre-output connection failure bounded live backoff, clears the streak only on later output from that same Source, normalizes an expired overlay before API serialization, and makes an unclassified post-output interruption event-only. An error frame no machine-code row names, inside a 2xx response, never writes Source health: before output it is this turn's fallback only, recorded as `unclassified_error`; after output it is event-only (orchestrator decision 2026-10-11). A live overlay applies only over a healthy capability-present hop; cooldown, needs-action, error, missing Source, and unsupported model keep their stronger projections, while native-process unavailability is the sole reason-priority exception. Probe `connection_failed` is confined to the Hub/unreachable/null-latency shape. Forced Source/manual-model deletion preserves survivor order; discovered-model DELETE instead persists `retired: true`, retains the row through refresh, and uses the same exact-hop and protected-supply guards. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, second persisted route policy, separate mapping, takeover, experimental-consent, observation-evidence detail, durable pre-create claim, receipt/digest, or vendor-guessed protocol surface exists. || **FC-13** | `migration-scan.schema.json` | Copy-only native config import uses the §6 action matrix. keep_native/import place Sources into backend defaults and report effective added_to positions without writing manual route keys. Original files remain byte-identical, duplicate native selection fails before OAuth/partial commit. Supported internal persisted shapes still use compatibility loading; import is a separate user workflow. || **FC-14** | `runtime-dependency.schema.json` | Defines the single local engine asset, immutable version/SHA, loopback binding, lifecycle/health, management and Gateway tokens, and fail-closed behavior. `installing` is exactly the unverified non-listening shape with null installed version; any verified/listening runtime settles outside that transition. Engine availability is local Gateway health and never mutates an upstream Source cooldown. This entry does not widen the GA asset-mirror or platform-matrix research scope. **Installing-shape revision: 2026-08-11 23:09 K4.** |diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex ed7a4ef4c..b3897a449 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -645,7 +645,12 @@ unclassified connection failure creates only live short backoff. The fact flipsthe first user-visible model-output byte, never at HTTP status, headers, or anotherresponse byte. After it flips, a stream interruption creates only its existing redactedevent and never mutates Source health or creates backoff. No post-output failure is-replayed.+replayed. An error frame whose class no machine-code row names, arriving inside a 2xx+response, is ambiguous evidence (the relay, the engine, or a transient fault) and never+writes Source health (orchestrator decision 2026-10-11): before output it falls back for+this turn only, recorded as `unclassified_error`, with no cooldown, live backoff, or+Source event; after output it is event-only, like a stream interruption. An+unclassified HTTP-status failure keeps `error`.The read projection is `C` with live annotations plus `current`, never a reconstructedprovider list. Takeover remains derived: the current hop is not `C[0]` and `C[0]` is@@ -662,7 +667,9 @@ protocol conformance validator.The complete observation surface is limited to these facts:1. An official error envelope at a terminal position is `failed_terminal`; machine-code- extraction reads only the protocol's declared C12 trust roots.+ extraction reads only the protocol's declared C12 trust roots. Classification reads+ only those machine codes, never the engine client's own account of how the call+ ended.2. An official success terminal is `served` when its discriminator identity matches. Fornamed SSE events this is the minimal `(event name, data.type)` match. This isdiscriminator-only observation, not validation of the remaining envelope members or@@ -993,7 +1000,7 @@ Three classes, because the action owed by the user differs in each.| `standby` | 正常 | — | healthy source; when `adopted_by` is non-empty it is shown as supplying the configured route || `cooldown` | 暂不可用 (gold) | **yes** | shaped quota/rate/server result; persisted `retry_at` known; recovers unattended || `needs_action` | 需处理 (rose) | **no** | OAuth expired, balance exhausted, key revoked/banned — dead until the user acts |-| `error` | 异常 | **no** | unclassified failure — no `retry_at`, so nothing clears it unattended |+| `error` | 异常 | **no** | unclassified HTTP-status failure — no `retry_at`, so nothing clears it unattended; an unclassified in-stream error frame never sets it |`needs_action`, introduced in v2 and retained by v3, carries a `detail_key` naming the cause, so therow can offer **one tap to fix it** (re-auth, top up, replace key) instead of adiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 24a60dbca..638f1bd52 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -10,6 +10,7 @@ import tempfileimport threadingfrom collections import dequefrom concurrent.futures import ThreadPoolExecutor+from dataclasses import replacefrom contextlib import contextmanagerfrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -10926,6 +10927,170 @@ def test_a_turn_cancelled_before_it_read_the_body_is_still_a_call_that_happened(asyncio.run(exercise())+def _unnamed_stream_error(source_id: str, *, stream_started: bool = False) -> RawCallOutcome:+ """A 2xx response whose error frame no machine-code row names, as the engine client reports it."""++ return replace(+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=200,+ message="upstream returned a protocol error event",+ source_id=source_id,+ stream_started=stream_started,+ ),+ error_candidates=("relay_specific_error",),+ upstream_detail="upstream protocol error",+ )+++def _assert_source_health_untouched(service: ModelHubService, source_id: str) -> None:+ source = next(item for item in service.store.load().sources if item.id == source_id)+ assert (source.state.status, source.state.retry_at, source.state.detail_key) == ("standby", None, None)+ assert source_id not in service.recovery.annotations(service.store.load())+++def test_an_unnamed_stream_error_before_output_falls_back_for_this_turn_only(+ tmp_path: Path,+) -> None:+ """Orchestrator decision 2026-10-11: ambiguous evidence never writes Source health."""++ async def exercise() -> None:+ first = _source("src_primary01", "Primary")+ second = _source("src_backup001", "Backup")+ service = _service(+ tmp_path,+ sources=[first, second],+ outcomes=[+ _unnamed_stream_error(first.id),+ _outcome(RawOutcomeKind.SUCCESS, source_id=second.id),+ _outcome(RawOutcomeKind.SUCCESS, source_id=first.id),+ ],+ )+ model = _canonicalize_fixed_test_routes(service)["codex"]+ service.store.config.agents["codex"].routes[model] = ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(first.id, "shared-model"),+ ModelHubRouteHopConfig(second.id, "shared-model"),+ )+ )++ served = await service.resolve(backend="codex", model_id=model, request={}, supply_channel="hub")++ assert served.source_id == second.id+ _assert_source_health_untouched(service, first.id)+ # The turn's fallback is recorded under its own reason; no cooldown or error event exists.+ assert [(event["kind"], event["reason"]) for event in service.events.list()] == [+ ("switch", "unclassified_error")+ ]++ served = await service.resolve(backend="codex", model_id=model, request={}, supply_channel="hub")++ assert served.source_id == first.id+ assert [invocation[0] for invocation in service.adapter.invocations] == [first.id, second.id, first.id]++ asyncio.run(exercise())+++def test_an_unnamed_stream_error_on_the_only_source_ends_the_turn_and_leaves_it_usable(+ tmp_path: Path,+) -> None:+ async def exercise() -> None:+ source = _source("src_primary01", "Primary")+ service = _service(+ tmp_path,+ sources=[source],+ outcomes=[_unnamed_stream_error(source.id), _outcome(RawOutcomeKind.SUCCESS, source_id=source.id)],+ )+ model = _canonicalize_fixed_test_routes(service)["codex"]++ with pytest.raises(ModelHubError) as failed:+ await service.resolve(backend="codex", model_id=model, request={}, supply_channel="hub")++ _assert_source_health_untouched(service, source.id)+ assert service.events.list() == []+ # No Source is blamed: the request could not complete, and the upstream's own words follow.+ assert render_turn_outcome_copy(failed.value.turn_outcome, "en") == " ".join(+ (+ i18n_t("modelHub.launch.waiting_without_retry", "en", model=model),+ i18n_t(+ "modelHub.launch.last_upstream_failure_without_status",+ "en",+ source=source.display_name,+ detail="upstream protocol error",+ ),+ )+ )++ served = await service.resolve(backend="codex", model_id=model, request={}, supply_channel="hub")++ assert served.source_id == source.id++ asyncio.run(exercise())+++def test_gateway_leaves_source_health_alone_for_an_unnamed_stream_error_after_output(+ tmp_path: Path,+) -> None:+ """After output a shaped error keeps its class; with no named class it is event-only, never a rejected+ request (which the engine client's own words, "upstream returned a protocol error event", once made it)."""++ async def exercise() -> None:+ source = _source("src_unnamed01", "Unnamed failure")+ output = (+ b'event: response.output_text.delta\ndata: {"type":'+ b'"response.output_text.delta","sequence_number":1}\n\n'+ )+ service = _service(+ tmp_path,+ sources=[source],+ live_handles=[+ LiveInvokeHandle(+ _unnamed_stream_error(source.id, stream_started=True),+ (+ output,+ b'event: error\ndata: {"type":"error","code":"relay_specific_error",'+ b'"sequence_number":2}\n\n',+ ),+ ),+ LiveInvokeHandle(+ _outcome(RawOutcomeKind.SUCCESS, source_id=source.id, stream_started=True),+ (output, b'event: response.completed\ndata: {"type":"response.completed"}\n\n'),+ ),+ ],+ )+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]+ gateway = ModelHubTurnGateway(service)+ request = _prepared_gateway_request(+ gateway,+ turn_id="turn_unnamed_failure",+ requested_model=requested_model,+ source_id=source.id,+ stream=True,+ )+ with patch(+ "core.handlers.model_hub.turn_gateway.web.StreamResponse",+ return_value=FakeStreamResponse(),+ ):+ await gateway._handle_request(request)++ _assert_source_health_untouched(service, source.id)+ assert service.events.list() == []+ gateway.correlation.settle(+ "turn_unnamed_failure", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat(),+ )+ record = service.provenance.get("turn_unnamed_failure")+ assert record["terminal_error"]["reason"] == "stream_interrupted"++ served = await service.resolve(+ backend="codex", model_id=requested_model, request={}, supply_channel="hub",+ )++ assert served.source_id == source.id+ assert [invocation[0] for invocation in service.adapter.invocations] == [source.id, source.id]++ asyncio.run(exercise())++def test_gateway_meters_a_failed_turn_that_upstream_already_billed(tmp_path: Path,) -> None:diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.pyindex b45309472..22d7bce63 100644--- a/tests/test_model_hub_provenance.py+++ b/tests/test_model_hub_provenance.py@@ -273,7 +273,10 @@ def test_new_terminal_records_retain_only_safe_recognized_error_metadata(model_id="unknown-model",source_id="src_deleted01",)- registry.finish_attempt(turn_id, outcome=outcome, decision=classify_outcome(outcome))+ # The record keeps only safe, recognized metadata whatever the outcome carried; which class the classifier+ # assigns is not under test here (classification reads machine codes, never this text).+ decision = ResolutionDecision("surface", error_code="upstream_request_invalid", downstream_status=400)+ registry.finish_attempt(turn_id, outcome=outcome, decision=decision)registry.settle("turn-error", settled_by=SETTLED_BY_TERMINAL_RESULT)record = store.latest_for_model("claude", MODEL)assert record["terminal_error"] == {diff --git a/tests/test_model_hub_retry_lifecycle.py b/tests/test_model_hub_retry_lifecycle.pyindex 94a02a868..21d87b5b5 100644--- a/tests/test_model_hub_retry_lifecycle.py+++ b/tests/test_model_hub_retry_lifecycle.py@@ -153,6 +153,48 @@ def test_unavailable_production_client_releases_unadmitted_half_open_claim(tmp_pasyncio.run(run())[email protected]("stream", [False, True])+def test_an_unnamed_error_on_a_half_open_attempt_releases_the_claim_and_spares_the_source(tmp_path, stream):+ """Ambiguous evidence writes no Source health (decision 2026-10-11), and it must not keep the half-open slot."""+ async def run():+ service, clock, models = configured_service(tmp_path)+ source = service.store.load().sources[0]+ responses = [+ web.Response(+ status=200,+ content_type="text/event-stream",+ body=b'event: error\ndata: {"type":"error","code":"relay_specific_error",'+ b'"message":"upstream protocol error","param":null,"sequence_number":0}\n\n',+ )+ if stream+ else web.json_response({"error": {"type": "relay_specific_error", "message": "upstream protocol error"}}),+ web.Response(body=WIRE["openai_responses"][3], content_type="application/json"),+ ]++ async def respond(_request):+ return responses.pop(0)++ async with loopback_engine(tmp_path, service, respond):+ await fail(service, source)+ clock.advance(1)+ before = copy.deepcopy(service.store.load().to_payload())+ with pytest.raises(ModelHubError):+ await service.resolve_with_recovery(+ backend="codex", model_id=models["codex"], request={}, stream=stream,+ )+ entry = service.recovery._sources[source.id]+ assert entry.owner is None and entry.failures == 1+ assert service.store.load().to_payload() == before+ assert service.agent_chain("codex", models["codex"])["chain"][0]["recovery"] == "eligible"+ # The next real request can acquire the same half-open admission.+ async with gateway_client(service, "codex", models["codex"]) as (_gateway, client, url, headers):+ async with client.post(url, headers=headers, json={"model": "shared-model"}) as response:+ assert response.status == 200+ assert await response.read() == WIRE["openai_responses"][3]+ assert responses == []+ asyncio.run(run())++@pytest.mark.parametrize("backend", ["codex", "claude"])@pytest.mark.parametrize("diagnostic,delay", [("503 server error", 30), ("429 rate limit", 60), ("quota exhausted", 300), ("connection failed", 0),diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 23de5ae71..be85c33d8 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -6821,6 +6821,111 @@ def test_engine_client_reads_the_class_of_a_responses_stream_failure_wherever_itasyncio.run(run())+_STREAM_OUTPUT = {+ "anthropic": b'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,'+ b'"delta":{"type":"text_delta","text":"Hi"}}\n\n',+ "openai_chat": b'data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hi"}}]}\n\n',+}+# Error frames whose class no taxonomy row names. Their text says "protocol error",+# which classification must not read: only machine codes decide a class.+_UNNAMED_STREAM_ERRORS = {+ "anthropic": b'event: error\ndata: {"type":"error","error":{"type":"relay_specific_error",'+ b'"message":"upstream protocol error"}}\n\n',+ "openai_chat": b'data: {"error":{"type":"relay_specific_error","message":"upstream protocol error"}}\n\n',+}+++async def _stream_outcome(monkeypatch: pytest.MonkeyPatch, protocol: str, body: list[bytes]):+ chunks = list(body)++ class Content:+ async def read(self, _size: int) -> bytes:+ return chunks.pop(0) if chunks else b""++ async def iter_chunked(self, _size: int):+ while chunks:+ yield chunks.pop(0)++ class Response:+ status = 200+ content = Content()+ headers = {"Content-Type": "text/event-stream"}++ def close(self) -> None:+ return None++ class Session:+ async def post(self, *_args, **_kwargs):+ return Response()++ async def close(self) -> None:+ return None++ monkeypatch.setattr(client_module.aiohttp, "ClientSession", lambda **_kwargs: Session())+ source = SourceRecord(+ source_id="src_fixture123",+ vendor="custom",+ protocol=protocol,+ base_url="https://api.example.test/v1",+ credential_ref="cred_fixture123",+ allowed_origins=(),+ model_ids=("model-a",),+ prefix="source-fixture123",+ )+ handle = await EngineClient(+ EngineConnection(+ base_url="http://127.0.0.1:15220",+ management_key="management-key",+ gateway_token="gateway-token",+ )+ ).invoke(source, "model-a", {}, stream=True, request_protocol=protocol)+ if handle.stream is not None:+ assert b"".join([chunk async for chunk in handle.stream]) == b"".join(body)+ return await handle.outcome()++[email protected]("protocol", sorted(_UNNAMED_STREAM_ERRORS))[email protected]("after_output", [False, True], ids=["before-output", "after-output"])+def test_a_stream_error_no_rule_names_is_unclassified_whatever_its_text(+ monkeypatch: pytest.MonkeyPatch,+ protocol: str,+ after_output: bool,+) -> None:+ """The gateway's placeholder, "upstream returned a protocol error event", once made this a rejected request."""++ async def run() -> None:+ body = [*([_STREAM_OUTPUT[protocol]] if after_output else []), _UNNAMED_STREAM_ERRORS[protocol]]+ outcome = await _stream_outcome(monkeypatch, protocol, body)++ assert outcome.kind is RawOutcomeKind.HTTP_ERROR+ assert outcome.stream_started is after_output+ assert outcome.upstream_detail == "upstream protocol error"+ decision = classify_outcome(outcome)+ assert decision.reason == "unclassified_error"+ if after_output:+ assert (decision.action, decision.error_code) == ("surface", "stream_interrupted")+ else:+ assert decision.action == "fallback"++ asyncio.run(run())+++def test_cliproxyapis_claude_timeout_frame_is_a_server_failure(monkeypatch: pytest.MonkeyPatch) -> None:+ """CLIProxyAPI types an upstream 504, and since v8 a 408, as timeout_error in a Claude stream."""++ async def run() -> None:+ outcome = await _stream_outcome(+ monkeypatch,+ "anthropic",+ [b'event: error\ndata: {"type":"error","error":{"type":"timeout_error","message":"upstream timeout"}}\n\n'],+ )++ decision = classify_outcome(outcome)+ assert (decision.action, decision.reason, decision.cooldown_seconds) == ("fallback", "server_error", 30)++ asyncio.run(run())++@pytest.mark.parametrize("invalid_type", [None, [], {}])def test_engine_client_ignores_non_string_stream_event_types(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex cb0e6826d..4e6f7182d 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -296,6 +296,7 @@ MACHINE_ERROR_FAMILY_FIXTURES = {),"server": ("server_error",+ "timeout_error","internal_error","api_error","service_unavailable_error",