Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): retain attributed outcomes across turn completion (#1900)

Call White67cb0bc31361
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index 465966260..ae4e84df9 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -10,7 +10,7 @@ import threading
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Iterable, Literal, Mapping, Optional
+from typing import Any, Callable, Iterable, Literal, Mapping, Optional
from config.v2_config import ModelHubConfig
@@ -530,6 +530,8 @@ class TurnTrace:
gateway_model_id: Optional[str] = None
ambiguous: bool = False
terminal_outcome: TurnOutcomeProjectionInput | None = None
+ admission_closed: bool = False
+ outcome_frozen: bool = False
@property
def pending_attempt(self) -> Optional[AttemptIdentity]:
@@ -613,6 +615,7 @@ class GatewayTurnTerminalizer:
self._stream_started = False
self._attempt_started = False
self._downstream_canceled = False
+ self.on_attribution_released: Callable[[], None] | None = None
def __enter__(self) -> "GatewayTurnTerminalizer":
return self
@@ -637,6 +640,9 @@ class GatewayTurnTerminalizer:
gateway_model_id=gateway_model_id,
)
self.turn_id = routing.owner_turn_id
+ if self.turn_id is None and self.on_attribution_released is not None:
+ release, self.on_attribution_released = self.on_attribution_released, None
+ release()
return routing.caller_model_id
def fail(
@@ -950,13 +956,13 @@ class TurnCorrelationRegistry:
for turn_id in scope.active_turns:
trace = self._traces.get(turn_id)
terminal_is_exact = (
- turn_id == normalized_terminal_turn_id
- and trace is not None
+ trace is not None
+ and (turn_id == normalized_terminal_turn_id or trace.admission_closed)
and not trace.ambiguous
and not scope.untracked_use
and scope.active_turns == {turn_id}
and turn_id not in scope.ambiguous_turns
- and bool(trace.failed_attempts or trace.terminal_error)
+ and bool(trace.failed_attempts or trace.terminal_error or (trace.admission_closed and trace.served))
)
if terminal_is_exact:
turn_scopes = self._turn_scopes.get(turn_id)
@@ -981,7 +987,7 @@ class TurnCorrelationRegistry:
if turn_id in scope.ambiguous_turns:
return None
trace = self._traces.get(turn_id)
- if trace is not None and trace.ambiguous:
+ if trace is not None and (trace.ambiguous or trace.admission_closed):
return None
return turn_id, key
@@ -1142,6 +1148,17 @@ class TurnCorrelationRegistry:
if prepared_turn_id is None:
return GatewayRouting(caller_model_id, None)
if claimed:
+ trace = self._traces.get(prepared_turn_id)
+ if (
+ trace is not None
+ and trace.admission_closed
+ and not trace.ambiguous
+ and request_id in trace.pending_attempts
+ and gateway_model_id in {trace.gateway_request_model_id, trace.gateway_model_id}
+ ):
+ # This request acquired its identity before the FSM closed
+ # admission; completing its body parse is not a new claim.
+ return GatewayRouting(caller_model_id, prepared_turn_id)
owner = self.begin_gateway_request(
backend=backend,
token=token,
@@ -1282,7 +1299,7 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(turn_id)
- if trace is None:
+ if trace is None or trace.outcome_frozen:
return
identity = trace.pending_attempts.get(request_id)
if identity is not None and identity.channel == "hub":
@@ -1305,7 +1322,7 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(turn_id)
- if trace is None or trace.ambiguous:
+ if trace is None or trace.ambiguous or trace.outcome_frozen:
return
if not force and (
trace.served is not None
@@ -1428,7 +1445,7 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(turn_id)
- if trace is not None:
+ 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.
trace.pending_attempts.pop(request_id, None)
@@ -1446,7 +1463,7 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(turn_id)
- if trace is not None:
+ if trace is not None and not trace.outcome_frozen:
trace.terminal_outcome = turn_outcome
def begin_attempt(
@@ -1465,7 +1482,7 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(turn_id)
- if trace is None:
+ if trace is None or trace.outcome_frozen:
return
trace.pending_attempts[request_id] = AttemptIdentity(
source_id=source_id,
@@ -1493,7 +1510,7 @@ class TurnCorrelationRegistry:
if trace is not None
else None
)
- if trace is None or identity is None or identity.channel != "native_cli":
+ if trace is None or trace.outcome_frozen or identity is None or identity.channel != "native_cli":
return
trace.pending_attempts.pop(TURN_REQUEST, None)
trace.served = None
@@ -1510,8 +1527,9 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(normalized)
- if trace is None:
+ if trace is None or trace.outcome_frozen:
return
+ trace.outcome_frozen = True
identity = trace.pending_attempt
payload = (
identity.payload()
@@ -1553,7 +1571,7 @@ class TurnCorrelationRegistry:
identity = (
trace.pending_attempts.get(request_id) if trace is not None else None
)
- if trace is None or identity is None:
+ if trace is None or trace.outcome_frozen or identity is None:
return
trace.pending_attempts.pop(request_id, None)
if decision.action == "return":
@@ -1584,6 +1602,19 @@ class TurnCorrelationRegistry:
"upstream_error_code": diagnostic_code,
}
+ def close_turn_admission(self, turn_id: str, *, settled_by: Optional[str]) -> None:
+ """Latch the FSM boundary without discarding already-owned requests."""
+
+ with self._lock:
+ trace = self._traces.get(str(turn_id or "").strip())
+ if trace is None or trace.admission_closed:
+ return
+ trace.admission_closed = True
+ if settled_by == SETTLED_BY_STOPPED:
+ # Preserve the exact facts present at Stop. Teardown may expose
+ # a later producer success, but cannot change who ended the turn.
+ trace.outcome_frozen = True
+
def settle(self, turn_id: str, *, settled_by: Optional[str], ts: Optional[str] = None) -> None:
normalized_turn_id = str(turn_id or "").strip()
if not normalized_turn_id:
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 4ed0403aa..74b4a4cf6 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -9,7 +9,7 @@ import socket
import tempfile
from collections import deque
from collections.abc import Callable, Mapping
-from contextlib import AsyncExitStack, suppress
+from contextlib import AsyncExitStack, contextmanager, suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import BinaryIO, Final, Optional
@@ -17,6 +17,7 @@ from typing import BinaryIO, Final, Optional
from aiohttp import web
from config import paths
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
from vibe.i18n import t as i18n_t
from .adapter import (
@@ -25,7 +26,7 @@ from .adapter import (
RawCallOutcome,
RawOutcomeKind,
)
-from .async_owner import run_owned_in_thread
+from .async_owner import await_owned_task, run_owned_in_thread
from .classification import ResolutionDecision
from .provenance import (
BoundedProvenanceStore,
@@ -240,6 +241,14 @@ class _DownstreamDisconnected(ConnectionError):
pass
+@dataclass(eq=False)
+class _OwnedGatewayRequest:
+ task: asyncio.Task
+ terminalizer: GatewayTurnTerminalizer
+ execution: _TurnExecution
+ done: asyncio.Future[None]
+
+
class ModelHubTurnGateway:
"""Expose the controller-owned resolver to backend CLI HTTP clients."""
@@ -287,6 +296,101 @@ class ModelHubTurnGateway:
self._runner: web.AppRunner | None = None
self._site: web.SockSite | None = None
self._base_url: str | None = None
+ self._turn_requests: dict[str, set[_OwnedGatewayRequest]] = {}
+ self._turn_completions: dict[str, asyncio.Task[None]] = {}
+
+ @contextmanager
+ def _own_turn_request(self, terminalizer: GatewayTurnTerminalizer, execution: _TurnExecution):
+ turn_id = terminalizer.turn_id
+ if turn_id is None:
+ yield
+ return
+ task = asyncio.current_task()
+ assert task is not None
+ owned = _OwnedGatewayRequest(task, terminalizer, execution, asyncio.get_running_loop().create_future())
+ self._turn_requests.setdefault(turn_id, set()).add(owned)
+ # Body attribution may release the identity armed from headers. That
+ # request still routes, but the turn no longer owns its transport.
+ terminalizer.on_attribution_released = lambda: self._release_turn_request(turn_id, owned)
+ try:
+ yield
+ finally:
+ terminalizer.on_attribution_released = None
+ self._release_turn_request(turn_id, owned)
+
+ def _release_turn_request(self, turn_id: str, owned: _OwnedGatewayRequest) -> None:
+ requests = self._turn_requests.get(turn_id)
+ if requests is not None:
+ requests.discard(owned)
+ if not requests:
+ self._turn_requests.pop(turn_id, None)
+ if not owned.done.done():
+ owned.done.set_result(None)
+
+ def finalize_turn(
+ self,
+ turn_id: str,
+ *,
+ settled_by: str | None,
+ finish: Callable[[], None],
+ ) -> asyncio.Task[None] | None:
+ """Join the FSM boundary with every already-owned request boundary."""
+
+ existing = self._turn_completions.get(turn_id)
+ if existing is not None:
+ return existing
+ self.correlation.close_turn_admission(turn_id, settled_by=settled_by)
+ if not self._turn_requests.get(turn_id):
+ finish()
+ return None
+
+ async def complete() -> None:
+ try:
+ drain = asyncio.create_task(self._drain_turn_requests(
+ turn_id, cancel=settled_by != SETTLED_BY_TERMINAL_RESULT
+ ))
+ await await_owned_task(drain)
+ finally:
+ try:
+ finish()
+ finally:
+ self._turn_completions.pop(turn_id, None)
+
+ task = asyncio.create_task(complete(), name="model-hub-turn-finalization")
+ self._turn_completions[turn_id] = task
+ return task
+
+ async def _drain_turn_requests(self, turn_id: str, *, cancel: bool = False) -> None:
+ requests = tuple(self._turn_requests.get(turn_id, ()))
+ if not requests:
+ return
+ if cancel:
+ for owned in requests:
+ owned.task.cancel()
+ _, pending = await asyncio.wait(
+ {owned.done for owned in requests}, timeout=self._transport_timeout
+ )
+ if not pending:
+ return
+ # Reuse the request boundary's cancellation/teardown budget. Waiting on
+ # its completion signal includes terminalizer exit, not just attempts.
+ pending = {future for future in pending if not future.done()}
+ if not pending:
+ return
+ for owned in requests:
+ if owned.done in pending:
+ owned.task.cancel()
+ _, pending = await asyncio.wait(pending, timeout=self._transport_timeout)
+ for owned in requests:
+ if owned.done not in pending or owned.done.done():
+ continue
+ self._abandon_owned_task(
+ owned.task, phase="request", terminalizer=owned.terminalizer, execution=owned.execution
+ )
+ # An abandoned worker cannot publish late facts into this or a
+ # subsequent turn after the bounded owner has released its slot.
+ owned.terminalizer.turn_id = None
+ self._release_turn_request(turn_id, owned)
@property
def resource_leak_records(self) -> tuple[tuple[str, str | None], ...]:
@@ -357,8 +461,17 @@ class ModelHubTurnGateway:
self._runner = None
self._site = None
self._base_url = None
+ if self._turn_requests:
+ await asyncio.gather(*(
+ self._drain_turn_requests(turn_id, cancel=True)
+ for turn_id in tuple(self._turn_requests)
+ ))
if runner is not None:
await runner.cleanup()
+ if self._turn_completions:
+ await asyncio.gather(*(
+ await_owned_task(task) for task in tuple(self._turn_completions.values())
+ ))
# After the runner, so the handlers it cancels have queued their last
# writes first. Bounded like every other owned drain: a ledger that
# cannot be reached must not hold shutdown open.
@@ -446,11 +559,12 @@ class ModelHubTurnGateway:
token = self._authorized_token(request, backend)
if token is None:
return self._error_response(status=401, code="authentication_error")
- with self.correlation.gateway_terminalizer(
+ terminalizer = self.correlation.gateway_terminalizer(
backend=backend,
token=token,
- ) as terminalizer:
- execution = _TurnExecution()
+ )
+ execution = _TurnExecution()
+ with self._own_turn_request(terminalizer, execution), terminalizer:
resources = AsyncExitStack()
await resources.__aenter__()
request_task = asyncio.create_task(
diff --git a/core/session_turns.py b/core/session_turns.py
index 4f4fb6d9b..06865f471 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -1107,7 +1107,7 @@ class SessionTurnManager:
self,
context: "MessageContext",
settled_by: Optional[str],
- ) -> None:
+ ) -> asyncio.Task[None] | None:
runtime = getattr(self.controller, "model_hub_runtime", None)
settle = getattr(runtime, "settle_turn", None)
turn_id = str(
@@ -1126,7 +1126,7 @@ class SessionTurnManager:
mode = turn_mode_for_context(context)
if mode is None and launch is not None:
mode = "direct" if launch.channel == "direct" else "hub"
- settle(
+ return settle(
turn_id,
settled_by=settled_by,
ts=_utc_now_iso(),
@@ -7369,13 +7369,6 @@ class SessionTurnManager:
cancel_defers_queue_resume = bool(
turn is not None and turn.cancel_defers_queue_resume
)
- if turn is not None:
- self.in_flight.pop(session_id, None)
- if turn is not None:
- bus.publish(
- "turn.end",
- _turn_event_payload(session_id, logical_turn_id),
- )
if cancelled:
# Attribute the cancellation to whoever caused it. The Turn
# carries the cause when the canceller had a more specific one
@@ -7384,7 +7377,23 @@ class SessionTurnManager:
settled_by = (
getattr(turn, "cancel_settled_by", None) if turn is not None else None
) or SETTLED_BY_NO_TERMINAL_RESULT
- self._settle_model_hub_turn(context, settled_by)
+ completion = self._settle_model_hub_turn(context, settled_by)
+ if inspect.isawaitable(completion):
+ from core.handlers.model_hub.async_owner import await_owned_task
+
+ try:
+ await await_owned_task(asyncio.ensure_future(completion))
+ except Exception:
+ logger.warning("Model Hub turn finalization failed", exc_info=True)
+ # Durable output may already have marked the old row terminal.
+ # _start_persisted_turn still fences its successor on this live
+ # runner, so release the projection only after Hub finalization.
+ if turn is not None and self.in_flight.get(session_id) is turn:
+ self.in_flight.pop(session_id, None)
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, logical_turn_id),
+ )
if logical_turn_id and durable_turn_registered:
durable_terminal_result = self._reconcile_durable_runner_release(
logical_turn_id,
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
index 7e5563547..ced627ea6 100644
--- a/docs/plans/model-hub-implementation.md
+++ b/docs/plans/model-hub-implementation.md
@@ -35,6 +35,15 @@ mirrors that decision table; the direct backend test
`tests/test_model_hub_provenance.py::test_terminal_diagnostic_schema_uses_the_production_machine_code_authority`
compares schema enum minus null with production `UPSTREAM_MACHINE_ERROR_CODES`.
+Joined Turn Finalization in `model-hub-routing-modes.md` closes the terminal-frame
+race between native FSM completion and actual gateway settlement. Existing
+correlation/terminalizer owners retain exactly attributed request identities until
+both boundaries finish, with bounded teardown and same-Session admission ordering.
+They preserve cancellation, failure and ambiguous-scope rules; neither Session
+text nor a lookup retry may manufacture a replacement successful record. Real
+loopback early/late completion and reused-process follow-up tests consume this
+boundary, alongside the merged local recorded-turn browser workflow.
+
Transport registration is separate from inventory: SourceBinding.route_model_ids is a
default-empty tuple, mirrored in the internal SourceRecord with absent-as-empty loading.
The deterministic sorted/deduplicated set comes from effective Hub-channel targets across
diff --git a/docs/plans/model-hub-routing-modes.md b/docs/plans/model-hub-routing-modes.md
index 6691b348c..c4c071f2c 100644
--- a/docs/plans/model-hub-routing-modes.md
+++ b/docs/plans/model-hub-routing-modes.md
@@ -243,6 +243,39 @@ Contract and consuming tests must cover old records without optional metadata,
model/backend isolation, latest-success clearing, bounded/absent history, unsafe
upstream text exclusion, read-only retrieval, and real model-not-found display.
+### Joined Turn Finalization
+
+A backend may finish its native turn as soon as it reads a terminal protocol
+frame, before the gateway has settled the corresponding transport outcome. FSM
+completion alone must not destroy an exactly attributed trace with owned gateway
+requests still settling. Correlation and the existing gateway terminalizer join
+those two lifecycles; only observed service outcomes can establish Hub success.
+
+At FSM completion, close new attribution admission for that turn while allowing
+already-owned request identities to finish. Finalize the retained record once,
+after both boundaries are terminal, preserving the existing stopped, backend
+failure, ambiguity, and native-channel precedence. Prefer a bounded per-turn
+drain integrated with the existing Session completion/admission owner and gateway
+teardown deadline. Do not wait under a service mutation lock or a global lock,
+and do not block unrelated Sessions. The next turn in the same Session must not
+be attributed to the departing trace or have its newer record replaced by a
+late finalization of that trace. Preserve route credential reuse and independent
+request identities across retries and concurrent requests within one turn.
+
+Cancellation, process-scope retirement, gateway close and teardown timeout must
+release owned state without inventing success or silently dropping committed
+terminal facts. A terminal frame is not permission to bypass settlement. No
+second history store, delayed lookup retry, new wire/version field, arbitrary
+sleep, or per-request engine registration is part of this correction. OpenCode's
+existing shared-process untracked boundary remains unchanged.
+
+Consuming regression must exercise real loopback HTTP completion before gateway
+settlement, the opposite ordering, first-error/second-success on a reused process
+credential, multiple requests and retries, stopped/backend-error/retired scopes,
+bounded cancellation and timeout, and independent Session progress. Live
+acceptance must retain the actual second request's source/model capture and
+distinct turn identity before claiming that a later success clears an old error.
+
### Atomic Invocation Admission
Transport draining alone does not protect a request that resolved an old target
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 8f83e6e77..65a09b1bc 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -1237,6 +1237,16 @@ this turn" is a billing question the user asks days later, not just live. A turn
that switched sources mid-flight lists every attempt in order, so the record
explains the switch rather than merely naming the winner.
+Turn resolution joins FSM completion with settlement of its already-attributed
+gateway requests. Receiving a terminal protocol frame is not proof that the
+gateway has finished recording the transport result. Closing a turn therefore
+closes new attribution admission but retains owned request identities until
+their terminalizers finish. Finalization is exactly once, bounded by existing
+teardown policy, and preserves cancellation/failure precedence and subsequent
+turn ordering without blocking unrelated Sessions. The existing service outcome
+remains the only Hub success authority; see `model-hub-routing-modes.md`,
+Joined Turn Finalization. No Session-text inference or new history store is used.
+
**Recorded-error diagnostic selection (authoritative and exhaustive).**
New terminal-error records may retain observed `http_status` (100-599 or null) and
`upstream_error_code` (recognized upstream code or null). Historical records may omit
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index 861bcd893..3c82f8a8f 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -815,17 +815,23 @@ class ModelHubRuntimeRouter:
settled_by: Optional[str],
ts: str,
mode: Optional[Literal["direct", "hub"]] = None,
- ) -> None:
- try:
- if mode is not None:
- self.service.note_turn_mode(turn_id, mode)
- finally:
- if self.turn_gateway is not None:
- self.turn_gateway.correlation.settle(
- turn_id,
- settled_by=settled_by,
- ts=ts,
- )
+ ) -> asyncio.Task[None] | None:
+ def finish() -> None:
+ try:
+ if mode is not None:
+ self.service.note_turn_mode(turn_id, mode)
+ finally:
+ if self.turn_gateway is not None:
+ self.turn_gateway.correlation.settle(
+ turn_id,
+ settled_by=settled_by,
+ ts=ts,
+ )
+
+ if self.turn_gateway is not None:
+ return self.turn_gateway.finalize_turn(turn_id, settled_by=settled_by, finish=finish)
+ finish()
+ return None
def retire_process_scope(
self,
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index db81f56ca..f1486d751 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -143,6 +143,7 @@ capabilities:
- tests/test_model_hub_admission.py
- tests/test_model_hub_config.py
- tests/test_model_hub_provenance.py
+ - tests/test_model_hub_retention.py
- tests/test_model_hub_resolution.py
- tests/test_model_hub_routing_modes.py
- tests/test_model_hub_transport_leases.py
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index b112101e2..189d55d13 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -5297,7 +5297,7 @@ def test_settlement_retires_correlation_when_mode_persistence_fails(
service.note_turn_mode = Mock(side_effect=OSError("mode store unavailable"))
router = ModelHubRuntimeRouter(
service=service,
- turn_gateway=SimpleNamespace(correlation=correlation),
+ turn_gateway=ModelHubTurnGateway(service, correlation=correlation),
)
with pytest.raises(OSError, match="mode store unavailable"):
diff --git a/tests/test_model_hub_retention.py b/tests/test_model_hub_retention.py
new file mode 100644
index 000000000..ea3af62da
--- /dev/null
+++ b/tests/test_model_hub_retention.py
@@ -0,0 +1,778 @@
+from __future__ import annotations
+
+import asyncio
+import inspect
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import aiohttp
+import pytest
+
+from core.handlers.model_hub.adapter import RawOutcomeKind
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from core.run_settlement import (
+ SETTLED_BY_BACKEND_REFRESH, SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULT,
+)
+from modules.agents.model_hub import ModelHubRuntimeRouter
+from modules.agents.codex.event_handler import CodexEventHandler
+from tests.test_model_hub_l3 import (
+ FakeStreamResponse,
+ LiveInvokeHandle,
+ NeverResolvingCloseHandle,
+ _canonicalize_fixed_test_routes,
+ _outcome,
+ _prepared_gateway_request,
+ _service,
+ _source,
+)
+
+
+TERMINAL = (
+ b'event: response.completed\ndata: {"type":"response.completed",'
+ b'"response":{"status":"completed","output":[],"usage":'
+ b'{"input_tokens":1,"output_tokens":1}}}\n\n'
+)
+
+
+async def _settle(runtime, turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT):
+ completion = runtime.settle_turn(
+ turn_id, settled_by=settled_by, ts="2026-09-06T00:00:00+00:00"
+ )
+ if inspect.isawaitable(completion):
+ await completion
+
+
+class HeldTerminalHandle(LiveInvokeHandle):
+ def __init__(self, source_id, chunks=(TERMINAL,)):
+ super().__init__(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source_id, stream_started=True),
+ chunks,
+ )
+ self.at_end = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def _iterate(self, chunks):
+ for chunk in chunks:
+ yield chunk
+ self.at_end.set()
+ await self.release.wait()
+
+
[email protected]("early", [True, False], ids=["terminal-frame", "gateway-finished"])
+def test_loopback_first_error_then_success_retained_on_reused_credentials(tmp_path, early):
+ async def exercise():
+ source = _source("src_retention01", "Retention")
+ handle = HeldTerminalHandle(source.id)
+ service = _service(
+ tmp_path,
+ sources=[source],
+ outcomes=[_outcome(RawOutcomeKind.HTTP_ERROR, status=404, code="model_not_found", source_id=source.id)],
+ )
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ first = _prepared_gateway_request(
+ gateway, turn_id="first-error", requested_model=model, source_id=source.id, stream=True
+ )
+ completion = None
+ try:
+ await gateway._handle_request(first)
+ await _settle(runtime, "first-error")
+ assert service.provenance.get("first-error")["terminal_error"]["upstream_error_code"] == "model_not_found"
+ service.adapter.live_handles.append(handle)
+ base, token = await gateway.endpoint(
+ "codex", process_scope="/repo", turn_id="second-success", requested_model_id=model,
+ resolved_model_id="shared-model", source_id=source.id,
+ )
+ assert first.headers["Authorization"] == f"Bearer {token}"
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ async with client.post(
+ f"{base}/v1/responses", headers={"Authorization": f"Bearer {token}"},
+ json={"model": "shared-model", "input": "synthetic", "stream": True},
+ ) as response:
+ frame = await asyncio.wait_for(response.content.readuntil(b"\n\n"), 5)
+ assert b"response.completed" in frame
+ await asyncio.wait_for(handle.at_end.wait(), 5)
+ if early:
+ completion = asyncio.create_task(_settle(runtime, "second-success"))
+ await asyncio.sleep(0)
+ handle.release.set()
+ await asyncio.wait_for(response.read(), 5)
+ if completion is None:
+ completion = asyncio.create_task(_settle(runtime, "second-success"))
+ await asyncio.wait_for(completion, 5)
+ latest = service.provenance.latest_for_model("codex", model)
+ assert latest["turn_id"] == "second-success"
+ assert latest["outcome"] == "served"
+ assert latest["terminal_error"] is None
+ assert len(service.adapter.invocations) == 2
+ finally:
+ handle.release.set()
+ if completion is not None:
+ await asyncio.gather(completion, return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_codex_will_retry_keeps_same_turn_open_until_success_settles(tmp_path):
+ async def exercise():
+ source = _source("src_retryturn1", "Retry")
+ handle = HeldTerminalHandle(source.id)
+ service = _service(tmp_path, sources=[source], outcomes=[
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=404, code="model_not_found", source_id=source.id)
+ ])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(
+ gateway, turn_id="retried", requested_model=model, source_id=source.id, stream=True
+ )
+ recorder = AsyncMock()
+ handler = CodexEventHandler(SimpleNamespace(_record_model_hub_native_failure=recorder))
+ running = completion = None
+ try:
+ await gateway._handle_request(request)
+ await handler.handle_notification(
+ "error", {"error": {"message": "synthetic retry"}, "willRetry": True, "turnId": "retried"},
+ SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "retried"})),
+ )
+ recorder.assert_not_awaited()
+ assert service.provenance.get("retried") is None
+ retry = _prepared_gateway_request(
+ gateway, turn_id="retried", requested_model=model, source_id=source.id, stream=True
+ )
+ assert request.headers == retry.headers
+ service.adapter.live_handles.append(handle)
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()):
+ running = asyncio.create_task(gateway._handle_request(retry))
+ await asyncio.wait_for(handle.at_end.wait(), 5)
+ completion = runtime.settle_turn(
+ "retried", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00Z"
+ )
+ assert completion is not None and not completion.done()
+ handle.release.set()
+ await asyncio.wait_for(completion, 5)
+ await running
+ record = service.provenance.get("retried")
+ assert record["outcome"] == "served"
+ assert record["terminal_error"] is None
+ assert record["served"]["source_id"] == source.id
+ assert len(service.adapter.invocations) == 2
+ finally:
+ handle.release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
[email protected]("malformed", [False, True], ids=["valid", "malformed"])
+def test_request_admitted_before_completion_keeps_identity_through_body_parse(tmp_path, malformed):
+ async def exercise():
+ source = _source("src_parsedturn", "Delayed body")
+ service = _service(tmp_path, sources=[source], live_handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id), (TERMINAL,))
+ ])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="parsed", requested_model=model, source_id=source.id, stream=True)
+ original_json = request.json
+ parsing = asyncio.Event()
+ release = asyncio.Event()
+
+ async def parse(**_kwargs):
+ parsing.set()
+ await release.wait()
+ return {} if malformed else await original_json()
+
+ request.json = parse
+ completion = None
+ running = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(parsing.wait(), 5)
+ completion = asyncio.create_task(_settle(runtime, "parsed"))
+ await asyncio.sleep(0)
+ assert not completion.done()
+ # A later request may still route, but must not claim the closed turn.
+ token = request.headers["Authorization"].removeprefix("Bearer ")
+ with gateway.correlation.gateway_terminalizer(backend="codex", token=token) as late:
+ assert late.turn_id is None
+ release.set()
+ await asyncio.wait_for(running, 5)
+ await asyncio.wait_for(completion, 5)
+ record = service.provenance.get("parsed")
+ assert record["outcome"] == ("failed_terminal" if malformed else "served")
+ if malformed:
+ assert record["terminal_error"]["reason"] == "invalid_parameter"
+ assert service.adapter.invocations == []
+ finally:
+ release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
[email protected]("exact_request", [False, True], ids=["untracked-only", "also-exact"])
[email protected]("reason", [SETTLED_BY_TERMINAL_RESULT, SETTLED_BY_STOPPED])
+def test_out_of_window_request_releases_finalization_ownership(tmp_path, exact_request, reason):
+ async def exercise():
+ source = _source("src_oldroute01", "Old route")
+ old_handle = HeldTerminalHandle(source.id)
+ exact_handle = HeldTerminalHandle(source.id)
+ service = _service(tmp_path, sources=[source], live_handles=[old_handle, exact_handle])
+ old_model = _canonicalize_fixed_test_routes(service)["codex"]
+ agent = service.store.load().agents["codex"]
+ new_model = next(model for model in agent.routes if model != old_model)
+ agent.routes[new_model] = agent.routes[old_model]
+ gateway = ModelHubTurnGateway(service, transport_timeout=0.02)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ old_request = _prepared_gateway_request(
+ gateway, turn_id="old-route", requested_model=old_model, source_id=source.id, stream=True
+ )
+ await _settle(runtime, "old-route")
+ new_request = _prepared_gateway_request(
+ gateway, turn_id="new-route", requested_model=new_model, source_id=source.id, stream=True
+ )
+ assert old_request.headers != new_request.headers
+ old_task = exact_task = completion = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", side_effect=lambda **_kwargs: FakeStreamResponse()):
+ old_task = asyncio.create_task(gateway._handle_request(old_request))
+ await asyncio.wait_for(old_handle.at_end.wait(), 5)
+ if exact_request:
+ exact_task = asyncio.create_task(gateway._handle_request(new_request))
+ await asyncio.wait_for(exact_handle.at_end.wait(), 5)
+ completion = runtime.settle_turn("new-route", settled_by=reason, ts="2026-09-06T00:00:00+00:00")
+ if exact_request:
+ assert completion is not None
+ assert not completion.done()
+ if reason == SETTLED_BY_TERMINAL_RESULT:
+ exact_handle.release.set()
+ await asyncio.wait_for(asyncio.shield(completion), 5)
+ await asyncio.gather(exact_task, return_exceptions=True)
+ record = service.provenance.get("new-route")
+ assert record["outcome"] == ("served" if reason == SETTLED_BY_TERMINAL_RESULT else "canceled")
+ assert record["requested_model_id"] == new_model
+ else:
+ assert completion is None
+ record = service.provenance.get("new-route")
+ if reason == SETTLED_BY_STOPPED:
+ # Existing no-request Stop history is retained, without
+ # attributing any of the out-of-window request's facts.
+ assert record["outcome"] == "canceled"
+ assert record["canceled_attempt"] is None
+ assert record["served"] is None
+ assert record["terminal_error"] is None
+ assert record["failed_attempts"] == []
+ else:
+ assert record is None
+ assert not old_task.done(), "finalization must neither wait for nor cancel the untracked request"
+ old_handle.release.set()
+ await asyncio.wait_for(old_task, 5)
+ assert service.provenance.get("old-route") is None
+ assert len(service.adapter.invocations) == (2 if exact_request else 1)
+ finally:
+ old_handle.release.set()
+ exact_handle.release.set()
+ await asyncio.gather(*(task for task in (old_task, exact_task, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_body_claim_releases_request_already_snapshotted_by_finalization(tmp_path):
+ async def exercise():
+ source = _source("src_bodyclaim01", "Body claim")
+ handle = HeldTerminalHandle(source.id)
+ service = _service(tmp_path, sources=[source], live_handles=[handle])
+ old_model = _canonicalize_fixed_test_routes(service)["codex"]
+ agent = service.store.load().agents["codex"]
+ new_model = next(model for model in agent.routes if model != old_model)
+ gateway = ModelHubTurnGateway(service, transport_timeout=0.05)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(
+ gateway, turn_id="old-route", requested_model=old_model, source_id=source.id, stream=True
+ )
+ await _settle(runtime, "old-route")
+ _prepared_gateway_request(gateway, turn_id="new-route", requested_model=new_model, source_id=source.id, stream=True)
+ original_json = request.json
+ parsing = asyncio.Event()
+ release = asyncio.Event()
+ draining = asyncio.Event()
+ original_drain = gateway._drain_turn_requests
+
+ async def parse(**kwargs):
+ parsing.set()
+ await release.wait()
+ return await original_json(**kwargs)
+
+ async def drain(*args, **kwargs):
+ draining.set()
+ await original_drain(*args, **kwargs)
+
+ request.json = parse
+ running = completion = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()), patch.object(
+ gateway, "_drain_turn_requests", side_effect=drain
+ ):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(parsing.wait(), 5)
+ completion = runtime.settle_turn(
+ "new-route", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00+00:00"
+ )
+ await asyncio.wait_for(draining.wait(), 5)
+ release.set()
+ await asyncio.wait_for(handle.at_end.wait(), 5)
+ await asyncio.wait_for(asyncio.shield(completion), 5)
+ assert not running.done(), "released attribution must wake the existing drain without canceling transport"
+ assert service.provenance.get("new-route") is None
+ handle.release.set()
+ await asyncio.wait_for(running, 5)
+ assert service.provenance.get("old-route") is None
+ finally:
+ release.set()
+ handle.release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+ "reason,backend_rejection,expected",
+ [
+ (SETTLED_BY_STOPPED, False, "canceled"),
+ (SETTLED_BY_NO_TERMINAL_RESULT, False, "failed_terminal"),
+ (SETTLED_BY_BACKEND_REFRESH, False, "failed_terminal"),
+ (SETTLED_BY_TERMINAL_RESULT, True, "failed_terminal"),
+ ],
+)
+def test_finalization_preserves_stop_and_backend_failure_before_late_success(tmp_path, reason, backend_rejection, expected):
+ async def exercise():
+ source = _source("src_stoppedturn", "Late success")
+ handle = HeldTerminalHandle(source.id)
+ service = _service(tmp_path, sources=[source], live_handles=[handle])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="terminated", requested_model=model, source_id=source.id, stream=True)
+ running = None
+ completion = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(handle.at_end.wait(), 5)
+ if backend_rejection:
+ gateway.correlation.fail_hub_attempt("terminated")
+ completion = asyncio.create_task(_settle(runtime, "terminated", reason))
+ await asyncio.sleep(0)
+ handle.release.set()
+ await asyncio.gather(running, return_exceptions=True)
+ await asyncio.wait_for(completion, 5)
+ record = service.provenance.get("terminated")
+ assert record["outcome"] == expected
+ assert record["served"] is None
+ if backend_rejection:
+ assert record["terminal_error"]["reason"] == "protocol_error"
+ elif reason != SETTLED_BY_STOPPED:
+ assert record["terminal_error"]["reason"] == "stream_interrupted"
+ else:
+ assert record["canceled_attempt"]["source_id"] == source.id
+ finally:
+ handle.release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_finalization_deadline_cancels_owned_request_without_inventing_success(tmp_path):
+ async def exercise():
+ source = _source("src_deadline01", "Deadline")
+ service = _service(tmp_path, sources=[source])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service, transport_timeout=0.02)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="deadline", requested_model=model, source_id=source.id, stream=True)
+ entered = asyncio.Event()
+
+ async def parse(**_kwargs):
+ entered.set()
+ await asyncio.Event().wait()
+
+ request.json = parse
+ running = asyncio.create_task(gateway._handle_request(request))
+ try:
+ await asyncio.wait_for(entered.wait(), 5)
+ await asyncio.wait_for(_settle(runtime, "deadline"), 1)
+ await asyncio.gather(running, return_exceptions=True)
+ record = service.provenance.get("deadline")
+ assert record is None or record["served"] is None
+ assert service.adapter.invocations == []
+ assert not gateway._turn_requests
+ assert not gateway._turn_completions
+ finally:
+ running.cancel()
+ await asyncio.gather(running, return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_completion_is_owned_once_through_repeated_waiter_cancellation(tmp_path):
+ async def exercise():
+ source = _source("src_cancelwait", "Canceled waiter")
+ handle = HeldTerminalHandle(source.id)
+ service = _service(tmp_path, sources=[source], live_handles=[handle])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="owned", requested_model=model, source_id=source.id, stream=True)
+ puts = []
+ original_put = service.provenance.put
+
+ def put(record):
+ puts.append(record)
+ original_put(record)
+
+ service.provenance.put = put
+ running = None
+ waiter = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(handle.at_end.wait(), 5)
+ completion = runtime.settle_turn("owned", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00Z")
+ assert completion is runtime.settle_turn("owned", settled_by=SETTLED_BY_STOPPED, ts="later")
+
+ async def wait():
+ await asyncio.shield(completion)
+
+ for _ in range(2):
+ waiter = asyncio.create_task(wait())
+ await asyncio.sleep(0)
+ waiter.cancel()
+ await asyncio.gather(waiter, return_exceptions=True)
+ assert not completion.done()
+ handle.release.set()
+ await asyncio.wait_for(completion, 5)
+ await running
+ await _settle(runtime, "owned")
+ assert len(puts) == 1
+ assert puts[0]["outcome"] == "served"
+ finally:
+ handle.release.set()
+ await asyncio.gather(*(task for task in (running, waiter) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_finalization_waits_for_every_request_after_its_attempt_is_finished(tmp_path):
+ async def exercise():
+ source = _source("src_retention02", "Concurrent requests")
+ service = _service(tmp_path, sources=[source], live_handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id), (TERMINAL,))
+ for _ in range(2)
+ ])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ at_eof = [asyncio.Event(), asyncio.Event()]
+ release = [asyncio.Event(), asyncio.Event()]
+
+ class HeldEOF(FakeStreamResponse):
+ def __init__(self, index):
+ super().__init__()
+ self.index = index
+
+ async def write_eof(self):
+ at_eof[self.index].set()
+ await release[self.index].wait()
+
+ requests = []
+ completion = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", side_effect=[HeldEOF(0), HeldEOF(1)]):
+ for _ in range(2):
+ request = _prepared_gateway_request(
+ gateway, turn_id="concurrent", requested_model=model, source_id=source.id, stream=True
+ )
+ requests.append(asyncio.create_task(gateway._handle_request(request)))
+ await asyncio.wait_for(asyncio.gather(*(event.wait() for event in at_eof)), 5)
+ completion = asyncio.create_task(_settle(runtime, "concurrent"))
+ await asyncio.sleep(0)
+ assert not completion.done()
+ release[0].set()
+ await requests[0]
+ assert not completion.done()
+ release[1].set()
+ await asyncio.gather(*requests)
+ await asyncio.wait_for(completion, 5)
+ assert service.provenance.get("concurrent")["outcome"] == "served"
+ finally:
+ for event in release:
+ event.set()
+ await asyncio.gather(*requests, return_exceptions=True)
+ if completion is not None:
+ await asyncio.gather(completion, return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
[email protected]("no_candidate", [False, True], ids=["malformed", "no-candidate"])
+def test_noninvoking_request_must_exit_before_finalization(tmp_path, no_candidate):
+ from config.v2_config import ModelHubRouteConfig
+
+ async def exercise():
+ source = _source("src_noinvoke01", "Non-invoking request")
+ service = _service(tmp_path, sources=[source])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="noninvoking", requested_model=model, source_id=source.id, stream=True)
+ if no_candidate:
+ service.store.config.agents["codex"].routes[model] = ModelHubRouteConfig()
+ else:
+ request.json.return_value = {}
+ response_ready = asyncio.Event()
+ release = asyncio.Event()
+ run_request = gateway._run_request_turn
+
+ async def exiting(*args, **kwargs):
+ response = await run_request(*args, **kwargs)
+ response_ready.set()
+ await release.wait()
+ return response
+
+ gateway._run_request_turn = exiting
+ running = asyncio.create_task(gateway._handle_request(request))
+ completion = None
+ try:
+ await asyncio.wait_for(response_ready.wait(), 5)
+ completion = asyncio.create_task(_settle(runtime, "noninvoking"))
+ await asyncio.sleep(0)
+ assert not completion.done()
+ assert service.provenance.get("noninvoking") is None
+ release.set()
+ await running
+ await asyncio.wait_for(completion, 5)
+ record = service.provenance.get("noninvoking")
+ assert record["outcome"] == ("no_candidate" if no_candidate else "failed_terminal")
+ assert service.adapter.invocations == []
+ finally:
+ release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
[email protected]("ending", ["stop", "retire", "close"])
+def test_committed_gateway_facts_survive_completion_cleanup(tmp_path, ending):
+ async def exercise():
+ source = _source("src_committed1", "Committed attempt")
+ service = _service(tmp_path, sources=[source], live_handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id), (TERMINAL,))
+ ])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="committed", requested_model=model, source_id=source.id, stream=True)
+ at_eof = asyncio.Event()
+ release = asyncio.Event()
+
+ class HeldEOF(FakeStreamResponse):
+ async def write_eof(self):
+ at_eof.set()
+ await release.wait()
+
+ running = None
+ completion = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=HeldEOF()):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(at_eof.wait(), 5)
+ completion = runtime.settle_turn(
+ "committed", settled_by=SETTLED_BY_STOPPED if ending == "stop" else SETTLED_BY_TERMINAL_RESULT,
+ ts="2026-09-06T00:00:00Z",
+ )
+ assert completion is not None
+ if ending == "retire":
+ gateway.correlation.retire_scope("codex", "/repo")
+ elif ending == "close":
+ await gateway.close()
+ release.set()
+ await asyncio.gather(running, return_exceptions=True)
+ await asyncio.wait_for(completion, 5)
+ assert service.provenance.get("committed")["outcome"] == "served"
+ assert not gateway._turn_requests
+ assert not gateway._turn_completions
+ finally:
+ release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
[email protected]("ending", ["retire", "overlap", "untracked"])
+def test_ambiguous_owned_request_is_never_promoted_to_attributed_success(tmp_path, ending):
+ async def exercise():
+ source = _source("src_ambiguous1", "Ambiguous turn")
+ handle = HeldTerminalHandle(source.id)
+ service = _service(tmp_path, sources=[source], live_handles=[handle])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="ambiguous", requested_model=model, source_id=source.id, stream=True)
+ running = None
+ completion = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(handle.at_end.wait(), 5)
+ completion = runtime.settle_turn("ambiguous", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00Z")
+ if ending == "retire":
+ gateway.correlation.retire_scope("codex", "/repo")
+ else:
+ gateway.correlation.credentials("codex", "/repo", "peer" if ending == "overlap" else None)
+ handle.release.set()
+ await running
+ await asyncio.wait_for(completion, 5)
+ assert service.provenance.get("ambiguous") is None
+ finally:
+ handle.release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
[email protected]("failed", [False, True])
+def test_native_only_and_untracked_turns_finalize_without_async_work(tmp_path, failed):
+ source = _source("src_nativeonly", "Native", channel="native_cli")
+ service = _service(tmp_path, sources=[source])
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ gateway.correlation.begin_native_attempt(
+ backend="codex", process_scope="/repo", turn_id="native", requested_model_id="shared-model",
+ source_id=source.id, resolved_model_id="shared-model", via_mapping=False,
+ )
+ if failed:
+ gateway.correlation.fail_native_attempt("native", reason="rate_limited")
+ assert runtime.settle_turn("native", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00Z") is None
+ assert service.provenance.get("native")["outcome"] == ("exhausted" if failed else "served")
+ gateway.correlation.credentials("opencode", "shared", "opencode")
+ assert runtime.settle_turn("opencode", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00Z") is None
+ assert service.provenance.get("opencode") is None
+ assert not gateway._turn_completions
+
+
+def test_fallback_requests_keep_owned_identity_until_the_final_attempt_finishes(tmp_path):
+ async def exercise():
+ first = _source("src_fallback01", "First")
+ second = _source("src_fallback02", "Second")
+ handle = HeldTerminalHandle(second.id)
+ service = _service(tmp_path, sources=[first, second], outcomes=[
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=429, source_id=first.id)
+ ])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ original_invoke = service.adapter.invoke
+
+ async def invoke(source_id, *args, **kwargs):
+ if source_id == second.id:
+ service.adapter.live_handles.append(handle)
+ return await original_invoke(source_id, *args, **kwargs)
+
+ service.adapter.invoke = invoke
+ request = _prepared_gateway_request(gateway, turn_id="fallback", requested_model=model, source_id=first.id, stream=True)
+ running = None
+ completion = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(handle.at_end.wait(), 5)
+ # Same-turn retry preparation remains idempotent, not overlapping.
+ assert gateway.correlation.credentials("codex", "/repo", "fallback")
+ completion = runtime.settle_turn("fallback", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00Z")
+ assert completion is not None
+ handle.release.set()
+ await running
+ await asyncio.wait_for(completion, 5)
+ record = service.provenance.get("fallback")
+ assert record["outcome"] == "served"
+ assert record["served"]["source_id"] == second.id
+ assert [attempt["source_id"] for attempt in record["failed_attempts"]] == [first.id]
+ assert len(service.adapter.invocations) == 2
+ finally:
+ handle.release.set()
+ await asyncio.gather(*(task for task in (running, completion) if task is not None), return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_finalization_abandons_stuck_teardown_without_late_history_mutation(tmp_path):
+ async def exercise():
+ source = _source("src_stuckdrain", "Stuck teardown")
+ handle = NeverResolvingCloseHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=source.id))
+ service = _service(tmp_path, sources=[source], live_handles=[handle])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service, transport_timeout=0.02)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="stuck", requested_model=model, source_id=source.id, stream=True)
+ running = None
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", return_value=FakeStreamResponse()):
+ running = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(handle.started.wait(), 5)
+ await asyncio.wait_for(_settle(runtime, "stuck"), 1)
+ record = service.provenance.get("stuck")
+ assert record["outcome"] == "failed_terminal"
+ assert record["terminal_error"]["reason"] == "engine_down"
+ assert gateway.resource_leak_records
+ assert not gateway._turn_requests
+ assert not gateway._turn_completions
+ handle.release_close.set()
+ await asyncio.wait_for(handle.closed.wait(), 1)
+ await asyncio.gather(running, return_exceptions=True)
+ assert service.provenance.get("stuck") == record
+ finally:
+ handle.release_close.set()
+ if running is not None:
+ await asyncio.gather(running, return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_buffered_completion_uses_the_existing_synchronous_settlement_path(tmp_path):
+ async def exercise():
+ source = _source("src_buffered01", "Buffered")
+ service = _service(tmp_path, sources=[source], live_handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id), (b'{"output":[]}',))
+ ])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ request = _prepared_gateway_request(gateway, turn_id="buffered", requested_model=model, source_id=source.id, stream=False)
+ try:
+ response = await gateway._handle_request(request)
+ assert response.status == 200
+ assert runtime.settle_turn("buffered", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-09-06T00:00:00Z") is None
+ assert service.provenance.get("buffered")["outcome"] == "served"
+ finally:
+ await gateway.close()
+
+ asyncio.run(exercise())
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 7f3e00cff..9c7c5ff25 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -2727,6 +2727,112 @@ def test_terminal_output_persistence_failure_does_not_emit_empty_fallback(
assert status == "running"
+def test_model_hub_finalization_fences_native_start_after_durable_terminal(managers, monkeypatch, tmp_path):
+ from core.handlers.model_hub.adapter import RawOutcomeKind
+ from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+ from modules.agents.model_hub import ModelHubRuntimeRouter, bind_turn_mode
+ from tests.test_model_hub_l3 import (
+ FakeStreamResponse, LiveInvokeHandle, _canonicalize_fixed_test_routes,
+ _outcome, _prepared_gateway_request, _service, _source,
+ )
+ from tests.test_model_hub_retention import HeldTerminalHandle, TERMINAL
+
+ manager, _other, engine, _engine_b, _starts = managers
+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)
+ _seed_session(engine, "ses_independent")
+ source = _source("src_fencedturn", "Fenced finalization")
+ held = HeldTerminalHandle(source.id)
+ service = _service(tmp_path, sources=[source])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ runtime = ModelHubRuntimeRouter(service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json")
+ manager.controller.model_hub_runtime = runtime
+ monkeypatch.setattr("core.handlers.model_hub.service.get_cached_sqlite_engine", lambda: engine)
+ dispatched = []
+ requests = []
+ runners = []
+ finalization_started = asyncio.Event()
+ independent_done = asyncio.Event()
+ original_settle = runtime.settle_turn
+
+ def settle(*args, **kwargs):
+ result = original_settle(*args, **kwargs)
+ if result is not None:
+ finalization_started.set()
+ return result
+
+ runtime.settle_turn = settle
+
+ async def dispatch(_controller, context, text, **_kwargs):
+ session_id = context.platform_specific["workbench_session_id"]
+ turn_id = context.platform_specific["turn_token"]
+ dispatched.append((text, turn_id))
+ set_dispatch_phase(context, DISPATCH_PHASE_ATTEMPTING)
+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"
+ manager.on_native_start(context, backend="codex", runtime_key=f"key-{session_id}", runtime_turn_id=f"runtime-{turn_id}")
+ if text == "first":
+ bind_turn_mode(context, "hub")
+ service.adapter.live_handles.append(held)
+ request = _prepared_gateway_request(gateway, turn_id=turn_id, requested_model=model, source_id=source.id, stream=True)
+ requests.append(asyncio.create_task(gateway._handle_request(request)))
+ await held.at_end.wait()
+ elif text == "second":
+ assert service.provenance.latest_for_model("codex", model)["turn_id"] == dispatched[0][1]
+ bind_turn_mode(context, "hub")
+ service.adapter.live_handles.append(LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id), (TERMINAL,)
+ ))
+ request = _prepared_gateway_request(gateway, turn_id=turn_id, requested_model=model, source_id=source.id, stream=True)
+ await gateway._handle_request(request)
+ manager.on_terminal_result(context, is_error=False)
+ manager.on_terminal_delivery_complete(context)
+ if text == "independent":
+ independent_done.set()
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT, backend_dispatch_attempted=True)
+
+ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", dispatch)
+
+ async def exercise():
+ try:
+ with patch("core.handlers.model_hub.turn_gateway.web.StreamResponse", side_effect=lambda **_kwargs: FakeStreamResponse()):
+ first = await manager.deliver(DeliveryRequest(session_id="ses_fsm", priority="p3", content="first"), context=_context())
+ old_runner = manager.in_flight["ses_fsm"].task
+ runners.append(old_runner)
+ await asyncio.wait_for(finalization_started.wait(), 5)
+ with engine.connect() as conn:
+ assert delivery_store.get_turn(conn, first.turn_id)["state"] == "terminal"
+ second = await manager.deliver(DeliveryRequest(session_id="ses_fsm", priority="p3", content="second"), context=_context())
+ assert second.turn_id != first.turn_id
+ assert manager.in_flight["ses_fsm"].task is old_runner
+ assert [text for text, _ in dispatched] == ["first"]
+ # A durable successor can be claimed, but cannot launch while
+ # the departing Session runner still owns its Hub finalizer.
+ assert not await manager._start_persisted_turn(second.turn_id)
+ await manager.deliver(DeliveryRequest(session_id="ses_independent", priority="p3", content="independent"), context=_context("ses_independent"))
+ independent = manager.in_flight["ses_independent"].task
+ runners.append(independent)
+ await asyncio.wait_for(independent_done.wait(), 5)
+ await independent
+ assert not old_runner.done()
+ held.release.set()
+ await asyncio.wait_for(old_runner, 5)
+ successor = manager.in_flight.get("ses_fsm")
+ if successor is not None:
+ runners.append(successor.task)
+ await asyncio.wait_for(successor.task, 5)
+ assert [text for text, _ in dispatched] == ["first", "independent", "second"]
+ assert service.provenance.latest_for_model("codex", model)["turn_id"] == second.turn_id
+ finally:
+ held.release.set()
+ for runner in runners:
+ if not runner.done():
+ runner.cancel()
+ await asyncio.gather(*requests, *runners, return_exceptions=True)
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
def test_turn_state_repairs_only_an_exact_ownerless_running_projection(managers) -> None:
manager, _other, engine, _engine_b, _starts = managers
with engine.begin() as conn:
diff --git a/ui/e2e/model-recorded-turn.spec.ts b/ui/e2e/model-recorded-turn.spec.ts
index 36172580c..ae4918755 100644
--- a/ui/e2e/model-recorded-turn.spec.ts
+++ b/ui/e2e/model-recorded-turn.spec.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
-import type { RecordedTurn, Source } from './support/api';
+import type { RecordedTurn, Source, TurnReceipt } from './support/api';
import { routableModels } from './support/api';
import { hub as copy } from './support/copy';
import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';
@@ -9,7 +9,7 @@ import { labelledButton } from './support/hub';
import { captureAgentChain, restoreAgentChain, restoreNativeSources } from './support/restore';
// Additional live-browser evidence, not a Vitest scenario-catalog entry.
-test('MH-ROUTING-011 recorded request error is independent of current route and cleared by latest success', async ({ api, mock, hub, page }) => {
+test('MH-ROUTING-011 recorded request error is independent of current route and cleared by latest success', async ({ api, mock, hub, page }, testInfo) => {
test.setTimeout(180_000);
const projectId = process.env.VIBE_E2E_TURN_PROJECT_ID?.trim();
test.skip(!projectId, 'Set VIBE_E2E_TURN_PROJECT_ID to a task-owned disposable project on the explicitly consented regression instance.');
@@ -28,15 +28,82 @@ test('MH-ROUTING-011 recorded request error is independent of current route and
const suffix = randomUUID().slice(0, 8);
const agentName = `e2e-recorded-${suffix}`;
const ownPrefix = `${E2E_SOURCE_PREFIX}${suffix}-`;
+ const keys = { A: `e2e-mh011-${randomUUID()}-a`, B: `e2e-mh011-${randomUUID()}-b` };
let sessionId: string | null = null;
let agentAttempted = false;
let modeAttempted = false;
let first: Source;
let second: Source;
+ let primaryFailure = false;
+ let primaryError: unknown;
+ const cleanupFailures: unknown[] = [];
+ const cleanup = async (action: () => Promise<unknown>) => {
+ try { await action(); } catch (error) { cleanupFailures.push(error); }
+ };
+ const observedReceipts: TurnReceipt[] = [];
+ const observeTurn = async (label: string, text: string, expected: 'error' | 'served') => {
+ let receipt: TurnReceipt | null = null;
+ let latest: RecordedTurn | null = null;
+ let primary: unknown;
+ let failed = false;
+ let requestLogReset = false;
+ const requests: { method: string; path: string; model: unknown; synthetic_key_identity: string; uses_synthetic_b_key: boolean }[] = [];
+ const evidenceFailures: string[] = [];
+ try {
+ await mock.resetRequests();
+ requestLogReset = true;
+ receipt = await api.sendTurn(sessionId!, text);
+ observedReceipts.push(receipt);
+ expect(receipt.queued).toBe(false);
+ expect(new Set(observedReceipts.map((entry) => entry.turn_id)).size).toBe(observedReceipts.length);
+ await expect.poll(async () => {
+ latest = await api.latestRecordedTurn(backend, model);
+ if (latest?.turn_id !== receipt!.turn_id) return false;
+ return expected === 'error'
+ ? latest.terminal_error?.source_id === first.id && latest.terminal_error.upstream_error_code === 'model_not_found'
+ : latest.served?.source_id === first.id && latest.served.configured_model_id === model && latest.terminal_error === null;
+ }, { timeout: 70_000 }).toBe(true);
+ } catch (error) { failed = true; primary = error; }
+ try {
+ for (const entry of requestLogReset ? await mock.requests() : []) {
+ const authorization = entry.headers?.authorization;
+ const key = Object.entries(keys).find(([, value]) => authorization === `Bearer ${value}`)?.[0] ?? 'unrecognized';
+ const body = entry.body as { model?: unknown } | null;
+ requests.push({ method: entry.method, path: entry.path, model: typeof body?.model === 'string' ? body.model : null,
+ synthetic_key_identity: key, uses_synthetic_b_key: authorization === `Bearer ${keys.B}` || entry.headers?.['x-api-key'] === keys.B });
+ }
+ expect(requests.filter((entry) => entry.uses_synthetic_b_key)).toEqual([]);
+ const calls = requests.filter((entry) => entry.method === 'POST');
+ expect(calls.length).toBeGreaterThan(0);
+ expect(calls.every((entry) => entry.path === '/v1/responses' && entry.model === model && entry.synthetic_key_identity === 'A')).toBe(true);
+ } catch (error) {
+ evidenceFailures.push('mock request capture or exact model/source assertion failed');
+ if (!failed) { failed = true; primary = error; }
+ }
+ try {
+ // Only safe retained fields, never arbitrary headers, request bodies or receipt text.
+ const record = latest as RecordedTurn | null;
+ const retained = record && {
+ turn_id: record.turn_id, ts: record.ts, agent: record.agent, requested_model_id: record.requested_model_id,
+ terminal_error: record.terminal_error && {
+ source_id: record.terminal_error.source_id, configured_model_id: record.terminal_error.configured_model_id,
+ reason: record.terminal_error.reason, http_status: record.terminal_error.http_status,
+ upstream_error_code: record.terminal_error.upstream_error_code,
+ },
+ served: record.served && { source_id: record.served.source_id, configured_model_id: record.served.configured_model_id },
+ };
+ await testInfo.attach(`MH-ROUTING-011-${label}`, { contentType: 'application/json', body: JSON.stringify({
+ receipt, retained, requests, evidenceFailures, request_log_reset: requestLogReset,
+ synthetic_sources: { A: { source_id: first.id, key: keys.A }, B: { source_id: second.id, key: keys.B } },
+ }, null, 2) });
+ } catch (error) { if (!failed) { failed = true; primary = error; } }
+ if (failed) throw primary;
+ return latest! as RecordedTurn;
+ };
try {
await mock.configure({ auth: 'ok', protocol: 'openai_responses', models_endpoint: 'ok', models: [], model_errors: {}, stream: 'healthy' });
- const a = await api.createApiKeySource(`${ownPrefix}recorded-a`, `${mockBaseUrl()}/v1`);
- const b = await api.createApiKeySource(`${ownPrefix}recorded-b`, `${mockBaseUrl()}/v1`);
+ const a = await api.createApiKeySource(`${ownPrefix}recorded-a`, `${mockBaseUrl()}/v1`, keys.A);
+ const b = await api.createApiKeySource(`${ownPrefix}recorded-b`, `${mockBaseUrl()}/v1`, keys.B);
expect(a).not.toBeNull();
expect(b).not.toBeNull();
first = a!;
@@ -55,13 +122,7 @@ test('MH-ROUTING-011 recorded request error is independent of current route and
agentAttempted = true;
await api.createTurnAgent(agentName, backend, model);
sessionId = await api.createTurnSession(projectId!, agentName, model);
- await api.sendTurn(sessionId, 'Return the synthetic upstream response. Request: \u4e2d\u6587');
- let failed: RecordedTurn | null = null;
- await expect.poll(async () => {
- failed = await api.latestRecordedTurn(backend, model);
- return failed?.terminal_error?.source_id === first.id ? failed.terminal_error.upstream_error_code : null;
- }, { timeout: 70_000 }).toBe('model_not_found');
- const recorded = failed! as RecordedTurn;
+ const recorded = await observeTurn('failed-turn', 'Return the synthetic upstream response. Request: \u4e2d\u6587', 'error');
expect(recorded.terminal_error).toMatchObject({ source_id: first.id, configured_model_id: model, http_status: 404 });
expect((await api.sources()).find((entry) => entry.id === first.id)!.state).toEqual(healthBefore);
expect((await api.agentChain(backend, model)).route_origin).toBe('passthrough');
@@ -90,11 +151,8 @@ test('MH-ROUTING-011 recorded request error is independent of current route and
expect(await api.deleteAgentChain(backend, model)).toBe(true);
await mock.configure({ model_errors: {} });
- await api.sendTurn(sessionId, 'Return the synthetic upstream response again.');
- await expect.poll(async () => {
- const latest = await api.latestRecordedTurn(backend, model);
- return latest?.turn_id !== recorded.turn_id && latest?.served?.source_id === first.id && latest.terminal_error === null;
- }, { timeout: 70_000 }).toBe(true);
+ await observeTurn('successful-turn', 'Return the synthetic upstream response again.', 'served');
+ expect(observedReceipts).toHaveLength(2);
await page.reload();
const historyRead = page.waitForResponse((response) => new URL(response.url()).pathname === `/api/models/agents/${backend}/provenance`);
await hub.openRoute(backend, model);
@@ -102,33 +160,24 @@ test('MH-ROUTING-011 recorded request error is independent of current route and
await expect(hub.routeDialog.locator('.model-hub-recorded-turn')).toHaveCount(0);
expect((await api.agentChain(backend, model)).route_origin).toBe('passthrough');
expect((await api.sources()).find((entry) => entry.id === first.id)!.state).toEqual(healthBefore);
+ } catch (error) {
+ primaryFailure = true;
+ primaryError = error;
} finally {
- try {
- if (agentAttempted) await api.removeTurnFixture(agentName, sessionId);
- } finally {
- try {
- await restoreAgentChain(api, { backend, model }, originalRoute);
- } finally {
- try {
- await api.setDefaultSourceOrder(backend, originalOrder);
- } finally {
- try {
- if (modeAttempted) await api.setAgentMode(backend, agent!.mode);
- } finally {
- try {
- if (modeAttempted) await restoreNativeSources(api, sourceIds);
- } finally {
- try {
- for (const entry of await api.sources()) {
- if (entry.display_name.startsWith(ownPrefix)) await api.deleteSource(entry.id);
- }
- } finally {
- await mock.configure({ model_errors: {}, stream: 'healthy' });
- }
- }
- }
- }
+ await cleanup(async () => { if (agentAttempted) await api.removeTurnFixture(agentName, sessionId); });
+ await cleanup(() => restoreAgentChain(api, { backend, model }, originalRoute));
+ await cleanup(() => api.setDefaultSourceOrder(backend, originalOrder));
+ await cleanup(async () => { if (modeAttempted) await api.setAgentMode(backend, agent!.mode); });
+ await cleanup(async () => { if (modeAttempted) await restoreNativeSources(api, sourceIds); });
+ await cleanup(async () => {
+ for (const entry of await api.sources()) if (entry.display_name.startsWith(ownPrefix)) {
+ await cleanup(() => api.deleteSource(entry.id));
}
- }
+ });
+ await cleanup(() => mock.configure({ model_errors: {}, stream: 'healthy' }));
+ await cleanup(() => testInfo.attach('MH-ROUTING-011-cleanup', { contentType: 'application/json',
+ body: JSON.stringify({ failed: cleanupFailures.length > 0, failure_count: cleanupFailures.length, primary_failure_preserved: primaryFailure }) }));
}
+ if (primaryFailure) throw primaryError;
+ if (cleanupFailures.length) throw new AggregateError(cleanupFailures, 'Recorded-turn cleanup failed');
});
diff --git a/ui/e2e/model-route-cleanup.spec.ts b/ui/e2e/model-route-cleanup.spec.ts
index b4a48578e..655ee42fe 100644
--- a/ui/e2e/model-route-cleanup.spec.ts
+++ b/ui/e2e/model-route-cleanup.spec.ts
@@ -1,10 +1,170 @@
-import { expect, test, type Page } from '@playwright/test';
+import { expect, test, type APIRequestContext, type Page } from '@playwright/test';
import type { AgentChain, HubApi } from './support/api';
import { HubApi as HubApiClient } from './support/api';
import { ModelHubPage } from './support/hub';
import { captureAgentChain, restoreAgentChain } from './support/restore';
+type CleanupReply = { status: number; body: unknown };
+const ownedSession = 'sess_owned';
+const ownedAgent = 'e2e-recorded-owned';
+const archivedSession = { id: ownedSession, status: 'archived' };
+
+const acceptedTurn = { ok: true, session_id: ownedSession, turn_id: `trn_${'a'.repeat(32)}`, queued: false };
+for (const [name, status, body, accepted] of [
+ ['actual top-level receipt', 202, { ...acceptedTurn, text: 'must not persist', metadata: { private: true } }, true],
+ ['queued receipt', 202, { ...acceptedTurn, queued: true }, true],
+ ['missing turn id', 202, { ...acceptedTurn, turn_id: undefined }, false],
+ ['invented nested turn envelope', 202, { ok: true, turn: { id: acceptedTurn.turn_id } }, false],
+ ['wrong Session', 202, { ...acceptedTurn, session_id: 'sess_other' }, false],
+ ['rejected response', 403, acceptedTurn, false],
+ ['false ok', 202, { ...acceptedTurn, ok: false }, false],
+ ['missing queued state', 202, { ...acceptedTurn, queued: undefined }, false],
+] as const) {
+ test(`sendTurn checks the real delivery envelope: ${name}`, async () => {
+ const context = {
+ get: async () => ({ ok: () => true, json: async () => ({ csrf_token: 'synthetic' }) }),
+ post: async (path: string) => {
+ expect(path).toBe(`/api/sessions/${ownedSession}/messages`);
+ return { ok: () => status === 202, status: () => status, json: async () => body };
+ },
+ } as unknown as APIRequestContext;
+ const sending = new HubApiClient(context).sendTurn(ownedSession, 'synthetic prompt');
+ if (accepted) {
+ expect(await sending).toEqual({ ...acceptedTurn, queued: body.queued });
+ } else {
+ await expect(sending).rejects.toThrow('exact accepted FSM receipt');
+ }
+ });
+}
+
+function turnCleanupClient(options: {
+ turn?: 'completed' | 'active' | 'archived';
+ archive?: CleanupReply;
+ readback?: CleanupReply;
+ agent?: CleanupReply;
+} = {}) {
+ const calls: string[] = [];
+ const response = ({ status, body }: CleanupReply) => ({
+ ok: () => status >= 200 && status < 300,
+ status: () => status,
+ statusText: () => 'Synthetic fixture response',
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ });
+ const request = {
+ get: async (path: string) => {
+ if (path === '/api/csrf-token') return response({ status: 200, body: { csrf_token: 'synthetic-csrf' } });
+ calls.push(`GET ${path}`);
+ expect(path).toBe(`/api/sessions/${ownedSession}`);
+ return response(options.readback ?? { status: 200, body: archivedSession });
+ },
+ post: async (path: string) => {
+ calls.push(`POST ${path}`);
+ expect(path).toBe(`/api/sessions/${ownedSession}/cancel`);
+ return response(options.turn === 'active'
+ ? { status: 200, body: { ok: true } }
+ : { status: 404, body: { ok: false, code: 'not_in_flight', session_id: ownedSession } });
+ },
+ delete: async (path: string) => {
+ calls.push(`DELETE ${path}`);
+ if (path === `/api/sessions/${ownedSession}`) {
+ return response(options.archive ?? { status: 200, body: archivedSession });
+ }
+ expect(path).toBe(`/api/agents/${ownedAgent}`);
+ return response(options.agent ?? { status: 200, body: { ok: true } });
+ },
+ } as unknown as APIRequestContext;
+ return { client: new HubApiClient(request), calls };
+}
+
+test('completed turn cleanup archives and reads back without a cancel precondition', async () => {
+ const { client, calls } = turnCleanupClient({ turn: 'completed' });
+ await client.removeTurnFixture(ownedAgent, ownedSession);
+ expect(calls).toEqual([
+ `DELETE /api/sessions/${ownedSession}`,
+ `GET /api/sessions/${ownedSession}`,
+ `DELETE /api/agents/${ownedAgent}`,
+ ]);
+});
+
+for (const turn of ['active', 'archived'] as const) {
+ test(`${turn} turn cleanup uses the archive lifecycle and verifies persisted identity`, async () => {
+ const { client, calls } = turnCleanupClient({ turn });
+ await client.removeTurnFixture(ownedAgent, ownedSession);
+ expect(calls).toEqual([
+ `DELETE /api/sessions/${ownedSession}`,
+ `GET /api/sessions/${ownedSession}`,
+ `DELETE /api/agents/${ownedAgent}`,
+ ]);
+ });
+}
+
+for (const status of [403, 404, 500]) {
+ test(`session archive rejects HTTP ${status} without a success waiver or retry`, async () => {
+ const { client, calls } = turnCleanupClient({ archive: { status, body: { error: 'synthetic_refusal' } } });
+ await expect(client.archiveTurnSession(ownedSession)).rejects.toThrow(`Archive fixture session failed: HTTP ${status}`);
+ expect(calls).toEqual([`DELETE /api/sessions/${ownedSession}`]);
+ });
+
+ test(`session archive rejects HTTP ${status} from its readback`, async () => {
+ const { client, calls } = turnCleanupClient({ readback: { status, body: { error: 'synthetic_refusal' } } });
+ await expect(client.archiveTurnSession(ownedSession)).rejects.toThrow(`GET /api/sessions/${ownedSession}`);
+ expect(calls).toEqual([`DELETE /api/sessions/${ownedSession}`, `GET /api/sessions/${ownedSession}`]);
+ });
+}
+
+for (const [label, body] of [
+ ['missing', null],
+ ['different identity', { id: 'sess_someone_else', status: 'archived' }],
+ ['still active', { id: ownedSession, status: 'active' }],
+] as const) {
+ test(`session archive rejects a successful response with ${label} state`, async () => {
+ const { client, calls } = turnCleanupClient({ archive: { status: 200, body } });
+ await expect(client.archiveTurnSession(ownedSession)).rejects.toThrow('response did not confirm archived identity');
+ expect(calls).toEqual([`DELETE /api/sessions/${ownedSession}`]);
+ });
+
+ test(`session archive rejects a false-success readback with ${label} state`, async () => {
+ const { client, calls } = turnCleanupClient({ readback: { status: 200, body } });
+ await expect(client.archiveTurnSession(ownedSession)).rejects.toThrow('readback did not confirm archived identity');
+ expect(calls).toEqual([`DELETE /api/sessions/${ownedSession}`, `GET /api/sessions/${ownedSession}`]);
+ });
+}
+
+for (const archiveFails of [true, false]) {
+ test(`Agent cleanup is attempted after ${archiveFails ? 'archive rejection' : 'false-success archive readback'}`, async () => {
+ const { client, calls } = turnCleanupClient(archiveFails
+ ? { archive: { status: 403, body: { error: 'forbidden' } } }
+ : { readback: { status: 200, body: { id: ownedSession, status: 'active' } } });
+ const failure = await client.removeTurnFixture(ownedAgent, ownedSession).catch((error: unknown) => error);
+ expect(failure).toBeInstanceOf(AggregateError);
+ expect((failure as AggregateError).errors).toHaveLength(1);
+ expect(calls.at(-1)).toBe(`DELETE /api/agents/${ownedAgent}`);
+ expect(calls.some((call) => call.startsWith('POST '))).toBe(false);
+ });
+}
+
+test('fixture cleanup reports both archive and Agent errors', async () => {
+ const { client, calls } = turnCleanupClient({
+ archive: { status: 404, body: { error: 'session_not_found' } },
+ agent: { status: 500, body: { error: 'synthetic_agent_failure' } },
+ });
+ const failure = await client.removeTurnFixture(ownedAgent, ownedSession).catch((error: unknown) => error);
+ expect(failure).toBeInstanceOf(AggregateError);
+ expect((failure as AggregateError).errors.map((error: Error) => error.message)).toEqual([
+ 'Archive fixture session failed: HTTP 404',
+ 'Remove fixture agent failed: {"error":"synthetic_agent_failure"}',
+ ]);
+ expect(calls).toEqual([`DELETE /api/sessions/${ownedSession}`, `DELETE /api/agents/${ownedAgent}`]);
+});
+
+test('Agent-only cleanup preserves the existing missing-Agent policy', async () => {
+ const { client, calls } = turnCleanupClient({ agent: { status: 404, body: { error: 'agent_not_found' } } });
+ await client.removeTurnFixture(ownedAgent, null);
+ expect(calls).toEqual([`DELETE /api/agents/${ownedAgent}`]);
+});
+
for (const override of [null, { hops: [] }, { hops: [{ source_id: 'src_operator', model_id: 'vendor/model' }] }]) {
test(`route cleanup preserves ${override === null ? 'absence' : override.hops.length ? 'manual hops' : 'explicit empty'}`, async () => {
let saved: AgentChain['manual_override'] = override;
diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.ts
index 53ff38df3..d0c98f513 100644
--- a/ui/e2e/support/api.ts
+++ b/ui/e2e/support/api.ts
@@ -93,6 +93,8 @@ export type Probe = {
error?: string | null;
};
+export type TurnReceipt = { ok: true; session_id: string; turn_id: string; queued: boolean };
+
export type RecordedTurn = {
turn_id: string;
ts: string;
@@ -372,20 +374,37 @@ export class HubApi {
return body.id;
}
- async sendTurn(sessionId: string, text: string): Promise<void> {
+ async sendTurn(sessionId: string, text: string): Promise<TurnReceipt> {
const result = await this.mutate('post', `/api/sessions/${sessionId}/messages`, { text });
- if (result.status !== 202) throw new Error(`Send turn failed: ${JSON.stringify(result.body)}`);
+ const body = result.body as Partial<TurnReceipt> | null;
+ // ui_server merges public_delivery_payload with dispatch_async's receipt.
+ if (result.status !== 202 || body?.ok !== true || body.session_id !== sessionId
+ || typeof body.turn_id !== 'string' || !/^trn_[a-f0-9]{32}$/.test(body.turn_id)
+ || typeof body.queued !== 'boolean') {
+ throw new Error(`Send turn did not return the exact accepted FSM receipt: HTTP ${result.status}`);
+ }
+ return { ok: true, session_id: body.session_id, turn_id: body.turn_id, queued: body.queued };
+ }
+
+ /** Archive owns lifecycle cancellation; an already-completed turn needs no Stop. */
+ async archiveTurnSession(sessionId: string): Promise<void> {
+ const path = `/api/sessions/${encodeURIComponent(sessionId)}`;
+ const result = await this.mutate('delete', path);
+ if (!result.ok) throw new Error(`Archive fixture session failed: HTTP ${result.status}`);
+ const archived = result.body as { id?: unknown; status?: unknown } | null;
+ if (archived?.id !== sessionId || archived?.status !== 'archived') {
+ throw new Error(`Archive fixture session response did not confirm archived identity: ${sessionId}`);
+ }
+ const stored = await this.read<{ id?: unknown; status?: unknown } | null>(path);
+ if (stored?.id !== sessionId || stored?.status !== 'archived') {
+ throw new Error(`Archive fixture session readback did not confirm archived identity: ${sessionId}`);
+ }
}
async removeTurnFixture(agentName: string, sessionId: string | null): Promise<void> {
const failures: unknown[] = [];
try {
- if (sessionId) {
- const canceled = await this.mutate('post', `/api/sessions/${sessionId}/cancel`, {});
- if (!canceled.ok) throw new Error(`Cancel fixture turn failed: ${JSON.stringify(canceled.body)}`);
- const archived = await this.mutate('delete', `/api/sessions/${sessionId}`);
- if (!archived.ok) throw new Error(`Archive fixture session failed: ${JSON.stringify(archived.body)}`);
- }
+ if (sessionId) await this.archiveTurnSession(sessionId);
} catch (error) {
failures.push(error);
}