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): keep recovery waiting through owed blockers and engine transport failures (#2375)
Call White01d87a4f8f83
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex a7c736624..4eb021670 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -687,6 +687,9 @@ class GatewayTurnTerminalizer:self._attempt_started = Falseself._downstream_canceled = Falseself._recovery_closed = False+ # This request's exit, staged so it commits as one registry write.+ self._staged_exit: dict | None = None+ self._exit_committed = Falseself.on_attribution_released: Callable[[], None] | None = Nonedef __enter__(self) -> "GatewayTurnTerminalizer":@@ -695,6 +698,11 @@ class GatewayTurnTerminalizer:def __exit__(self, exc_type, _exc, _traceback) -> None:if self._downstream_canceled or exc_type is asyncio.CancelledError:return+ self.commit_exit()+ if self._exit_committed:+ # A classified exit is this request's whole ending; the+ # unclassified fallback below is only for requests without one.+ returnself._registry._terminalize_gateway_exit(self.turn_id,request_id=self._request_id,@@ -722,13 +730,7 @@ class GatewayTurnTerminalizer:self,reason: Literal["invalid_parameter", "protocol_error"],) -> None:- self._registry._terminalize_gateway_exit(- self.turn_id,- request_id=self._request_id,- reason=reason,- stream_started=self._stream_started,- force=True,- )+ self._staged_exit = {**(self._staged_exit or {}), "fail_reason": reason}def engine_down(self, *, local_error_detail: str | None = None) -> None:self._registry._terminalize_gateway_exit(@@ -745,12 +747,9 @@ class GatewayTurnTerminalizer:supply_state: SupplyState,blockers: Iterable[ExactHopBlocker] = (),) -> None:- self._registry.mark_gateway_no_candidate(- self.turn_id,- supply_state,- blockers,- request_id=self._request_id,- )+ self._staged_exit = {+ **(self._staged_exit or {}), "no_candidate": (supply_state, tuple(blockers)),+ }def begin_attempt(self,@@ -806,8 +805,28 @@ class GatewayTurnTerminalizer:) -> None:"""Keep the settlement projection attached to the correlated turn event."""- if self.turn_id is not None:- self._registry.record_turn_outcome(self.turn_id, turn_outcome)+ self.commit_exit(turn_outcome, has_outcome=True)++ def commit_exit(+ self,+ turn_outcome: TurnOutcomeProjectionInput | None = None,+ *,+ has_outcome: bool = False,+ ) -> None:+ """Commit this request's staged exit and projection as one write."""++ staged, self._staged_exit = self._staged_exit, None+ if staged is None and not has_outcome:+ return+ self._exit_committed = True+ self._registry.commit_gateway_exit(+ self.turn_id,+ request_id=self._request_id,+ stream_started=self._stream_started,+ turn_outcome=turn_outcome,+ has_outcome=has_outcome,+ **(staged or {}),+ )def mark_downstream_canceled(self) -> None:"""Clear a prepared-only attempt before the outer stopped settlement."""@@ -1842,6 +1861,9 @@ class TurnCorrelationRegistry:**({"local_error_detail": local_error_detail} if local_error_detail else {}),}return+ if self._peer_request_open(trace, request_id):+ trace.pending_attempts.pop(request_id, None)+ returnidentity = trace.pending_attempts.get(request_id)if identity is None and (trace.gateway_source_id is not None@@ -1948,8 +1970,10 @@ class TurnCorrelationRegistry:with self._lock:trace = self._traces.get(turn_id)if trace is not None and not trace.outcome_frozen:- # Only this request found nothing to call; a peer still- # awaiting an upstream result keeps its identity.+ # Only this request found nothing to call.+ if self._peer_request_open(trace, request_id):+ trace.pending_attempts.pop(request_id, None)+ returntrace.pending_attempts.pop(request_id, None)trace.served = Nonetrace.terminal_error = None@@ -1968,6 +1992,43 @@ class TurnCorrelationRegistry:if trace is not None and not trace.outcome_frozen:trace.terminal_outcome = turn_outcome+ def commit_gateway_exit(+ self,+ turn_id: Optional[str],+ *,+ request_id: str,+ stream_started: bool,+ turn_outcome: TurnOutcomeProjectionInput | None = None,+ has_outcome: bool = False,+ no_candidate: tuple[SupplyState, tuple[ExactHopBlocker, ...]] | None = None,+ fail_reason: Literal["invalid_parameter", "protocol_error"] | None = None,+ ) -> None:+ """Commit one gateway request's whole exit under one lock.++ Beside an open peer the exit drops only this request's identity, so+ one exit is either wholly this request's or wholly the turn's.+ """++ if turn_id is None:+ return+ with self._lock:+ trace = self._traces.get(turn_id)+ if trace is None:+ return+ if self._peer_request_open(trace, request_id):+ if not trace.outcome_frozen:+ trace.pending_attempts.pop(request_id, None)+ return+ if no_candidate is not None:+ self.mark_gateway_no_candidate(turn_id, no_candidate[0], no_candidate[1], request_id=request_id)+ if fail_reason is not None:+ self._terminalize_gateway_exit(+ turn_id, request_id=request_id, reason=fail_reason,+ stream_started=stream_started, force=True,+ )+ if has_outcome:+ self.record_turn_outcome(turn_id, turn_outcome)+def begin_attempt(self,turn_id: Optional[str],@@ -2026,6 +2087,18 @@ class TurnCorrelationRegistry:{**identity.payload(), "reason": reason})+ @staticmethod+ def _peer_request_open(trace: TurnTrace, request_id: str) -> bool:+ """Whether another request of this turn is still open.++ Every gateway request arms an identity on arrival, so this covers a+ peer that is waiting as well as one awaiting its upstream result. A+ request ending beside it records only its own exit: the turn settles+ on whichever request ends last.+ """++ return any(key != request_id for key in trace.pending_attempts)+def fail_hub_attempt(self, turn_id: Optional[str]) -> None:"""Replace a gateway success rejected by the backend terminal result."""diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.pyindex 7a38c53b0..e4195694a 100644--- a/core/handlers/model_hub/resolver.py+++ b/core/handlers/model_hub/resolver.py@@ -97,6 +97,20 @@ class ModelHubTurnResolution:recoverable_source_ids: tuple[str, ...] = ()supply_status: SupplyStatus | None = None+ def self_healing_hops(self, supply_channel: str | None) -> tuple[ExactHopInspection, ...]:+ """Blocked hops that may become runnable unattended, for recovery control.++ ``supply_status`` answers whether the user owes an action, so one revoked+ key makes a chain ``interrupted``. Whether a request may wait is a+ different question: any of these hops lets it wait for recovery.+ """++ return tuple(+ hop for hop in self.inspected_hops+ if hop.temporary_blocker+ and (supply_channel is None or hop.source.supply_channel == supply_channel)+ )+@propertydef structural_blocker_reason(self) -> str | None:if self.route_reason == "route_unconfigured":diff --git a/core/handlers/model_hub/retry.py b/core/handlers/model_hub/retry.pyindex 8cf965a3c..fa1bec739 100644--- a/core/handlers/model_hub/retry.py+++ b/core/handlers/model_hub/retry.py@@ -70,6 +70,8 @@ class RecoveryRequest:source_id: str | None = Nonereason: str | None = Noneobserver: Callable[[dict | None], None] | None = None+ # A hard failure this request itself observed ends it with that verdict.+ non_retryable_failure: bool = Falsedef start(self) -> None:if self.started is None:diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex a337905e8..487725b99 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -8161,7 +8161,13 @@ class ModelHubService:backend=cast(BackendName, backend),model_id=model_id,)- turn_outcome = self._produce_no_candidate_terminal_outcome(+ # A request that attempted in an earlier walk exhausted those attempts.+ attempted = recovery_request is not None and recovery_request.attempt_count > 0+ turn_outcome = (+ self._produce_exhausted_terminal_outcome+ if attempted+ else self._produce_no_candidate_terminal_outcome+ )(config=projection_config,resolution=projection_resolution,)@@ -8182,6 +8188,7 @@ class ModelHubService:failed_reason: Optional[EventReason] = Nonewindow_closed = Falsenon_retryable_failure = False+ attempted = Falseglobally_blocked_source_ids: set[str] = set()while True:async with self._mutation_lock:@@ -8226,7 +8233,8 @@ class ModelHubService:settlement_generation = Nonedef admitted(generation: int) -> None:- nonlocal settlement_generation+ nonlocal attempted, settlement_generation+ attempted = Truesettlement_generation = generationif recovery_request is not None:recovery_request.attempt_count += 1@@ -8434,6 +8442,8 @@ class ModelHubService:if recovery_request is not None and decision.reason in RETRY_DELAYS:recovery_request.start()recovery_request.reason = decision.reason+ elif recovery_request is not None:+ recovery_request.non_retryable_failure = Trueevent_reason, _persisted = await self._settle_fallback_source(source,decision,@@ -8456,7 +8466,16 @@ class ModelHubService:backend=cast(BackendName, backend),model_id=model_id,)- turn_outcome = self._produce_exhausted_terminal_outcome(+ # A request that admitted nothing in any walk (another waiter held the+ # half-open slot, or the window closed first) found every hop blocked;+ # it exhausted no attempt of its own.+ attempted = attempted or (recovery_request is not None and recovery_request.attempt_count > 0)+ produce_outcome = (+ self._produce_exhausted_terminal_outcome+ if attempted+ else self._produce_no_candidate_terminal_outcome+ )+ turn_outcome = produce_outcome(config=final_config,resolution=final_resolution,)@@ -8491,6 +8510,7 @@ class ModelHubService:# Explicit opt-out for single-walk probes and characterization tests.return await self.resolve(**kwargs)pending = RecoveryRequest(self.recovery, observer=recovery_observer)+ supply_channel = kwargs.get("supply_channel")try:while True:try:@@ -8500,7 +8520,7 @@ class ModelHubService:if (projection is None or projection.outcome not in {"no_candidate", "exhausted"}or projection.supply_facts is None- or projection.supply_facts.supply_state != "waiting"+ or pending.non_retryable_failure):raisepending.start()@@ -8508,11 +8528,15 @@ class ModelHubService:raise self._recovery_exhausted(exc) from excconfig = self.store.load()resolution = self._invocation_resolution(- config, kwargs["backend"], kwargs["model_id"], kwargs.get("supply_channel"),+ config, kwargs["backend"], kwargs["model_id"], supply_channel,)if resolution.candidate_hops:continue- if resolution.supply_status != "waiting":+ # An action already owed elsewhere in the chain keeps it+ # `interrupted` for display, but must not end this request+ # while another hop may still heal.+ waitable = resolution.self_healing_hops(supply_channel)+ if not waitable:raiseannotations = self.recovery.annotations(config)waits = [@@ -8520,17 +8544,17 @@ class ModelHubService:max(0.0, (parse_model_hub_timestamp(hop.retry_at) - self.now()).total_seconds()),hop,)- for hop in resolution.inspected_hops- if hop.temporary_blocker and hop.recovery != "in_flight" and hop.retry_at+ for hop in waitable+ if hop.recovery != "in_flight" and hop.retry_at]selected = min(waits, key=lambda item: item[0]) if waits else Nonedelay = selected[0] if selected is not None else pending.remainingif delay >= pending.remaining:# Another admitted owner can still wake this request early.- if not any(hop.recovery == "in_flight" for hop in resolution.inspected_hops):+ if not any(hop.recovery == "in_flight" for hop in waitable):raise self._recovery_exhausted(exc) from excdelay = pending.remaining- hop = selected[1] if selected is not None else resolution.inspected_hops[0]+ hop = selected[1] if selected is not None else waitable[0]pending.source_id = hop.source_idannotation = annotations.get(hop.source_id)pending.reason = annotation.reason if annotation else pending.reasondiff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex 20e530c55..53322fc73 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -1435,9 +1435,12 @@ class ModelHubTurnGateway:"""Commit terminal history before deriving any user-visible copy."""if execution.settlement_recorded:+ terminalizer.commit_exit()return execution.rendered_turn_outcome or _RenderedTurnOutcome(None, None)if turn_outcome is not None:terminalizer.record_turn_outcome(turn_outcome)+ else:+ terminalizer.commit_exit()language = self._language_provider() or "en"copy = project_turn_outcome_copy(turn_outcome) if turn_outcome is not None else Nonemessage = render_turn_outcome_copy(turn_outcome, language) if turn_outcome is not None else Nonediff --git a/docs/plans/model-hub-retry-experience.md b/docs/plans/model-hub-retry-experience.mdindex 2f65c79a0..b848d3880 100644--- a/docs/plans/model-hub-retry-experience.md+++ b/docs/plans/model-hub-retry-experience.md@@ -82,7 +82,7 @@ not change a running installation.| --- | --- || Existing Turn / Delivery manager | Own input, native acceptance, queue order, cancellation, final settlement, and explicit user Retry. A waiting subphase is not a new Turn or Delivery. || Existing Model Hub service and resolver | Own classification, configured fallback, per-Source eligibility, backoff, and a shared in-memory recovery admission coordinator. |-| Gateway and runtime router | Gateway consumes the service policy. Router launches an all-temporary Hub chain without pre-native waiting; only the arriving gateway request owns a recovery window. Neither owns a second retry counter. |+| Gateway and runtime router | Gateway consumes the service policy. Router launches a blocked Hub chain with a self-healing hop without pre-native waiting; only the arriving gateway request owns a recovery window. Neither owns a second retry counter. || CPA | Execute the selected attempt. Keep inference request retries disabled; preserve the existing bounded credential-refresh exception. || Native backend | Execute the agent and any supported continuation. For `channel=hub`, redundant whole-HTTP-request retry must be reconciled with Hub ownership. For `native_cli`, Hub cannot control unobserved provider requests. || Web / IM | Render controller-owned progress and terminal facts. Never retry model requests from a view timer. |@@ -109,14 +109,14 @@ model, restart a backend, or change credentials implicitly.### One bounded automatic recovery window-Approved default: **120 seconds per pending model request**, starting-at its first retryable failure or first blocked admission. The same window-covers fallback passes, cooldown waits, and recovery admission; it never resets-because another Source was tried. For an all-temporary Hub chain, preflight-constructs the gateway launch immediately without waiting, starting a recovery-clock, or reserving a half-open slot. The first gateway request then owns its-window. Dispatch acknowledgement and native acceptance retain their existing-owners and deadlines.+Approved default: **120 seconds per pending model request**, starting at its+first retryable failure or first blocked admission. The same window covers+fallback passes, cooldown waits, and recovery admission; it never resets+because another Source was tried. For a blocked Hub chain with a hop that may+heal unattended, preflight constructs the gateway launch immediately without+waiting, starting a recovery clock, or reserving a half-open slot. The first+gateway request then owns its window. Dispatch acknowledgement and native+acceptance retain their existing owners and deadlines.This is an admission limit, not an inference timeout:@@ -132,9 +132,11 @@ This is an admission limit, not an inference timeout:- If the next permitted attempt is beyond the remaining window, end automaticrecovery now and show the next eligible time as advisory. Do not spend twominutes waiting when the recorded quota reset is five minutes away.-- Only an all-temporary blocked chain is an automatic waiting case. Preserve- `interrupted` and its remedies if any blocker needs user action; do not hide- it behind a cooling Source.+- A blocked chain waits while any hop may heal unattended. A blocker that+ needs user action keeps the chain `interrupted`, stays in its live and+ terminal blockers, and its remedy is shown when automatic recovery ends; it+ does not end the wait for a cooling Source. A request that itself observes+ such a failure ends at once with it.Two minutes allows two recovery opportunities after typical 30-second and60-second transient delays while bounding unattended outage waits. It is adiff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex b931809f2..23da7e746 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -710,6 +710,19 @@ start the model-output stream.| `network_failure.shaped_after_first_byte` | explicit closed code/classification arrives only after model output began | `stream_started: true`; after first user-visible model output | apply that existing non-permanent family and its unchanged recovery rule | none | terminal, no replay; emit only the existing redacted event || `network_failure.transport_after_first_byte` | stream interrupted without explicit code | `stream_started: true`; after first user-visible model output | none; the successful connection/authentication/output evidence wins | none | terminal, no replay; emit only the existing redacted `network` event |+The engine answers its own failed upstream connection or read, before any upstream+response, with one of exactly two JSON error bodies, both produced by the pinned+engine's error writers: the Anthropic form+`{"type":"error","error":{"type":"api_error","message":M}}` and the OpenAI form+`{"error":{"type":"server_error","code":"internal_server_error","message":M}}`. The+engine always sets that `code` for a 5xx in the OpenAI form; no code-less form exists.+When `M` is the transport error text, such as `dial tcp ...: i/o timeout` or+`read tcp ...: operation timed out`, that exact body is the engine's label, not an+upstream verdict, so the engine client projects it to+`network_failure.transport_before_first_byte`. An upstream that answered adds or+omits fields (for example a request id, a specific code, or no code), so any other+body, a 4xx, and any streamed error event keep their own classification.+Connection backoff is live execution state, never Source/configuration state. For thesame Source, consecutive `transport_before_first_byte` decisions use delays`1, 2, 4, 8, 16, 30, 30, ...` seconds. While the deadline is future, it overlays only@@ -779,17 +792,21 @@ probe scheduler or prompt/Turn/Source blackout deduplication.Each pending model HTTP request has one 120-second automatic admission window,starting at its first retryable failure or temporarily blocked admission. Fallbackpasses and Source changes never reset it. The service re-reads the effective route-after waits and immediately tries a runnable fallback. It waits only for-all-temporary supply; empty routes and mixed action/process/capability blockers-retain their existing terminal rules. If the next eligibility time is outside+after waits and immediately tries a runnable fallback. It waits while any hop of the+effective chain may heal unattended: an effective cooldown, live connection backoff,+or half-open ownership. A hop that already owes user action keeps the chain+`interrupted` for display and stays in its terminal blockers, but does not end the+wait for another hop. An empty route, a chain with no such hop, or a non-retryable+failure this request itself observed keeps its existing terminal rule. Runtime+preflight launches on the same predicate. If the next eligibility time is outsidethe remaining window, it ends immediately; an in-flight owner may instead wake-waiters before their window closes. Window expiry prevents another admission,-never cancels an already connected slow inference, and never permits replay-after output. Explicit Stop and downstream disconnection retain cancellation.-An expired admission remains the explicit exhausted-recovery domain result even-if another owner recovers or a route changes before this waiter resumes or-finishes engine preparation. An actual admitted request's permanent, request,-engine, or post-output failure retains its own terminal classification.+waiters before their window closes. Window expiry prevents another admission, never+cancels an already connected slow inference, and never permits replay after output.+Explicit Stop and downstream disconnection retain cancellation. An expired admission+remains the explicit exhausted-recovery domain result even if another owner recovers+or a route changes before this waiter resumes or finishes engine preparation. An+actual admitted request's permanent, request, engine, or post-output failure retains+its own terminal classification.Consecutive failed HTTP attempts on the same Hub Source identity use:@@ -814,18 +831,20 @@ timer-generated `recover` events. Unclassified native connection failures remainnon-persistent and do not create a Hub backoff.An eligible affected Source admits one real request as half-open owner across-waiting Sessions. Ownership and stale settlement fencing reuse the existing-attempt-start generation. Cancellation releases that owner only after transport-cleanup; old generations and replaced endpoint/credential identities cannot clear-or extend the new identity's state. A valid recovery clears the streak and emits-one `recover`; mere timer expiry emits none. Live reads expose optional-`recovery: eligible | in_flight` on AgentChain hops. `in_flight` is not runnable;-with no stronger blocker it is temporary `waiting`, with nullable `retry_at`.-The same annotation feeds service, runtime launch, API chain and AgentSupply reads.-If the adapter returns a completed local failure without transport admission,-release the provisional half-open claim on that normal return as well as on-exception or cancellation. Do not synthesize `on_admitted`, attempt observations-or retry counts for a request the engine never owned.+waiting Sessions. A waiter whose walk admits no attempt of its own ends as+`turn.no_candidate.blocked`, never as a gateway protocol error. Ownership and stale+settlement fencing reuse the existing attempt-start generation. Cancellation+releases that owner only after transport cleanup; old generations and replaced+endpoint/credential identities cannot clear or extend the new identity's state. A+valid recovery clears the streak and emits one `recover`; mere timer expiry emits+none. Live reads expose optional `recovery: eligible | in_flight` on AgentChain+hops. `in_flight` is not runnable; with no stronger blocker it is temporary+`waiting`, with nullable `retry_at`. The same annotation feeds service, runtime+launch, API chain and AgentSupply reads. If the adapter returns a completed local+failure without transport admission, release the provisional half-open claim on that+normal return as well as on exception or cancellation. Do not synthesize+`on_admitted`, attempt observations or retry counts for a request the engine never+owned.Temporary cooldown persistence and recovery bookkeeping are observational.A failed write cannot destroy valid output or replace the actual upstream@@ -1108,15 +1127,18 @@ the probe's typed `supply` sibling, the turn record's `model_supply_state` — arollup stays what its name says. One taxonomy, two grains, and only one definition of「稍等即可」 vs 「需处理」 at each.-The predicate itself is stated **once, here**, and every contract that carries either-grain points back at this table rather than restating it: `interrupted` when the chain-is empty **or at least one blocker needs the user**, `waiting` only when every blocker-is an effective cooldown, live connection backoff, or half-open ownership. The asymmetry is deliberate and-load-bearing — `interrupted` is the+The predicate itself is stated **once, here**, and every contract that carries+either grain points back at this table rather than restating it: `interrupted` when+the chain is empty **or at least one blocker needs the user**, `waiting` only when+every blocker is an effective cooldown, live connection backoff, or half-open+ownership. The asymmetry is deliberate and load-bearing — `interrupted` is theOR-branch, `waiting` the AND-branch, so a chain holding one cooling source and one-revoked key is `interrupted`. Reading it as "every member needs the user" leaves that-mixed chain matching neither value and, worse, hides the action the user is owed for-the revoked key behind the fact that something else in the chain is merely cooling.+revoked key is `interrupted`. This answers what the user owes, not whether a pending+request may wait: recovery admission (§ bounded automatic recovery) waits for that+cooling source while the chain still reads `interrupted`. Reading it as "every+member needs the user" leaves that mixed chain matching neither value and, worse,+hides the action the user is owed for the revoked key behind the fact that something+else in the chain is merely cooling.**Surfacing tiers** (the colleague test: ask for action only when action is owed):diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex ae04dd953..c87fe085a 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -615,21 +615,11 @@ class ModelHubRuntimeRouter:supply_channel=supply_channel,live_recovery=self.service.recovery_annotations(config),)- if (- self.turn_gateway is not None and resolution.source is None- and resolution.supply_status == "waiting"- and resolution.inspected_hops- and any(- hop.source is not None and hop.source.supply_channel == "hub"- for hop in resolution.inspected_hops- )- ):+ waitable = resolution.self_healing_hops("hub")+ if self.turn_gateway is not None and resolution.source is None and waitable:# Preflight prepares the existing native delivery. Its first model# request owns recovery admission; no second startup wait/window.- first = next(- hop for hop in resolution.inspected_hops- if hop.source is not None and hop.source.supply_channel == "hub"- )+ first = waitable[0]resolution = replace(resolution, channel="hub", source=first.source,target_model=first.model_id or requested_model,diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 9f71f3dd0..d5760d723 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -193,6 +193,36 @@ scenarios:kind: recoverylayer: unittest: tests/test_model_hub_retry_lifecycle.py::test_expiry_after_mixed_real_failures_keeps_the_action_blocker_terminal+ - id: MH-RETRY-MIXED-001+ name: A chain waits for a self-healing hop while another hop already owes user action+ status: covered+ kind: recovery+ layer: unit+ test: tests/test_model_hub_retry_policy.py::test_draft_preview_does_not_clear_live_health_and_mixed_chain_waits_for_the_healing_hop+ related_tests:+ - tests/test_model_hub_retry_policy.py::test_startup_passes_temporary_hub_supply_without_spending_another_window+ - id: MH-RETRY-TRANSPORT-001+ name: The engine's generic 5xx for its own failed upstream connection takes network recovery+ status: covered+ kind: contract+ layer: unit+ test: tests/test_model_hub_runtime.py::test_engine_reported_upstream_transport_failure_takes_network_recovery+ - id: MH-RETRY-PROVENANCE-001+ name: A waiter that never admits an attempt records blocked supply, not a gateway protocol error+ status: covered+ kind: recovery+ layer: unit+ test: tests/test_model_hub_retry_lifecycle.py::test_waiters_without_an_attempt_record_blocked_supply_not_a_protocol_error+ related_tests:+ - tests/test_model_hub_retry_policy.py::test_a_request_that_attempted_keeps_exhausted_after_a_peer_takes_the_slot+ - id: MH-RETRY-PROVENANCE-003+ name: A request ending beside an open peer request leaves the turn's outcome to that peer+ status: covered+ kind: contract+ layer: unit+ test: tests/test_model_hub_l3.py::test_a_request_ending_beside_an_open_peer_leaves_the_turn_to_that_peer+ related_tests:+ - tests/test_model_hub_retry_lifecycle.py::test_a_waiter_ending_beside_the_slot_owner_leaves_no_turn_projection- id: MH-RETRY-ADVICE-001name: Failed HTTP advice retains the receipt clock across delayed or broken bodiesstatus: covereddiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 31598a5e1..f8d482a9e 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -1943,6 +1943,79 @@ def test_a_canceled_turn_reports_the_attempt_it_waited_on_longest(}[email protected]("peer", ["open_at_commit", "closed_before_commit", "opened_before_commit"])[email protected]("peer_result", ["served", "exhausted"])[email protected]("loser_exit", ["no_candidate", "gateway_exit"])+def test_a_request_ending_beside_an_open_peer_leaves_the_turn_to_that_peer(+ tmp_path: Path,+ loser_exit: str,+ peer_result: str,+ peer: str,+) -> None:+ """MH-RETRY-PROVENANCE-003: one request's exit is wholly its own or wholly the turn's.++ A waiter that lost the half-open slot ends beside the request that won it.+ Its staged exit commits as one write: beside an open peer it leaves the+ turn to that peer; as the last request to end it is the turn's ending.+ """++ store = BoundedProvenanceStore(tmp_path / "routing-peer.json")+ registry = TurnCorrelationRegistry(store)+ token = registry.credentials("claude", "session:/repo", "turn_peer01")+ live_token = _prepare_route(+ registry,+ token,+ turn_id="turn_peer01",+ requested="caller-live",+ resolved="hub-live",+ )+ result = (+ _outcome(RawOutcomeKind.SUCCESS)+ if peer_result == "served"+ else _outcome(RawOutcomeKind.HTTP_ERROR, status=500, code="server_error")+ )+ projection = produce_turn_outcome("turn.engine_down")++ def open_peer():+ terminalizer = registry.gateway_terminalizer(backend="claude", token=live_token)+ assert terminalizer.resolution_model("hub-live") == "caller-live"+ terminalizer.begin_attempt(+ source_id="src_primary01", resolved_model_id="hub-live", channel="hub", via_mapping=True,+ )+ return terminalizer++ winner = open_peer() if peer != "opened_before_commit" else None+ with registry.gateway_terminalizer(backend="claude", token=live_token) as loser:+ assert loser.resolution_model("hub-live") == "caller-live"+ if loser_exit == "no_candidate":+ loser.mark_no_candidate("waiting")+ else:+ loser.fail("protocol_error")+ if peer == "closed_before_commit":+ winner.finish_attempt(outcome=result, decision=classify_outcome(result))+ winner.__exit__(None, None, None)+ elif peer == "opened_before_commit":+ winner = open_peer()+ loser.record_turn_outcome(projection)+ if peer != "closed_before_commit":+ # The loser left the turn to its peer: no projection of its own remains.+ assert registry.terminal_projection("turn_peer01", backend="claude") is None+ winner.finish_attempt(outcome=result, decision=classify_outcome(result))+ winner.__exit__(None, None, None)+ registry.settle("turn_peer01", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())++ record = store.get("turn_peer01")+ assert record is not None+ if peer == "closed_before_commit":+ # The loser ended last, so its whole exit is the turn's.+ assert record["outcome"] == ("no_candidate" if loser_exit == "no_candidate" else "failed_terminal")+ assert (record["model_supply_state"] is not None) is (loser_exit == "no_candidate")+ else:+ assert record["outcome"] == peer_result+ assert record["terminal_error"] is None+ assert record["model_supply_state"] is None++def test_an_unclaimed_request_leaves_no_attempt_on_the_live_turn(tmp_path: Path,) -> None:diff --git a/tests/test_model_hub_retry_lifecycle.py b/tests/test_model_hub_retry_lifecycle.pyindex e2e1bc611..94a02a868 100644--- a/tests/test_model_hub_retry_lifecycle.py+++ b/tests/test_model_hub_retry_lifecycle.py@@ -641,6 +641,73 @@ def test_expiry_after_mixed_real_failures_keeps_the_action_blocker_terminal(tmp_asyncio.run(run())[email protected]("backend", ["codex", "claude"])+def test_waiters_without_an_attempt_record_blocked_supply_not_a_protocol_error(tmp_path, backend):+ """MH-RETRY-PROVENANCE-001: losing the half-open slot is blocked supply, not a gateway fault."""+ async def run():+ service, clock, models = configured_service(tmp_path)+ service.store = FreshStore(service.store.load())+ source = service.store.load().sources[0]+ await fail(service, source, "server_error")+ clock.advance(31)+ claim = service.recovery.claim+ peers = []++ def a_peer_claims_first(candidate, generation):+ # Another waiter wins the eligible slot between inspection and claim.+ if not peers:+ peers.append(claim(candidate, service._reserve_settlement_generation(candidate.id)))+ return claim(candidate, generation)++ service.recovery.claim = a_peer_claims_first+ async with gateway_client(service, backend, models[backend]) as (gateway, client, url, headers):+ async with client.post(url, headers=headers, json={"model": "shared-model"}) as response:+ assert response.status == (400 if backend == "codex" else 424)+ gateway.correlation.settle("turn_lifecycle", settled_by=SETTLED_BY_TERMINAL_RESULT)+ record = service.provenance.get("turn_lifecycle")+ assert peers == [True] and service.adapter.invocations == []+ assert (record["outcome"], record["model_supply_state"]) == ("no_candidate", "waiting")+ assert record["terminal_error"] is None and record["failed_attempts"] == []+ asyncio.run(run())++[email protected]("backend", ["codex", "claude"])+def test_a_waiter_ending_beside_the_slot_owner_leaves_no_turn_projection(tmp_path, backend):+ """MH-RETRY-PROVENANCE-003: the gateway commits a peer-scoped ending only for its own request."""+ async def run():+ service, clock, models = configured_service(tmp_path, outcomes=[+ _outcome(RawOutcomeKind.SUCCESS, source_id="src_recovery01"),+ ])+ source = service.store.load().sources[0]+ await fail(service, source, "server_error")+ clock.advance(31)+ release = asyncio.Event()+ original_invoke = service.adapter.invoke++ async def owner_waits_upstream(*args, **kwargs):+ handle = await original_invoke(*args, **kwargs)+ await release.wait()+ return handle++ service.adapter.invoke = owner_waits_upstream+ async with gateway_client(service, backend, models[backend]) as (gateway, client, url, headers):+ async def post():+ async with client.post(url, headers=headers, json={"model": "shared-model"}) as response:+ return response.status++ owner = asyncio.create_task(post())+ while not service.adapter.invocations:+ await asyncio.sleep(0.01)+ assert await post() == (400 if backend == "codex" else 424)+ release.set()+ assert await owner == 200+ assert gateway.correlation.terminal_projection("turn_lifecycle", backend=backend) is None+ gateway.correlation.settle("turn_lifecycle", settled_by=SETTLED_BY_TERMINAL_RESULT)+ record = service.provenance.get("turn_lifecycle")+ assert record["outcome"] == "served" and record["model_supply_state"] is None+ asyncio.run(run())++KEEPALIVE = b": keepalive\n\n"diff --git a/tests/test_model_hub_retry_policy.py b/tests/test_model_hub_retry_policy.pyindex 1695eaa77..b51c9f2c3 100644--- a/tests/test_model_hub_retry_policy.py+++ b/tests/test_model_hub_retry_policy.py@@ -252,12 +252,21 @@ def test_one_window_covers_all_fallback_passes_without_replaying_after_output(tmasyncio.run(run())[email protected]("action_sibling", [None, "before", "after"])@pytest.mark.parametrize("backend", ["codex", "claude", "opencode"])-def test_startup_passes_temporary_hub_supply_without_spending_another_window(tmp_path, backend):+def test_startup_passes_temporary_hub_supply_without_spending_another_window(tmp_path, backend, action_sibling):async def run():- service, clock = clock_service(tmp_path)+ cooling = _source("src_recovery01", "Recovering")+ sources = [cooling]+ if action_sibling is not None:+ action = _source("src_backup001", "Backup")+ action.state = ModelHubSourceStateConfig(+ status="needs_action", detail_key="models.source.needs_action.credential_revoked",+ )+ sources = [action, cooling] if action_sibling == "before" else [cooling, action]+ service, clock = clock_service(tmp_path, sources=sources)models = _canonicalize_fixed_test_routes(service)- source = service.store.load().sources[0]+ source = next(item for item in service.store.load().sources if item.id == cooling.id)await fail(service, source)gateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")@@ -512,22 +521,55 @@ def test_permissive_success_releases_admission_without_verified_recovery(tmp_patasyncio.run(run())-def test_draft_preview_does_not_clear_live_health_and_mixed_action_blocks_waiting(tmp_path):[email protected]("action_first", [False, True])+def test_draft_preview_does_not_clear_live_health_and_mixed_chain_waits_for_the_healing_hop(+ tmp_path, action_first,+):+ """MH-RETRY-MIXED-001: an action owed elsewhere cannot end the wait for a healing hop."""async def run():- first, second = _source("src_primary01", "Primary"), _source("src_backup001", "Backup")- service, clock = clock_service(tmp_path, sources=[first, second])- await fail(service, first)+ cooling, action = _source("src_primary01", "Primary"), _source("src_backup001", "Backup")+ service, clock = clock_service(+ tmp_path,+ sources=[action, cooling] if action_first else [cooling, action],+ outcomes=[_outcome(RawOutcomeKind.SUCCESS, source_id=cooling.id, stream_started=True)],+ )+ await fail(service, cooling)draft = copy.deepcopy(service.store.load())- draft.sources[0].credential_ref = "cred_draft"- assert first.id not in service.recovery_annotations(draft)- assert first.id in service.recovery_annotations(service.store.load())- second.state = ModelHubSourceStateConfig(+ draft.sources[1 if action_first else 0].credential_ref = "cred_draft"+ assert cooling.id not in service.recovery_annotations(draft)+ assert cooling.id in service.recovery_annotations(service.store.load())+ action.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.credential_revoked",)- with pytest.raises(ModelHubError) as failed:+ assert service.agent_chain("codex", "shared-model")["supply_state"] == "interrupted"+ result = await service.resolve_with_recovery(backend="codex", model_id="shared-model", request={})+ assert result.source_id == cooling.id and result.outcome.kind is RawOutcomeKind.SUCCESS+ assert clock.delays == [1]+ assert [source_id for source_id, *_ in service.adapter.invocations] == [cooling.id]+ asyncio.run(run())+++def test_a_request_that_attempted_keeps_exhausted_after_a_peer_takes_the_slot(tmp_path):+ """MH-RETRY-PROVENANCE-001: attempts from an earlier walk are still this request's own."""+ async def run():+ service, clock = clock_service(tmp_path, outcomes=[+ _outcome(RawOutcomeKind.HTTP_ERROR, source_id="src_recovery01", status=500, code="server_error"),+ ])+ source_id = service.store.load().sources[0].id+ wait_for_eligibility = service.recovery.sleep++ async def a_peer_claims_on_eligibility(seconds):+ await wait_for_eligibility(seconds)+ # A concurrent request wins the half-open slot and keeps it.+ source = next(item for item in service.store.load().sources if item.id == source_id)+ service.recovery.claim(source, service._reserve_settlement_generation(source_id))++ service.recovery.sleep = a_peer_claims_on_eligibility+ with pytest.raises(ModelHubError) as ended:await service.resolve_with_recovery(backend="codex", model_id="shared-model", request={})- assert failed.value.supply_state == "interrupted"- assert clock.delays == [] and service.adapter.invocations == []+ assert ended.value.code == RECOVERY_EXHAUSTED_CODE+ assert ended.value.turn_outcome.outcome == "exhausted"+ assert len(service.adapter.invocations) == 1asyncio.run(run())diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 89d3b45a3..c2b16a00f 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -7282,6 +7282,154 @@ def test_engine_buffered_2xx_error_envelope_carries_upstream_detail() -> None:assert outcome.upstream_detail == "model retired"+_ANTHROPIC_OUTPUT_STARTED = (+ b'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","type":"message",'+ b'"role":"assistant","content":[],"model":"model-a","usage":{"input_tokens":1,"output_tokens":0}}}\n\n'+ b'event: content_block_start\ndata: {"type":"content_block_start","index":0,'+ b'"content_block":{"type":"text","text":""}}\n\n'+ b'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,'+ b'"delta":{"type":"text_delta","text":"partial"}}\n\n'+)+++ "protocol,stream,status,body,kind,stream_started,reason",+ [+ # CPA's own Anthropic-shaped answer when the upstream read times out.+ (+ "anthropic", False, 500,+ {"type": "error", "error": {"type": "api_error", "message": (+ "read tcp 192.168.2.3:56860->47.131.95.123:443: read: operation timed out"+ )}},+ RawOutcomeKind.NETWORK_ERROR, False, "network",+ ),+ # CPA's OpenAI-shaped answer when the upstream connection cannot be made.+ (+ "openai_responses", False, 500,+ {"error": {"type": "server_error", "code": "internal_server_error", "message": (+ 'Post "https://relay.example.test/v1/responses": dial tcp 203.0.113.7:443: i/o timeout'+ )}},+ RawOutcomeKind.NETWORK_ERROR, False, "network",+ ),+ # After output the turn is already lost; the stream keeps its class.+ (+ "anthropic", True, 200,+ _ANTHROPIC_OUTPUT_STARTED + (+ b'event: error\ndata: {"type":"error","error":{"type":"api_error",'+ b'"message":"unexpected EOF"}}\n\n'+ ),+ RawOutcomeKind.HTTP_ERROR, True, "server_error",+ ),+ # An upstream that answered adds its own fields beyond the engine's shape.+ (+ "anthropic", False, 500,+ {"type": "error", "request_id": "req_011", "error": {"type": "api_error", "message": (+ "read tcp 10.0.0.2:443: read: connection reset by peer"+ )}},+ RawOutcomeKind.HTTP_ERROR, False, "server_error",+ ),+ (+ "openai_responses", False, 500,+ {"error": {"type": "server_error", "code": "vendor_backend_down", "message": (+ "dial tcp 203.0.113.7:443: i/o timeout"+ )}},+ RawOutcomeKind.HTTP_ERROR, False, "server_error",+ ),+ # An upstream that answered keeps its own server verdict.+ (+ "anthropic", False, 500,+ {"type": "error", "error": {"type": "api_error", "message": "Internal server error"}},+ RawOutcomeKind.HTTP_ERROR, False, "server_error",+ ),+ (+ "anthropic", False, 529,+ {"type": "error", "error": {"type": "overloaded_error", "message": "read tcp: connection reset by peer"}},+ RawOutcomeKind.HTTP_ERROR, False, "server_error",+ ),+ (+ "openai_responses", False, 400,+ {"error": {"type": "invalid_request_error", "message": "image fetch failed: connection refused"}},+ RawOutcomeKind.HTTP_ERROR, False, None,+ ),+ # Without the engine's generic type the body is not the engine's own label.+ (+ "openai_responses", False, 500,+ {"error": {"message": "connection refused"}},+ RawOutcomeKind.HTTP_ERROR, False, "server_error",+ ),+ ],+ ids=[+ "anthropic-read-timeout",+ "responses-dial-timeout",+ "anthropic-mid-stream-eof",+ "anthropic-upstream-request-id",+ "responses-unknown-specific-code",+ "anthropic-upstream-500",+ "anthropic-overloaded",+ "responses-request-error",+ "responses-untyped-500",+ ],+)+def test_engine_reported_upstream_transport_failure_takes_network_recovery(+ protocol: str,+ stream: bool,+ status: int,+ body: object,+ kind: RawOutcomeKind,+ stream_started: bool,+ reason: str | None,+) -> None:+ """MH-RETRY-TRANSPORT-001: the engine's own transport failure takes network recovery."""++ from aiohttp import web++ async def run():+ async def respond(_request: web.Request) -> web.Response:+ if isinstance(body, bytes):+ return web.Response(status=status, body=body, content_type="text/event-stream")+ return web.json_response(body, status=status)++ app = web.Application()+ app.router.add_post("/{path:.*}", respond)+ runner = web.AppRunner(app)+ await runner.setup()+ await web.TCPSite(runner, "127.0.0.1", 0).start()+ try:+ handle = await EngineClient(+ EngineConnection(+ base_url=f"http://127.0.0.1:{runner.addresses[0][1]}",+ management_key="management-key",+ gateway_token="gateway-token",+ )+ ).invoke(+ SourceRecord(+ source_id="src_fixture123",+ vendor="custom",+ protocol=protocol,+ base_url="https://api.example.test",+ credential_ref="cred_fixture123",+ allowed_origins=(),+ model_ids=("model-a",),+ prefix="source-fixture123",+ ),+ "model-a",+ {"stream": stream},+ stream=stream,+ )+ if handle.stream is not None:+ async for _chunk in handle.stream:+ pass+ return await handle.outcome()+ finally:+ await runner.cleanup()++ outcome = asyncio.run(run())++ assert outcome.kind is kind+ assert outcome.stream_started is stream_started+ assert classify_outcome(outcome).reason == reason++@pytest.mark.parametrize("payload",[diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 8c6fd9699..5e162d1ea 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -4,6 +4,7 @@ import asyncioimport ioimport jsonimport logging+import reimport socketimport tempfileimport time@@ -53,6 +54,16 @@ from vibe.model_hub_runtime.state import SourceRecord_STREAM_CHUNK_BYTES = 64 * 1024# Upper bound on upstream error text shown to the user in a terminal message._UPSTREAM_DETAIL_CHARS = 400+# The engine answers a failed upstream connection itself, before any upstream+# response, with exactly its own generic envelope and Go's transport error text.+# That is a network fact, not an upstream server verdict.+_ENGINE_TRANSPORT_FAILURE = re.compile(+ r"\b(?:dial|read|write) (?:tcp|udp)\b|i/o timeout|connection reset by peer|"+ r"connection refused|broken pipe|\bunexpected EOF\b|: EOF$|TLS handshake timeout|"+ r"Client\.Timeout exceeded|context deadline exceeded|timeout awaiting response headers|"+ r"http2: (?:client connection lost|server sent GOAWAY)|server closed idle connection|"+ r"no such host|network is unreachable|proxyconnect"+)# This threshold only selects memory or a temporary file; it never rejects or# truncates upstream response bytes._PRELUDE_MEMORY_BYTES = 256 * 1024@@ -1580,6 +1591,32 @@ def _reduce_protocol_observation(observation.error_payload or b"",observation.error_envelope_paths,)+ upstream_detail = (+ _bounded_upstream_detail(observation.error_message)+ if observation.error_message is not None+ else _upstream_error_detail(+ observation.error_payload or b"",+ observation.error_envelope_paths or (("error",),),+ )+ )+ if (+ http_status is not None and http_status >= 500+ and observation.error_payload+ and _engine_transport_failure(observation.error_payload, observation.error_envelope_paths)+ ):+ # The generic type is the engine's label for its own failure, so no+ # machine code is carried that could outrank the network fact.+ return _outcome(+ kind=RawOutcomeKind.NETWORK_ERROR,+ source=source,+ model_id=model_id,+ http_status=http_status,+ message="engine could not reach the upstream",+ stream_started=stream_started,+ usage=observation.usage,+ recovery_verified=observation.recovery_verified,+ upstream_detail=upstream_detail,+ )return _outcome(kind=RawOutcomeKind.HTTP_ERROR,source=source,@@ -1592,14 +1629,7 @@ def _reduce_protocol_observation(stream_started=stream_started,usage=observation.usage,recovery_verified=observation.recovery_verified,- upstream_detail=(- _bounded_upstream_detail(observation.error_message)- if observation.error_message is not None- else _upstream_error_detail(- observation.error_payload or b"",- observation.error_envelope_paths or (("error",),),- )- ),+ upstream_detail=upstream_detail,)return _outcome(kind=RawOutcomeKind.PROTOCOL_ERROR,@@ -1613,6 +1643,31 @@ def _reduce_protocol_observation()+def _engine_transport_failure(payload: bytes, envelope_paths: tuple[ErrorEnvelopePath, ...]) -> bool:+ """Whether an error body is exactly the engine's own envelope for a transport failure.++ An upstream that answered adds its own fields (a request id, a specific code),+ so only a body equal to one of the engine's two shapes qualifies.+ """++ try:+ document = json.loads(payload)+ except (UnicodeDecodeError, ValueError):+ return False+ for path in envelope_paths or (("error",),):+ message: object = document+ for key in (*path, "message"):+ message = message.get(key) if isinstance(message, dict) else None+ if not isinstance(message, str) or not _ENGINE_TRANSPORT_FAILURE.search(message):+ continue+ if document in (+ {"type": "error", "error": {"type": "api_error", "message": message}},+ {"error": {"type": "server_error", "code": "internal_server_error", "message": message}},+ ):+ return True+ return False++def _protocol_error_outcome(observation: ProtocolObservation,source: SourceRecord,