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): give each gateway route and request its own identity (#1824)

Call White0b83f7c70379
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index bced3c4fd..58fab1793 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -487,6 +487,11 @@ def render_turn_outcome_copy(
return i18n_t(copy.key, language, **params)
+# The request id for a turn's own single attempt: the native CLI path, where
+# the turn and the request really are one thing.
+TURN_REQUEST = "turn"
+
+
@dataclass
class TurnTrace:
turn_id: str
@@ -496,7 +501,13 @@ class TurnTrace:
failed_attempts: list[dict] = field(default_factory=list)
served: Optional[dict] = None
terminal_error: Optional[dict] = None
- pending_attempt: Optional[AttemptIdentity] = None
+ # One entry per in-flight request, keyed by request id, in arrival order.
+ # An attempt identity describes a request, not a turn, and one launched
+ # process issues concurrent requests on one turn's credentials — so a
+ # single slot has each arrival overwrite the identity of whichever request
+ # is actually awaiting an upstream result, and the loser settles with no
+ # record of what served it.
+ pending_attempts: dict[str, AttemptIdentity] = field(default_factory=dict)
model_supply_state: Optional[SupplyState] = None
blockers: list[dict] = field(default_factory=list)
gateway_source_id: Optional[str] = None
@@ -505,6 +516,21 @@ class TurnTrace:
ambiguous: bool = False
terminal_outcome: TurnOutcomeProjectionInput | None = None
+ @property
+ def pending_attempt(self) -> Optional[AttemptIdentity]:
+ """The in-flight attempt this turn has been waiting on longest.
+
+ Turn-terminal readers — cancellation, interruption, settlement — need
+ one identity for a turn that may hold several. The oldest is the only
+ stable choice: entries are removed as their requests settle, so
+ whatever is still first arrived before all the others and cannot be
+ displaced by a later one.
+ """
+
+ for identity in self.pending_attempts.values():
+ return identity
+ return None
+
@dataclass
class ProcessScope:
@@ -514,6 +540,13 @@ class ProcessScope:
prepared_routes: dict[str, "PreparedGatewayRoute"] = field(default_factory=dict)
routing_conflicts: set[str] = field(default_factory=set)
untracked_use: bool = False
+ # The credential each route launched from this scope authenticates with,
+ # one per distinct route rather than one per launch. `token` identifies
+ # the process; these identify a route within it, which is what routing
+ # actually needs: an upstream model id is not unique across routes, so a
+ # credential that names only the process cannot answer which route a
+ # request for that model belongs to.
+ route_tokens: dict["PreparedGatewayRoute", str] = field(default_factory=dict)
@dataclass(frozen=True)
@@ -524,6 +557,22 @@ class PreparedGatewayRoute:
gateway_request_model_id: str
+@dataclass(frozen=True)
+class GatewayCredential:
+ """What a gateway credential answers for: a process, and maybe a route."""
+
+ scope_key: ScopeKey
+ route: Optional[PreparedGatewayRoute] = None
+
+
+@dataclass(frozen=True)
+class GatewayRouting:
+ """Where a gateway request goes, and which turn — if any — owns it."""
+
+ caller_model_id: Optional[str]
+ owner_turn_id: Optional[str]
+
+
class GatewayTurnTerminalizer:
"""One funnel for every exit after an exact gateway identity is prepared."""
@@ -537,9 +586,14 @@ class GatewayTurnTerminalizer:
self._registry = registry
self._backend = backend
self._token = token
+ # One gateway request, one identity. Every attempt this terminalizer
+ # records is filed under it, so concurrent requests on one turn cannot
+ # overwrite each other's provenance.
+ self._request_id = secrets.token_hex(8)
self.turn_id = registry._open_prepared_gateway_turn(
backend=backend,
token=token,
+ request_id=self._request_id,
)
self._stream_started = False
self._attempt_started = False
@@ -553,30 +607,22 @@ class GatewayTurnTerminalizer:
return
self._registry._terminalize_gateway_exit(
self.turn_id,
+ request_id=self._request_id,
stream_started=self._stream_started,
)
- def bind_request_model(self, model_id: str) -> Optional[str]:
- if self.turn_id is None:
- return None
- matched = self._registry.begin_gateway_request(
- backend=self._backend,
- token=self._token,
- requested_model_id=model_id,
- )
- if matched != self.turn_id:
- self.turn_id = None
- return self.turn_id
-
def resolution_model(self, gateway_model_id: str) -> Optional[str]:
"""Return the uniquely prepared caller model for this gateway request."""
- self.bind_request_model(gateway_model_id)
- return self._registry.gateway_resolution_model(
+ routing = self._registry.claim_gateway_request(
backend=self._backend,
token=self._token,
+ prepared_turn_id=self.turn_id,
+ request_id=self._request_id,
gateway_model_id=gateway_model_id,
)
+ self.turn_id = routing.owner_turn_id
+ return routing.caller_model_id
def fail(
self,
@@ -584,6 +630,7 @@ class GatewayTurnTerminalizer:
) -> None:
self._registry._terminalize_gateway_exit(
self.turn_id,
+ request_id=self._request_id,
reason=reason,
stream_started=self._stream_started,
force=True,
@@ -592,6 +639,7 @@ class GatewayTurnTerminalizer:
def engine_down(self) -> None:
self._registry._terminalize_gateway_exit(
self.turn_id,
+ request_id=self._request_id,
reason="engine_down",
stream_started=self._stream_started,
force=True,
@@ -606,6 +654,7 @@ class GatewayTurnTerminalizer:
self.turn_id,
supply_state,
blockers,
+ request_id=self._request_id,
)
def begin_attempt(
@@ -623,6 +672,7 @@ class GatewayTurnTerminalizer:
resolved_model_id=resolved_model_id,
channel=channel,
via_mapping=via_mapping,
+ request_id=self._request_id,
)
def finish_attempt(
@@ -636,6 +686,7 @@ class GatewayTurnTerminalizer:
self.turn_id,
outcome=outcome,
decision=decision,
+ request_id=self._request_id,
)
def mark_stream_started(self) -> None:
@@ -654,7 +705,10 @@ class GatewayTurnTerminalizer:
"""Clear a prepared-only attempt before the outer stopped settlement."""
if not self._attempt_started:
- self._registry.clear_prepared_attempt(self.turn_id)
+ self._registry.clear_prepared_attempt(
+ self.turn_id,
+ request_id=self._request_id,
+ )
self._downstream_canceled = True
@@ -756,7 +810,7 @@ class TurnCorrelationRegistry:
self.store = store
self._lock = threading.RLock()
self._scopes: dict[ScopeKey, ProcessScope] = {}
- self._token_scopes: dict[str, ScopeKey] = {}
+ self._credentials: dict[str, GatewayCredential] = {}
self._turn_scopes: dict[str, set[ScopeKey]] = {}
self._traces: dict[str, TurnTrace] = {}
@@ -782,7 +836,7 @@ class TurnCorrelationRegistry:
if scope is None:
scope = ProcessScope(token=secrets.token_urlsafe(32))
self._scopes[key] = scope
- self._token_scopes[scope.token] = key
+ self._credentials[scope.token] = GatewayCredential(scope_key=key)
# Frozen v3 has no discriminator for the shared OpenCode server.
if normalized_turn_id is None or backend == "opencode":
@@ -807,11 +861,43 @@ class TurnCorrelationRegistry:
def authenticates(self, backend: str, token: str) -> bool:
with self._lock:
authorized = False
- for candidate, key in self._token_scopes.items():
+ for candidate, credential in self._credentials.items():
matches = secrets.compare_digest(candidate, token)
- authorized = authorized or (matches and key[0] == backend)
+ authorized = authorized or (
+ matches and credential.scope_key[0] == backend
+ )
return authorized
+ def _credential(self, backend: str, token: str) -> Optional[GatewayCredential]:
+ """Resolve a token to what it answers for; call under `_lock`."""
+
+ credential = self._credentials.get(token)
+ if credential is None or credential.scope_key[0] != backend:
+ return None
+ return credential
+
+ def _route_credential(
+ self,
+ key: ScopeKey,
+ scope: ProcessScope,
+ route: PreparedGatewayRoute,
+ ) -> str:
+ """Return the credential a launch on this route authenticates with.
+
+ One credential per distinct route, not per launch: `authenticates`
+ compares against every credential in constant time, so the cost is
+ bounded by the routes a process actually uses rather than by how many
+ times it is launched. Re-launching the same route is the same routing
+ answer and reuses the same credential.
+ """
+
+ token = scope.route_tokens.get(route)
+ if token is None:
+ token = secrets.token_urlsafe(32)
+ scope.route_tokens[route] = token
+ self._credentials[token] = GatewayCredential(scope_key=key, route=route)
+ return token
+
def retire_scope(
self,
backend: str,
@@ -827,7 +913,9 @@ class TurnCorrelationRegistry:
scope = self._scopes.pop(key, None)
if scope is None:
return
- self._token_scopes.pop(scope.token, None)
+ self._credentials.pop(scope.token, None)
+ for route_token in scope.route_tokens.values():
+ self._credentials.pop(route_token, None)
for turn_id in scope.active_turns:
trace = self._traces.get(turn_id)
terminal_is_exact = (
@@ -847,9 +935,10 @@ class TurnCorrelationRegistry:
trace.ambiguous = True
def _exact_turn(self, backend: str, token: str) -> tuple[str, ScopeKey] | None:
- key = self._token_scopes.get(token)
- if key is None or key[0] != backend:
+ credential = self._credential(backend, token)
+ if credential is None:
return None
+ key = credential.scope_key
scope = self._scopes[key]
if scope.untracked_use or len(scope.active_turns) != 1:
for turn_id in scope.active_turns:
@@ -909,23 +998,32 @@ class TurnCorrelationRegistry:
source_id: str,
via_mapping: bool,
gateway_request_model_id: str | None = None,
- ) -> None:
- """Retain routing independently from best-effort provenance attribution."""
+ ) -> str:
+ """Bind a credential to this route, independently of attribution.
+
+ Returns the credential the launch must authenticate with. Routing is
+ answered from the credential, so the launch has to use this one rather
+ than the scope credential it passed in — a scope credential names only
+ the process, and an upstream model id is not unique across the routes
+ a process runs. Falls back to the given token when there is no route
+ to bind it to, so a caller can always use the return value.
+ """
with self._lock:
- key = self._token_scopes.get(token)
- if key is None or key[0] != backend:
- return
+ credential = self._credential(backend, token)
+ if credential is None:
+ return token
+ key = credential.scope_key
scope = self._scopes[key]
normalized_turn_id = str(turn_id or "").strip()
if normalized_turn_id:
if normalized_turn_id not in scope.active_turns:
- return
+ return token
route_turn_id = normalized_turn_id
else:
exact = self._exact_turn(backend, token)
if exact is None:
- return
+ return token
route_turn_id = exact[0]
request_model_id = gateway_request_model_id or resolved_model_id
prepared = PreparedGatewayRoute(
@@ -934,6 +1032,7 @@ class TurnCorrelationRegistry:
source_id=source_id,
gateway_request_model_id=request_model_id,
)
+ launch_token = self._route_credential(key, scope, prepared)
existing = scope.prepared_routes.get(route_turn_id)
if existing is not None and existing != prepared:
scope.prepared_routes.pop(route_turn_id, None)
@@ -943,10 +1042,10 @@ class TurnCorrelationRegistry:
exact = self._exact_turn(backend, token)
if exact is None:
- return
+ return launch_token
exact_turn_id, key = exact
if exact_turn_id != route_turn_id:
- return
+ return launch_token
trace = self._traces.setdefault(
exact_turn_id,
TurnTrace(
@@ -973,60 +1072,119 @@ class TurnCorrelationRegistry:
):
trace.ambiguous = True
self._scopes[key].ambiguous_turns.add(exact_turn_id)
- return
+ return launch_token
trace.gateway_source_id = source_id
trace.gateway_request_model_id = request_model_id
trace.gateway_model_id = resolved_model_id
+ return launch_token
- def gateway_resolution_model(
+ def claim_gateway_request(
self,
*,
backend: str,
token: str,
+ prepared_turn_id: Optional[str],
+ request_id: str = TURN_REQUEST,
gateway_model_id: str,
- ) -> Optional[str]:
- """Resolve only a route identity that the launching turn prepared."""
+ ) -> GatewayRouting:
+ """Route one gateway request and settle its attribution atomically.
+
+ Where the request goes, whether a live turn owns it, and whether the
+ attempt already opened for that turn still stands are one decision
+ about one request, so they are made in one critical section. Split
+ across two, a turn rotation lands in between: the turn that becomes
+ the sole live one is then told a model it never asked for arrived on
+ its token, which marks it ambiguous and drops the provenance of the
+ request it goes on to make itself.
+
+ The nested calls below re-enter `_lock`, which is an `RLock` for
+ exactly this reason — reusing the two public mutators keeps one
+ implementation of each rather than a `_locked` twin to keep in sync.
+ """
with self._lock:
- key = self._token_scopes.get(token)
- if key is None or key[0] != backend:
- return None
- scope = self._scopes[key]
- if scope.routing_conflicts.intersection(scope.active_turns):
- return None
- active_routes = [
- route
- for turn_id, route in scope.prepared_routes.items()
- if turn_id in scope.active_turns
- ]
- matching = [
- route
- for route in active_routes
- if route.gateway_request_model_id == gateway_model_id
- ]
- # A backend started before this upgrade may still send the resolved
- # upstream id. Prefer the canonical request id, then accept the old
- # shape only when it still identifies one prepared route.
- if not matching:
- matching = [
- route
- for route in active_routes
- if route.resolved_model_id == gateway_model_id
- ]
- identities = {
- (
- route.requested_model_id,
- route.resolved_model_id,
- route.source_id,
- route.gateway_request_model_id,
+ caller_model_id, claimed = self._route_gateway_model(
+ backend=backend,
+ token=token,
+ gateway_model_id=gateway_model_id,
+ )
+ if prepared_turn_id is None:
+ return GatewayRouting(caller_model_id, None)
+ if claimed:
+ owner = self.begin_gateway_request(
+ backend=backend,
+ token=token,
+ requested_model_id=gateway_model_id,
)
- for route in matching
- }
- if len(identities) == 1:
- return matching[0].requested_model_id
- if active_routes:
- return None
- return gateway_model_id if scope.untracked_use else None
+ if owner != prepared_turn_id:
+ owner = None
+ return GatewayRouting(caller_model_id, owner)
+ # Routing was answered from this request's own credential, so no
+ # live turn owns it and its own turn has already settled — there
+ # is nothing left to attribute it to. The attempt armed for the
+ # live turn on the way in therefore has to be given back: left
+ # behind, it settles that turn as having canceled or interrupted a
+ # Hub attempt it never made. It cannot be armed later instead,
+ # because `fail` runs before this call and needs a turn to fail.
+ self.clear_prepared_attempt(prepared_turn_id, request_id=request_id)
+ return GatewayRouting(caller_model_id, None)
+
+ def _route_gateway_model(
+ self,
+ *,
+ backend: str,
+ token: str,
+ gateway_model_id: str,
+ ) -> tuple[Optional[str], bool]:
+ """Resolve where this gateway request goes; call under `_lock`.
+
+ Routing is a property of the credential, not of the turn windows that
+ happen to be open. The credential was minted for one route when the
+ process was launched, so it answers for that route for as long as the
+ process lives — through CLI tool loops, agent-initiated turns, and
+ transport retries, none of which arrive inside a dispatched-turn
+ window.
+
+ Returns the caller model to route by, and whether a live turn claims
+ it and may therefore be credited with the request.
+ """
+
+ credential = self._credential(backend, token)
+ if credential is None:
+ return None, False
+ scope = self._scopes[credential.scope_key]
+ route = credential.route
+ if route is None:
+ # No route was known when this credential was minted: the shared
+ # OpenCode server, and any launch Avibe did not map. There the
+ # wire model id really is the route key, because one credential
+ # serves every model the process may name.
+ return (gateway_model_id if scope.untracked_use else None), False
+ if gateway_model_id not in {
+ route.gateway_request_model_id,
+ route.resolved_model_id,
+ }:
+ # This credential was minted for one route, and the route knows
+ # both model ids a request on it may legitimately name: the id the
+ # launch was told to send, and the resolved upstream id a backend
+ # started before that became explicit still sends. A request for
+ # anything else belongs to no route the process was launched on —
+ # a CLI naming its own model, most often — and answering it from
+ # some other route would be exactly the aliasing this credential
+ # exists to prevent. Accepting both ids cannot alias here: the
+ # credential already named the route, so there is no second route
+ # for the legacy id to be confused with.
+ return None, False
+ # A live turn claims this request when it prepared this same route.
+ # The whole route must match, not just the upstream model: two routes
+ # can resolve to one upstream model id, and crediting a turn for a
+ # request that belongs to the other one is how a turn ends up
+ # ambiguous over a model it never asked for.
+ claimed = any(
+ prepared == route and turn_id in scope.active_turns
+ for turn_id, prepared in scope.prepared_routes.items()
+ )
+ return route.requested_model_id, claimed
def gateway_terminalizer(
self,
@@ -1045,7 +1203,17 @@ class TurnCorrelationRegistry:
*,
backend: str,
token: str,
+ request_id: str = TURN_REQUEST,
) -> Optional[str]:
+ """Arm the launch identity for one gateway request.
+
+ The identity is filed under this request, so arming it can neither
+ displace nor be displaced by a concurrent request on the same turn.
+ Arming has to happen here, before any model id is read, because a
+ request can fail on its parameters before it ever names a model and
+ that failure still needs a turn to land on.
+ """
+
with self._lock:
exact = self._exact_turn(backend, token)
if exact is None:
@@ -1058,28 +1226,42 @@ class TurnCorrelationRegistry:
or trace.gateway_model_id is None
):
return None
- trace.pending_attempt = AttemptIdentity(
+ trace.pending_attempts[request_id] = AttemptIdentity(
source_id=trace.gateway_source_id,
resolved_model_id=trace.gateway_model_id,
channel="hub",
)
return turn_id
- def clear_prepared_attempt(self, turn_id: Optional[str]) -> None:
- """Remove the launch identity when cancellation precedes invocation."""
+ def clear_prepared_attempt(
+ self,
+ turn_id: Optional[str],
+ *,
+ request_id: str = TURN_REQUEST,
+ ) -> None:
+ """Remove one request's launch identity when it never invokes.
+
+ Only this request's own entry is removed. A peer awaiting an upstream
+ result keeps its identity, which is the whole point of filing attempts
+ per request: `finish_attempt` reconstructs nothing from an empty
+ entry, so taking a peer's would lose its provenance for good.
+ """
if turn_id is None:
return
with self._lock:
trace = self._traces.get(turn_id)
- if trace is not None and trace.pending_attempt is not None:
- if trace.pending_attempt.channel == "hub":
- trace.pending_attempt = None
+ if trace is None:
+ return
+ identity = trace.pending_attempts.get(request_id)
+ if identity is not None and identity.channel == "hub":
+ trace.pending_attempts.pop(request_id, None)
def _terminalize_gateway_exit(
self,
turn_id: Optional[str],
*,
+ request_id: str = TURN_REQUEST,
reason: Literal[
"invalid_parameter",
"protocol_error",
@@ -1099,13 +1281,14 @@ class TurnCorrelationRegistry:
or trace.terminal_error is not None
or trace.model_supply_state is not None
or (
- trace.pending_attempt is None
+ trace.pending_attempts.get(request_id) is None
and bool(trace.failed_attempts)
)
):
return
if reason == "engine_down":
- trace.pending_attempt = None
+ # The engine, not one request, is what went down.
+ trace.pending_attempts.clear()
trace.served = None
trace.model_supply_state = None
trace.blockers = []
@@ -1117,7 +1300,7 @@ class TurnCorrelationRegistry:
"stream_started": stream_started,
}
return
- identity = trace.pending_attempt
+ identity = trace.pending_attempts.get(request_id)
if identity is None and (
trace.gateway_source_id is not None
and trace.gateway_model_id is not None
@@ -1129,7 +1312,7 @@ class TurnCorrelationRegistry:
)
if identity is None or identity.channel != "hub":
return
- trace.pending_attempt = None
+ trace.pending_attempts.pop(request_id, None)
trace.served = None
trace.terminal_error = {
**identity.payload(),
@@ -1165,7 +1348,8 @@ class TurnCorrelationRegistry:
scope_key=exact[1],
),
)
- trace.pending_attempt = AttemptIdentity(
+ # A native turn is one request by construction.
+ trace.pending_attempts[TURN_REQUEST] = AttemptIdentity(
source_id=source_id,
resolved_model_id=resolved_model_id,
channel="native_cli",
@@ -1206,13 +1390,17 @@ class TurnCorrelationRegistry:
turn_id: Optional[str],
supply_state: SupplyState,
blockers: Iterable[ExactHopBlocker] = (),
+ *,
+ request_id: str = TURN_REQUEST,
) -> None:
if turn_id is None:
return
with self._lock:
trace = self._traces.get(turn_id)
if trace is not None:
- trace.pending_attempt = None
+ # Only this request found nothing to call; a peer still
+ # awaiting an upstream result keeps its identity.
+ trace.pending_attempts.pop(request_id, None)
trace.served = None
trace.terminal_error = None
trace.model_supply_state = supply_state
@@ -1238,6 +1426,7 @@ class TurnCorrelationRegistry:
resolved_model_id: str,
channel: SupplyChannel,
via_mapping: bool,
+ request_id: str = TURN_REQUEST,
) -> None:
if turn_id is None:
return
@@ -1245,7 +1434,7 @@ class TurnCorrelationRegistry:
trace = self._traces.get(turn_id)
if trace is None:
return
- trace.pending_attempt = AttemptIdentity(
+ trace.pending_attempts[request_id] = AttemptIdentity(
source_id=source_id,
resolved_model_id=resolved_model_id,
channel=channel,
@@ -1264,14 +1453,14 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(normalized)
- if (
- trace is None
- or trace.pending_attempt is None
- or trace.pending_attempt.channel != "native_cli"
- ):
+ identity = (
+ trace.pending_attempts.get(TURN_REQUEST)
+ if trace is not None
+ else None
+ )
+ if trace is None or identity is None or identity.channel != "native_cli":
return
- identity = trace.pending_attempt
- trace.pending_attempt = None
+ trace.pending_attempts.pop(TURN_REQUEST, None)
trace.served = None
trace.terminal_error = None
trace.failed_attempts.append(
@@ -1296,7 +1485,8 @@ class TurnCorrelationRegistry:
)
if payload is None or payload.get("channel") != "hub":
return
- trace.pending_attempt = None
+ # The backend rejected the turn's result, not one request's.
+ trace.pending_attempts.clear()
trace.served = None
trace.terminal_error = {
**payload,
@@ -1310,12 +1500,14 @@ class TurnCorrelationRegistry:
*,
outcome: RawCallOutcome,
decision: ResolutionDecision,
+ request_id: str = TURN_REQUEST,
) -> None:
if turn_id is None:
return
if decision.error_code == "engine_down":
self._terminalize_gateway_exit(
turn_id,
+ request_id=request_id,
reason="engine_down",
stream_started=outcome.stream_started,
force=True,
@@ -1323,10 +1515,12 @@ class TurnCorrelationRegistry:
return
with self._lock:
trace = self._traces.get(turn_id)
- if trace is None or trace.pending_attempt is None:
+ identity = (
+ trace.pending_attempts.get(request_id) if trace is not None else None
+ )
+ if trace is None or identity is None:
return
- identity = trace.pending_attempt
- trace.pending_attempt = None
+ trace.pending_attempts.pop(request_id, None)
if decision.action == "return":
trace.served = identity.payload()
trace.terminal_error = None
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index f164b1243..bec4232f9 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -335,7 +335,10 @@ class ModelHubTurnGateway:
scope = str(process_scope or "").strip() or f"{backend}:untracked"
token = self.correlation.credentials(backend, scope, turn_id)
if requested_model_id and resolved_model_id and source_id:
- self.correlation.prepare_gateway_turn(
+ # Preparing the route hands back the credential bound to it. The
+ # launch must authenticate with that one: routing is answered from
+ # the credential, and the scope credential names only the process.
+ token = self.correlation.prepare_gateway_turn(
backend=backend,
token=token,
turn_id=turn_id,
diff --git a/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
index 3b8b84caf..13ffb7612 100644
--- a/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
@@ -562,10 +562,9 @@ def test_mh_turn_outcomes_and_cancel_are_closed_provenance_products(tmp_path: Pa
records: list[dict] = []
def terminalizer(turn_id: str):
- token = registry.credentials("claude", f"scope-{turn_id}", turn_id)
- registry.prepare_gateway_turn(
+ token = registry.prepare_gateway_turn(
backend="claude",
- token=token,
+ token=registry.credentials("claude", f"scope-{turn_id}", turn_id),
requested_model_id="scenario-model",
resolved_model_id="scenario-model",
source_id="src_outcome01",
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index aee95f5e6..45575e6e2 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -1088,10 +1088,9 @@ def _prepared_gateway_request(
source_id: str,
stream: bool,
) -> SimpleNamespace:
- token = gateway.correlation.credentials("codex", "/repo", turn_id)
- gateway.correlation.prepare_gateway_turn(
+ token = gateway.correlation.prepare_gateway_turn(
backend="codex",
- token=token,
+ token=gateway.correlation.credentials("codex", "/repo", turn_id),
requested_model_id=requested_model,
resolved_model_id="shared-model",
source_id=source_id,
@@ -1434,6 +1433,15 @@ def test_retired_process_scope_revokes_token_and_fails_closed(
store = BoundedProvenanceStore(tmp_path / "retired-scope.json")
registry = TurnCorrelationRegistry(store)
token = registry.credentials("codex", "/repo", "turn_evicted")
+ launch = registry.prepare_gateway_turn(
+ backend="codex",
+ token=token,
+ requested_model_id="shared-model",
+ resolved_model_id="shared-model",
+ source_id="src_primary01",
+ via_mapping=False,
+ )
+ assert launch != token
turn_id = registry.begin_gateway_request(
backend="codex",
token=token,
@@ -1449,7 +1457,10 @@ def test_retired_process_scope_revokes_token_and_fails_closed(
registry.retire_scope("codex", "/repo")
+ # Every credential the scope minted is revoked, not only the one that
+ # names the process: a launch credential is as good as a token.
assert registry.authenticates("codex", token) is False
+ assert registry.authenticates("codex", launch) is False
replacement = registry.credentials("codex", "/repo", "turn_replacement")
assert replacement != token
assert registry.authenticates("codex", replacement) is True
@@ -1467,7 +1478,7 @@ def test_retired_process_scope_revokes_token_and_fails_closed(
)
registry.retire_scope("codex", "/repo")
assert registry._scopes == {}
- assert registry._token_scopes == {}
+ assert registry._credentials == {}
def test_terminal_failure_survives_exact_scope_retirement(
@@ -1546,6 +1557,584 @@ def test_terminal_retirement_does_not_restore_ambiguous_scope(
assert store.get("turn_first") is None
+def _routing_registry(tmp_path: Path, label: str) -> tuple[TurnCorrelationRegistry, str]:
+ store = BoundedProvenanceStore(tmp_path / f"routing-{label}.json")
+ registry = TurnCorrelationRegistry(store)
+ return registry, registry.credentials("claude", "session:/repo", "turn_route01")
+
+
+def _prepare_route(
+ registry: TurnCorrelationRegistry,
+ token: str,
+ *,
+ turn_id: str,
+ requested: str,
+ resolved: str,
+ source_id: str = "src_primary01",
+) -> str:
+ """Prepare a route and return the credential its launch must use.
+
+ Mirrors `ModelHubTurnGateway.endpoint`: the scope credential goes in, the
+ credential bound to this route comes back, and that is the one the
+ launched process authenticates with.
+ """
+
+ return registry.prepare_gateway_turn(
+ backend="claude",
+ token=token,
+ turn_id=turn_id,
+ requested_model_id=requested,
+ resolved_model_id=resolved,
+ source_id=source_id,
+ via_mapping=True,
+ )
+
+
+def _resolution(registry: TurnCorrelationRegistry, token: str, model: str) -> str | None:
+ return registry.claim_gateway_request(
+ backend="claude",
+ token=token,
+ prepared_turn_id=None,
+ gateway_model_id=model,
+ ).caller_model_id
+
+
+ "arrives",
+ [
+ pytest.param("after_its_turn_settled", id="after_its_turn_settled"),
+ pytest.param("while_another_model_is_live", id="while_another_model_is_live"),
+ ],
+)
+def test_gateway_keeps_a_live_process_routable_outside_its_turn_windows(
+ tmp_path: Path,
+ arrives: str,
+) -> None:
+ """Routing is a property of the process scope, not of an open turn window.
+
+ A launched CLI keeps issuing gateway requests between the turns Avibe
+ dispatches — tool loops, agent-initiated continuations, transport retries.
+ Those requests carry the upstream model id, which only the route the
+ process was launched on can translate back into the caller model the
+ resolver routes from, so routing tied to an open turn window makes every
+ one of them unroutable.
+ """
+
+ registry, token = _routing_registry(tmp_path, arrives)
+ route_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_route01",
+ requested="caller-model",
+ resolved="hub-model",
+ )
+ registry.settle(
+ "turn_route01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ if arrives == "while_another_model_is_live":
+ # A dispatched turn on a different model is the common case: the CLI
+ # keeps finishing work for the previous one. Its route answers for the
+ # model it prepared and must say nothing about any other.
+ registry.credentials("claude", "session:/repo", "turn_route02")
+ _prepare_route(
+ registry,
+ token,
+ turn_id="turn_route02",
+ requested="other-caller",
+ resolved="other-hub-model",
+ )
+
+ assert _resolution(registry, route_token, "hub-model") == "caller-model"
+ # Reach follows the route this launch was made on, so a model that route
+ # does not name stays unroutable rather than becoming reachable by naming
+ # it — including one another launch on the same process can reach.
+ assert _resolution(registry, route_token, "never-routed") is None
+ assert _resolution(registry, route_token, "other-hub-model") is None
+
+
+ ("scenario", "rival_caller", "rival_source"),
+ [
+ pytest.param("two_caller_models", "rival-caller", "src_primary01", id="two_caller_models"),
+ pytest.param("two_sources", "caller-model", "src_backup001", id="two_sources"),
+ ],
+)
+def test_gateway_answers_each_route_that_aliases_one_upstream_model(
+ tmp_path: Path,
+ scenario: str,
+ rival_caller: str,
+ rival_source: str,
+) -> None:
+ """A request is routed by the credential it arrives on, not by its model.
+
+ Two menu entries may resolve to one upstream model — deliberately, as two
+ price tiers or two Sources for the same model — and one process scope
+ launches both. The wire carries the upstream id alone, so a credential
+ naming only the process cannot say which of them a request belongs to, and
+ the routing table has to either guess or refuse. Binding the credential to
+ the route removes the question: each launch answers for its own route, and
+ that stays true once the turns that prepared them have settled.
+ """
+
+ registry, token = _routing_registry(tmp_path, scenario)
+ registry.credentials("claude", "session:/repo", "turn_route02")
+ first = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_route01",
+ requested="caller-model",
+ resolved="hub-model",
+ source_id="src_primary01",
+ )
+ rival = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_route02",
+ requested=rival_caller,
+ resolved="hub-model",
+ source_id=rival_source,
+ )
+
+ assert first != rival
+ for turn_id in (None, "turn_route01", "turn_route02"):
+ if turn_id is not None:
+ registry.settle(
+ turn_id,
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ assert _resolution(registry, first, "hub-model") == "caller-model"
+ assert _resolution(registry, rival, "hub-model") == rival_caller
+ # The scope credential names the process and no route, so it answers
+ # for neither rather than picking one.
+ assert _resolution(registry, token, "hub-model") is None
+
+
+def test_gateway_routing_dies_with_the_process_scope(tmp_path: Path) -> None:
+ """A retired scope revokes its credentials, so its routes stop answering.
+
+ Every credential the scope minted, not only the one that names the process
+ itself: a launch credential outliving its scope would keep a dead
+ runtime's routes answering on a token nothing can revoke.
+ """
+
+ registry, token = _routing_registry(tmp_path, "retired")
+ route_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_route01",
+ requested="caller-model",
+ resolved="hub-model",
+ )
+ registry.settle(
+ "turn_route01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ assert _resolution(registry, route_token, "hub-model") == "caller-model"
+
+ registry.retire_scope("claude", "session:/repo")
+
+ assert registry.authenticates("claude", token) is False
+ assert registry.authenticates("claude", route_token) is False
+ assert _resolution(registry, route_token, "hub-model") is None
+
+
+ ("settled_resolved", "live_resolved"),
+ [
+ pytest.param("hub-settled", "hub-live", id="distinct_upstream_models"),
+ pytest.param("hub-shared", "hub-shared", id="one_aliased_upstream_model"),
+ ],
+)
+def test_gateway_attributes_a_request_only_to_a_turn_that_claims_its_model(
+ tmp_path: Path,
+ settled_resolved: str,
+ live_resolved: str,
+) -> None:
+ """Serving a scope-routed request must not cost the live turn its record.
+
+ Routing and attribution share one entry point, so an out-of-turn request is
+ resolved while some unrelated turn is the only open window. Binding it there
+ would tell that turn a model it never asked for arrived on its token, which
+ marks it ambiguous — and an ambiguous trace makes `settle` drop the record
+ for the request the turn goes on to make itself.
+
+ A live turn's claim is its whole route, not the upstream model the route
+ ends at, so the aliased case holds too: two menu entries resolving to one
+ upstream model are two routes, and the live one owns only its own.
+ """
+
+ store = BoundedProvenanceStore(tmp_path / "routing-attribution.json")
+ registry = TurnCorrelationRegistry(store)
+ token = registry.credentials("claude", "session:/repo", "turn_settled01")
+ settled_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_settled01",
+ requested="caller-settled",
+ resolved=settled_resolved,
+ )
+ registry.settle(
+ "turn_settled01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ assert registry.credentials("claude", "session:/repo", "turn_live01") == token
+ live_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_live01",
+ requested="caller-live",
+ resolved=live_resolved,
+ )
+
+ with registry.gateway_terminalizer(
+ backend="claude",
+ token=settled_token,
+ ) as out_of_turn:
+ assert out_of_turn.resolution_model(settled_resolved) == "caller-settled"
+ # Its own turn has already settled, so there is nothing to attribute to.
+ assert out_of_turn.turn_id is None
+
+ with registry.gateway_terminalizer(backend="claude", token=live_token) as live:
+ assert live.resolution_model(live_resolved) == "caller-live"
+ assert live.turn_id == "turn_live01"
+
+ registry.settle(
+ "turn_live01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ record = store.get("turn_live01")
+ assert record is not None
+ assert record["terminal_error"] == {
+ "source_id": "src_primary01",
+ "configured_model_id": live_resolved,
+ "channel": "hub",
+ "reason": "protocol_error",
+ "stream_started": False,
+ }
+
+
+def test_a_canceled_turn_reports_the_attempt_it_waited_on_longest(
+ tmp_path: Path,
+) -> None:
+ """A turn holding several requests reports the one in flight the longest.
+
+ The settlement record has one attempt slot, but a live process issues
+ concurrent requests on one turn and each carries its own identity — a
+ request that fell back to a backup Source is not the same attempt as a peer
+ still holding the primary. The slot has to name one of them, and the oldest
+ entry is the only stable answer: entries are removed as their requests
+ settle, so whatever is still first arrived before all the others and no
+ later request can displace it.
+ """
+
+ store = BoundedProvenanceStore(tmp_path / "routing-oldest.json")
+ registry = TurnCorrelationRegistry(store)
+ token = registry.credentials("claude", "session:/repo", "turn_live01")
+ live_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_live01",
+ requested="caller-live",
+ resolved="hub-live",
+ )
+
+ with registry.gateway_terminalizer(backend="claude", token=live_token) as first:
+ assert first.resolution_model("hub-live") == "caller-live"
+ # This request fell back to a backup hop and is awaiting upstream.
+ first.begin_attempt(
+ source_id="src_backup001",
+ resolved_model_id="hub-live",
+ channel="hub",
+ via_mapping=True,
+ )
+ with registry.gateway_terminalizer(
+ backend="claude",
+ token=live_token,
+ ) as second:
+ assert second.resolution_model("hub-live") == "caller-live"
+ # Cancelled while both are open, before either has settled.
+ registry.settle(
+ "turn_live01",
+ settled_by=SETTLED_BY_STOPPED,
+ ts=NOW.isoformat(),
+ )
+
+ record = store.get("turn_live01")
+ assert record is not None
+ assert record["outcome"] == "canceled"
+ assert record["canceled_attempt"] == {
+ "source_id": "src_backup001",
+ "configured_model_id": "hub-live",
+ "channel": "hub",
+ }
+
+
+def test_an_unclaimed_request_leaves_no_attempt_on_the_live_turn(
+ tmp_path: Path,
+) -> None:
+ """A turn that issued no gateway request must settle as having made none.
+
+ The terminalizer opens the live turn's attempt on the way in, before any
+ model id has been read — `fail` runs before routing and needs a turn to
+ fail. So a request routed from scope history has to give that attempt back
+ on its way out: left armed, it settles the live turn as having canceled or
+ interrupted a Hub attempt that only ever belonged to the settled turn.
+ """
+
+ store = BoundedProvenanceStore(tmp_path / "routing-phantom.json")
+ registry = TurnCorrelationRegistry(store)
+ token = registry.credentials("claude", "session:/repo", "turn_settled01")
+ settled_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_settled01",
+ requested="caller-settled",
+ resolved="hub-settled",
+ )
+ registry.settle(
+ "turn_settled01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ assert registry.credentials("claude", "session:/repo", "turn_live01") == token
+ _prepare_route(
+ registry,
+ token,
+ turn_id="turn_live01",
+ requested="caller-live",
+ resolved="hub-live",
+ )
+
+ with registry.gateway_terminalizer(
+ backend="claude",
+ token=settled_token,
+ ) as out_of_turn:
+ assert out_of_turn.resolution_model("hub-settled") == "caller-settled"
+
+ registry.settle(
+ "turn_live01",
+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ assert store.get("turn_live01") is None
+
+
+def test_an_unclaimed_request_leaves_an_attempt_in_flight_untouched(
+ tmp_path: Path,
+) -> None:
+ """A request records what it attempted, whoever else is on its turn.
+
+ An attempt identity describes one request, and a live process issues
+ concurrent ones on one turn. So a delayed request for a settled turn's
+ route arrives while the live turn's own request is awaiting an upstream
+ result, and it touches the turn's pending state twice: on the way in to
+ arm a launch identity, and on the way out to give it back. Either move,
+ aimed at the turn rather than at the request, erases the attempt actually
+ in flight — and `finish_attempt` reconstructs nothing from an absent one,
+ so the live turn settles having served a model with no record of which
+ Source and model served it.
+
+ Stated as the surviving provenance rather than as the two moves, so any
+ later route to the same erasure fails here.
+ """
+
+ store = BoundedProvenanceStore(tmp_path / "routing-concurrent.json")
+ registry = TurnCorrelationRegistry(store)
+ token = registry.credentials("claude", "session:/repo", "turn_settled01")
+ settled_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_settled01",
+ requested="caller-settled",
+ resolved="hub-settled",
+ )
+ registry.settle(
+ "turn_settled01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ assert registry.credentials("claude", "session:/repo", "turn_live01") == token
+ live_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_live01",
+ requested="caller-live",
+ resolved="hub-live",
+ source_id="src_live0001",
+ )
+
+ with registry.gateway_terminalizer(backend="claude", token=live_token) as live:
+ assert live.resolution_model("hub-live") == "caller-live"
+ live.begin_attempt(
+ source_id="src_live0001",
+ resolved_model_id="hub-live",
+ channel="hub",
+ via_mapping=True,
+ )
+ # The live request is now awaiting upstream. A delayed request for the
+ # settled turn's route lands on the same process and same live turn.
+ with registry.gateway_terminalizer(
+ backend="claude",
+ token=settled_token,
+ ) as delayed:
+ assert delayed.resolution_model("hub-settled") == "caller-settled"
+ success = _outcome(RawOutcomeKind.SUCCESS, source_id="src_live0001")
+ live.finish_attempt(outcome=success, decision=classify_outcome(success))
+
+ registry.settle(
+ "turn_live01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ record = store.get("turn_live01")
+ assert record is not None
+ assert record["served"] == {
+ "source_id": "src_live0001",
+ "configured_model_id": "hub-live",
+ "channel": "hub",
+ }
+
+
+def test_a_request_gives_back_only_its_own_launch_identity(
+ tmp_path: Path,
+) -> None:
+ """Giving back a launch identity must not take a real attempt with it.
+
+ The reverse arrival order of the test above: a delayed request arms its
+ launch identity first, and only then does the live request begin its own
+ attempt. The delayed one is now stale, and it names the same Source and
+ model as the live attempt whenever the live request went out on its
+ primary hop — which is the ordinary case. So a give-back cannot be decided
+ by what a launch identity looks like, only by whose it is; by value the two
+ are indistinguishable, and the live turn loses the provenance of a request
+ it really did make.
+ """
+
+ store = BoundedProvenanceStore(tmp_path / "routing-stale-prep.json")
+ registry = TurnCorrelationRegistry(store)
+ token = registry.credentials("claude", "session:/repo", "turn_settled01")
+ settled_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_settled01",
+ requested="caller-settled",
+ resolved="hub-settled",
+ )
+ registry.settle(
+ "turn_settled01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ assert registry.credentials("claude", "session:/repo", "turn_live01") == token
+ live_token = _prepare_route(
+ registry,
+ token,
+ turn_id="turn_live01",
+ requested="caller-live",
+ resolved="hub-live",
+ source_id="src_live0001",
+ )
+
+ # The delayed request arms its launch identity first.
+ with registry.gateway_terminalizer(
+ backend="claude",
+ token=settled_token,
+ ) as delayed:
+ # Only then does the live request begin its own attempt, on the primary
+ # hop — the same Source and model the identity above named.
+ with registry.gateway_terminalizer(backend="claude", token=live_token) as live:
+ assert live.resolution_model("hub-live") == "caller-live"
+ live.begin_attempt(
+ source_id="src_live0001",
+ resolved_model_id="hub-live",
+ channel="hub",
+ via_mapping=True,
+ )
+ assert delayed.resolution_model("hub-settled") == "caller-settled"
+ success = _outcome(RawOutcomeKind.SUCCESS, source_id="src_live0001")
+ live.finish_attempt(outcome=success, decision=classify_outcome(success))
+
+ registry.settle(
+ "turn_live01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ record = store.get("turn_live01")
+ assert record is not None
+ assert record["served"] == {
+ "source_id": "src_live0001",
+ "configured_model_id": "hub-live",
+ "channel": "hub",
+ }
+
+
+def test_gateway_serves_a_request_that_arrives_after_its_turn_settled(
+ tmp_path: Path,
+) -> None:
+ """The 409 this fixes, end to end: same request, before and after settlement.
+
+ ``service.adapter.invocations`` is the evidence that the caller model was
+ the routing input — only the route keyed by it carries this hop.
+ """
+
+ async def exercise() -> None:
+ primary = _source(
+ "src_primary01",
+ "Primary",
+ vendor="anthropic",
+ protocol="anthropic",
+ model_id="hub-model",
+ )
+ service = _service(
+ tmp_path,
+ sources=[primary],
+ outcomes=[_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id)],
+ )
+ service.store.config.agents["claude"].routes["caller-model"] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(primary.id, "hub-model"),)
+ )
+ gateway = ModelHubTurnGateway(service)
+ base_url, token = await gateway.endpoint(
+ "claude",
+ process_scope="session:/repo",
+ turn_id="turn_between_windows",
+ requested_model_id="caller-model",
+ resolved_model_id="hub-model",
+ source_id=primary.id,
+ )
+ gateway.correlation.settle(
+ "turn_between_windows",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts=NOW.isoformat(),
+ )
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ response = await client.post(
+ f"{base_url}/v1/messages",
+ json={
+ "model": "hub-model",
+ "max_tokens": 1,
+ "messages": [{"role": "user", "content": "ping"}],
+ "stream": False,
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ )
+ assert response.status == 200
+ await response.read()
+ finally:
+ await gateway.close()
+
+ assert service.adapter.invocations == [(primary.id, "hub-model", "claude")]
+
+ asyncio.run(exercise())
+
+
def test_gateway_models_endpoint_serves_authenticated_backend_catalog(
tmp_path: Path,
) -> None:
@@ -1817,10 +2406,9 @@ def test_no_candidate_provenance_carries_exact_hop_blockers_from_each_entry(
blockers=blockers,
)
else:
- token = registry.credentials("claude", "/repo", turn_id)
- registry.prepare_gateway_turn(
+ token = registry.prepare_gateway_turn(
backend="claude",
- token=token,
+ token=registry.credentials("claude", "/repo", turn_id),
requested_model_id="shared-model",
resolved_model_id="shared-model",
source_id="src_primary01",
@@ -4040,15 +4628,31 @@ def test_gateway_provenance_retains_pre_mapping_model_identity(
_assert_valid("turn-provenance.schema.json", record)
+ "wire_model_id",
+ [
+ pytest.param("alias-a", id="canonical_backend_id"),
+ pytest.param("model-b", id="legacy_upstream_target"),
+ ],
+)
def test_gateway_accepts_canonical_backend_id_and_unique_legacy_target(
tmp_path: Path,
+ wire_model_id: str,
) -> None:
+ """A route answers for both model ids a request on it may name.
+
+ The launch is told which id to send, so that one is canonical. A process
+ started before Avibe made it explicit still sends the resolved upstream
+ id, and its requests must keep routing: the credential already named the
+ route, so accepting the older shape resolves an alias rather than
+ guessing between routes.
+ """
+
store = BoundedProvenanceStore(tmp_path / "provenance.json")
registry = TurnCorrelationRegistry(store)
- token = registry.credentials("codex", "/repo", "turn_alias")
- registry.prepare_gateway_turn(
+ launch_token = registry.prepare_gateway_turn(
backend="codex",
- token=token,
+ token=registry.credentials("codex", "/repo", "turn_alias"),
requested_model_id="alias-a",
resolved_model_id="model-b",
source_id="src_primary01",
@@ -4056,39 +4660,16 @@ def test_gateway_accepts_canonical_backend_id_and_unique_legacy_target(
gateway_request_model_id="alias-a",
)
- assert (
- registry.begin_gateway_request(
- backend="codex",
- token=token,
- requested_model_id="alias-a",
- )
- == "turn_alias"
- )
- assert (
- registry.gateway_resolution_model(
- backend="codex",
- token=token,
- gateway_model_id="alias-a",
- )
- == "alias-a"
- )
- assert (
- registry.begin_gateway_request(
- backend="codex",
- token=token,
- requested_model_id="model-b",
- )
- == "turn_alias"
- )
- assert (
- registry.gateway_resolution_model(
- backend="codex",
- token=token,
- gateway_model_id="model-b",
- )
- == "alias-a"
+ routing = registry.claim_gateway_request(
+ backend="codex",
+ token=launch_token,
+ prepared_turn_id="turn_alias",
+ gateway_model_id=wire_model_id,
)
+ assert routing.caller_model_id == "alias-a"
+ assert routing.owner_turn_id == "turn_alias"
+
def test_gateway_uses_persisted_exact_hops_for_failover(
tmp_path: Path,
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 2d6ca8cfb..6c389476c 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -1034,6 +1034,59 @@ def test_g5_terminalizer_fail_is_validation_only() -> None:
)
+def test_routing_a_gateway_request_and_attributing_it_are_one_critical_section() -> None:
+ """Review 5092034678: a turn rotation must not land between the two.
+
+ Where a gateway request goes and which turn may be credited with it are one
+ decision about one request. Resolved under one acquisition of the lock and
+ bound under another, a turn can settle in the gap: whichever turn becomes
+ the sole live one is then told a model it never asked for arrived on its
+ token, which marks it ambiguous and drops the provenance of the request it
+ goes on to make itself.
+
+ Stated as "whoever routes also attributes, under one held lock" rather than
+ naming the owner, so splitting the decision back apart fails here however
+ the pieces are renamed or moved.
+ """
+
+ attribution = {"begin_gateway_request", "clear_prepared_attempt"}
+ routing_owners: set[str] = set()
+ for name, fn in _functions(_tree(PROVENANCE)).items():
+ routing = [
+ node
+ for node in ast.walk(fn)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "_route_gateway_model"
+ ]
+ if not routing:
+ continue
+ routing_owners.add(name)
+ held = [
+ node
+ for node in ast.walk(fn)
+ if isinstance(node, ast.With)
+ and any(
+ isinstance(item.context_expr, ast.Attribute) and item.context_expr.attr == "_lock"
+ for item in node.items
+ )
+ ]
+ assert len(held) == 1, name
+ critical_section = range(held[0].lineno, held[0].end_lineno + 1)
+ bound = [
+ node
+ for node in ast.walk(fn)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr in attribution
+ ]
+ assert bound, name
+ for node in routing + bound:
+ assert node.lineno in critical_section, f"{name}:{node.lineno}"
+ # A rename that leaves nothing to scan must fail here, not pass vacuously.
+ assert routing_owners
+
+
def test_nonstream_transport_cannot_enter_the_sse_parser() -> None:
# Finding 3763339612: only the stream fixture may reach _response_stream.
source = CLIENT.read_text(encoding="utf-8")