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): carry the engine's own observation across the hand-off

cyh69c51cbaf631
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index ced461a5a..ff29a61e6 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -14,7 +14,7 @@ from dataclasses import dataclass
from enum import Enum
from typing import Any, AsyncIterator, Final, Literal, Mapping, Protocol, Sequence
-from .stream_wire import ProtocolUsageReport
+from .stream_wire import ProtocolSSEState, ProtocolUsageReport
ENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0
SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")
@@ -322,11 +322,24 @@ class InvokeHandle(Protocol):
For streaming calls, ``stream_started`` becomes true only when the
protocol taxonomy observes the first model output; transport metadata and
error frames remain pre-output. ``close_stream()`` is idempotent.
+
+ ``observed`` carries what the adapter itself read of this body, and it is
+ the handle's only member that answers before the body is consumed. A
+ streaming adapter has already read the head of the stream to decide there
+ was one — Anthropic reports the input tokens it billed in that head — and it
+ keeps reading as the body is yielded, so its tracker is never behind a
+ consumer's. Without it the facts of a call would exist only in bytes the
+ consumer has already pulled, and everything that can end a turn before the
+ first pull would see a call that never happened. It is None only when the
+ adapter tokenized no stream for this call.
"""
@property
def stream(self) -> AsyncIterator[bytes] | None: ...
+ @property
+ def observed(self) -> ProtocolSSEState | None: ...
+
@property
def outcome_available(self) -> bool: ...
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index 270503f1f..5eb83f46a 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -673,6 +673,22 @@ class ProtocolSSEState:
def next_sequence_number(self) -> int:
return self.last_sequence_number + 1
+ @property
+ def reached_model(self) -> bool:
+ """Whether this stream got far enough upstream to have been billed.
+
+ Forwarded model output proves the call reached the model even when the
+ stream then ended without a recognized terminal — a connection lost after
+ a text delta is a request that happened, and `token_reports` staying at
+ zero is exactly how the ledger records that nobody reported its tokens.
+
+ Lives on the tracker rather than beside one of its readers, because both
+ sides of the hand-off keep a tracker over the same body and a fact read
+ from only one of them is a fact the other half of the turn cannot use.
+ """
+
+ return self.terminal_outcome == "served" or self.model_output_started
+
def _observe_frame(self, frame: bytes) -> None:
if self.terminal_outcome is not None:
return
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 35500fa52..63e2f9b5c 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -100,7 +100,7 @@ class _TurnExecution:
# The live stream tracker, published here so a boundary that ends the turn
# without reaching the end of the chunk loop can still read the tokens the
# upstream had already reported.
- wire_state: _SSEWireState | None = None
+ wire_state: ProtocolSSEState | None = None
# The same two facts for a response the gateway buffered whole, which has no
# wire tracker to read them from.
buffered_usage: ProtocolUsageReport | None = None
@@ -110,6 +110,24 @@ class _TurnExecution:
# the write was started by something whose own death could still take it.
usage_write: asyncio.Future[None] | None = None
+ @property
+ def upstream_observation(self) -> ProtocolSSEState | None:
+ """What the engine read of this body, from before it was ours to forward.
+
+ Every other fact this turn holds is built from bytes this gateway has
+ already pulled, and the pulling starts after the downstream response is
+ prepared. The engine read the head of the same body to decide there was
+ one and keeps reading as it yields, so its tracker answers in the window
+ where ours does not exist yet and is never behind it afterwards.
+
+ Which is what makes it the first thing both facts below ask. They used
+ to ask the shapes this gateway builds, and each new ending that opened
+ before those shapes existed cost a review round teaching one more fact
+ to survive it.
+ """
+
+ return self.handle.observed if self.handle is not None else None
+
@property
def reported_usage(self) -> ProtocolUsageReport | None:
"""Tokens upstream reported for this turn, whichever shape it answered in.
@@ -119,6 +137,9 @@ class _TurnExecution:
was billed in both.
"""
+ upstream = self.upstream_observation
+ if upstream is not None and upstream.usage is not None:
+ return upstream.usage
if self.wire_state is not None:
return self.wire_state.usage
return self.buffered_usage
@@ -139,21 +160,26 @@ class _TurnExecution:
reached its terminal was, and an error envelope reached no model exactly as
a stream that forwarded no output did.
- Both halves are observations *of the body*, and the turn can end before
- either one exists: the gateway adopts the body first, and only then
- prepares the downstream response and starts reading. A client that goes
- away in that gap leaves no wire tracker and no buffered verdict behind,
- so the last answer is the adoption itself — which is both the earliest
- moment the question is answerable and the last one that cannot fail.
- It is an answer, not a guess: the engine hands this gateway a body only
- after the prelude observed the first model output, or for a call it had
- already completed upstream, and it keeps every other call to meter in
- the resolver. An adopted body is therefore a call the vendor billed, and
- `token_reports` staying at zero is how the ledger says nobody got to
- read its tokens. Later evidence still overrules this, so it decides only
- for the endings that collected none.
+ Both halves are observations *of the body* this gateway made itself, and
+ the turn can end before either one exists: the gateway adopts the body
+ first, and only then prepares the downstream response and starts reading.
+ A client that goes away in that gap leaves neither behind — which is why
+ the engine's own observation is asked first, here and in `reported_usage`.
+ It read the same body earlier than we did, so it is the one answer that
+ exists in that window rather than a weaker stand-in for it.
+
+ The adoption itself remains the floor, for a handle that tokenized no
+ stream to hand over. It is an answer, not a guess: the engine hands this
+ gateway a body only after the prelude observed the first model output, or
+ for a call it had already completed upstream, and it keeps every other
+ call to meter in the resolver. An adopted body is therefore a call the
+ vendor billed, and `token_reports` staying at zero is how the ledger says
+ nobody got to read its tokens.
"""
+ upstream = self.upstream_observation
+ if upstream is not None and upstream.reached_model:
+ return True
if self.wire_state is not None:
return self.wire_state.reached_model
if self.buffered_outcome is not None:
@@ -167,25 +193,6 @@ class _RenderedTurnOutcome:
message: str | None
-class _SSEWireState(ProtocolSSEState):
- """Gateway-local name for the shared protocol stream tracker."""
-
- @property
- def reached_model(self) -> bool:
- """Whether this stream got far enough upstream to have been billed.
-
- Forwarded model output proves the call reached the model even when the
- stream then ended without a recognized terminal — a connection lost after
- a text delta is a request that happened, and `token_reports` staying at
- zero is exactly how the ledger records that nobody reported its tokens.
-
- One owner for the question, because every ending of a stream has to
- answer it the same way.
- """
-
- return self.terminal_outcome == "served" or self.model_output_started
-
-
class _DownstreamDisconnected(ConnectionError):
pass
@@ -726,7 +733,7 @@ class ModelHubTurnGateway:
},
)
await self._downstream_io(response.prepare(request))
- wire_state = _SSEWireState(protocol)
+ wire_state = ProtocolSSEState(protocol)
execution.wire_state = wire_state
async for chunk in handle.stream:
output_started_before = wire_state.model_output_started
@@ -819,7 +826,7 @@ class ModelHubTurnGateway:
response: web.StreamResponse,
protocol: str,
rendered: _RenderedTurnOutcome | None,
- wire_state: _SSEWireState,
+ wire_state: ProtocolSSEState,
*,
forwarded_terminal: StreamTerminalOutcome | None,
) -> None:
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index ced461a5a..ff29a61e6 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -14,7 +14,7 @@ from dataclasses import dataclass
from enum import Enum
from typing import Any, AsyncIterator, Final, Literal, Mapping, Protocol, Sequence
-from .stream_wire import ProtocolUsageReport
+from .stream_wire import ProtocolSSEState, ProtocolUsageReport
ENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0
SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")
@@ -322,11 +322,24 @@ class InvokeHandle(Protocol):
For streaming calls, ``stream_started`` becomes true only when the
protocol taxonomy observes the first model output; transport metadata and
error frames remain pre-output. ``close_stream()`` is idempotent.
+
+ ``observed`` carries what the adapter itself read of this body, and it is
+ the handle's only member that answers before the body is consumed. A
+ streaming adapter has already read the head of the stream to decide there
+ was one — Anthropic reports the input tokens it billed in that head — and it
+ keeps reading as the body is yielded, so its tracker is never behind a
+ consumer's. Without it the facts of a call would exist only in bytes the
+ consumer has already pulled, and everything that can end a turn before the
+ first pull would see a call that never happened. It is None only when the
+ adapter tokenized no stream for this call.
"""
@property
def stream(self) -> AsyncIterator[bytes] | None: ...
+ @property
+ def observed(self) -> ProtocolSSEState | None: ...
+
@property
def outcome_available(self) -> bool: ...
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index f122780e3..4fd0d9708 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -620,6 +620,52 @@ reads every non-schema file in the directory. The four legitimately historical `
sentences the README already blessed stay untouched, and are now distinguishable
mechanically rather than by judgment.
+### Round 11 (head `d9e19d977`)
+
+One finding, and class C an eighth time — the direct sibling of what round 10 fixed.
+`reached_model` gained the adoption floor; `reported_usage`, which that docstring names
+as its sibling, kept its two branches. Same window (a client leaving inside
+`response.prepare()`), same call, and the row now records `requests == 1` with the token
+counts lost.
+
+**Why round 10's answer does not extend to this fact.** Adoption proves *that* the call
+happened; nothing about adoption reveals *how many tokens* it reported. So the class was
+never about publishing gateway-built facts earlier — it was about where those facts come
+from. Every fact `_TurnExecution` held was built from bytes the gateway had already
+pulled, and pulling starts after the downstream response is prepared. Each round found
+one more ending inside that window, and each fix taught one more fact to survive it. A
+ninth fact would have cost a ninth round.
+
+**The fact already exists on the other side of the hand-off.** `client.py:401` builds a
+`ProtocolSSEState` and `_read_stream_prelude` feeds it: the engine only knows there *is*
+a stream because it read as far as the first model output, which for Anthropic is past
+the `message_start` frame carrying the billed input tokens. `_response_stream` keeps
+observing into that same tracker as it yields, without re-observing the replayed prelude
+— so it is never behind the gateway's copy and never double-counts. `EngineInvokeHandle`
+then handed over `stream`, `outcome`, and `stream_closer`, and dropped it.
+
+`ended()` (`client.py:282`) is the proof this is a property with a missing owner rather
+than a missing line: the *non-adopted* population has owned exactly this since round 7 —
+one exit that attaches the wire's report to the outcome, with a comment naming the same
+Anthropic case. The adopted population is the same property with no owner at all.
+
+**The fix.** `InvokeHandle` gains `observed`, the adapter's own observation of the body
+it hands over, mirrored byte-identically into the contract copy. Both `_TurnExecution`
+facts ask it first and fall back to what the gateway builds itself. `reached_model` also
+moves off a gateway-local `ProtocolSSEState` subclass and onto the shared tracker, which
+deletes `_SSEWireState` entirely: both sides of the hand-off keep a tracker over the same
+body, so a reading available on only one of them is a reading half the turn cannot use.
+
+**Closed as a class, both directions.** `test_every_body_fact_the_turn_reads_can_come_from_the_engine_that_read_it`
+states the property rather than the pair: any `_TurnExecution` property that reads the
+gateway's own tracker is by definition a fact about the forwarded body, so it must also
+read `upstream_observation` — a ninth fact fails a test instead of costing a round. Its
+second half guards the other direction, that every member the contract declares is
+implemented by the one real handle, since a fact that stops at the hand-off leaves the
+reader asking only fakes for it. The behavioural test reuses round 10's enumeration-free
+form, driving the same `FakeStreamResponse` failure points and asserting the prelude's
+1028 input tokens land in the ledger at every one of them.
+
## Todo
- [x] Usage taxonomy and extraction in `stream_wire.py`
diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.py
index f93414212..e2f1c1735 100644
--- a/tests/scenario_harness/model_hub.py
+++ b/tests/scenario_harness/model_hub.py
@@ -78,6 +78,12 @@ class ScenarioInvokeHandle:
return chunks()
+ @property
+ def observed(self) -> None:
+ """This double reports nothing about the body until its consumer reads it."""
+
+ return None
+
@property
def outcome_available(self) -> bool:
return True
diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
index 3e6f327cc..fb78895f8 100644
--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
@@ -91,6 +91,12 @@ class InvokeHandle:
def stream(self) -> AsyncIterator[bytes] | None:
return self._stream
+ @property
+ def observed(self) -> None:
+ """This double reports nothing about the body until its consumer reads it."""
+
+ return None
+
@property
def outcome_available(self) -> bool:
return True
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 1ced3fdad..3b8b84caf 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
@@ -75,6 +75,12 @@ class MidTurnEngineLossHandle:
return chunks()
+ @property
+ def observed(self):
+ """This double reports nothing about the body until its consumer reads it."""
+
+ return None
+
@property
def outcome_available(self) -> bool:
return True
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index ba8945f96..c8354266e 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -69,10 +69,9 @@ from core.handlers.model_hub.service import (
from core.handlers.model_hub.turn_gateway import (
ModelHubTurnGateway,
_RenderedTurnOutcome,
- _SSEWireState,
render_protocol_terminal_event,
)
-from core.handlers.model_hub.stream_wire import ProtocolUsageReport
+from core.handlers.model_hub.stream_wire import ProtocolSSEState, ProtocolUsageReport
from core.handlers.model_hub.usage import BoundedUsageLedger, _ledger_executor
from core.run_settlement import (
SETTLED_BY_NO_TERMINAL_RESULT,
@@ -251,7 +250,7 @@ def test_terminal_event_renderer_uses_native_protocol_shape(
def test_responses_terminal_event_discards_partial_sequence_before_injection() -> None:
- wire = _SSEWireState("openai_responses")
+ wire = ProtocolSSEState("openai_responses")
wire.observe(b'data: {"type":"response.output_text.delta","sequence_number":7}\n\n')
wire.observe(b'data: {"type":"response.output_text.delta","sequence_number":8}')
@@ -268,7 +267,7 @@ def test_responses_terminal_event_discards_partial_sequence_before_injection() -
def test_responses_terminal_event_continues_sequence_on_cr_only_frames() -> None:
- wire = _SSEWireState("openai_responses")
+ wire = ProtocolSSEState("openai_responses")
wire.observe(
b'data: {"type":"response.output_text.delta","sequence_number":7}\r\r'
b'data: {"type":"response.output_text.delta","sequence_number":8}\r\r'
@@ -731,7 +730,23 @@ class MemoryStore:
return self.requested_models.get(backend, "")
-class InvokeHandle:
+class _EngineObservation:
+ """The adapter-side half of `InvokeHandle` these fakes all answer the same way.
+
+ Every fake below stands in for an engine that reports nothing about a body
+ until the gateway reads it, which is the state the contract calls `None`.
+ A fake that hands over a real observation sets `_observed` and thereby says
+ so explicitly, instead of being the only one that remembered the member.
+ """
+
+ _observed = None
+
+ @property
+ def observed(self):
+ return self._observed
+
+
+class InvokeHandle(_EngineObservation):
def __init__(self, outcome: RawCallOutcome):
self._outcome = outcome
@@ -750,9 +765,15 @@ class InvokeHandle:
return self._outcome
-class LiveInvokeHandle:
- def __init__(self, outcome: RawCallOutcome, chunks: tuple[bytes, ...]):
+class LiveInvokeHandle(_EngineObservation):
+ def __init__(
+ self,
+ outcome: RawCallOutcome,
+ chunks: tuple[bytes, ...],
+ observed: ProtocolSSEState | None = None,
+ ):
self._outcome = outcome
+ self._observed = observed
self._stream = self._iterate(chunks)
@staticmethod
@@ -775,7 +796,7 @@ class LiveInvokeHandle:
return self._outcome
-class BlockingLiveInvokeHandle:
+class BlockingLiveInvokeHandle(_EngineObservation):
def __init__(self, outcome: RawCallOutcome):
self._outcome = outcome
self.started = asyncio.Event()
@@ -825,7 +846,7 @@ class MidStreamBlockingInvokeHandle(BlockingLiveInvokeHandle):
yield b"data: [DONE]\n\n"
-class BrokenUpstreamInvokeHandle:
+class BrokenUpstreamInvokeHandle(_EngineObservation):
def __init__(self, outcome: RawCallOutcome):
self._outcome = outcome
self._stream = self._iterate()
@@ -911,7 +932,7 @@ class FakeStreamResponse:
return None
-class DeferredLifecycleHandle:
+class DeferredLifecycleHandle(_EngineObservation):
def __init__(self, outcome: RawCallOutcome):
self._outcome = outcome
self._available = False
@@ -946,7 +967,7 @@ class DeferredLifecycleHandle:
return self._outcome
-class RepeatedCancellationHandle:
+class RepeatedCancellationHandle(_EngineObservation):
def __init__(self, outcome: RawCallOutcome, blocked_phase: str):
self._outcome = outcome
self._blocked_phase = blocked_phase
@@ -989,7 +1010,7 @@ class RepeatedCancellationHandle:
return self._outcome
-class NeverResolvingCloseHandle:
+class NeverResolvingCloseHandle(_EngineObservation):
def __init__(self, outcome: RawCallOutcome):
self._outcome = outcome
self.started = asyncio.Event()
@@ -2146,7 +2167,7 @@ def test_gateway_emits_at_most_one_wire_terminal(case: dict[str, object]) -> Non
response, # type: ignore[arg-type]
"openai_responses",
outcomes[str(case["settlement"])],
- _SSEWireState("openai_responses"),
+ ProtocolSSEState("openai_responses"),
forwarded_terminal=cast(str | None, forwarded), # type: ignore[arg-type]
)
assert bool(response.writes) is case["write_terminal"]
@@ -6655,6 +6676,78 @@ def test_no_downstream_ending_after_adoption_can_drop_the_turn_from_the_ledger(
asyncio.run(exercise(point))
+def test_the_tokens_the_engine_already_read_survive_every_ending_before_our_first(
+ tmp_path: Path,
+) -> None:
+ """Review 4965405530: the engine read the head of this body before we did.
+
+ The gateway asks the engine for a stream, and the engine only knows there is
+ one because it read far enough to see the first model output — which for
+ Anthropic is past `message_start`, the frame carrying the input tokens the
+ vendor already billed. Those bytes then reach the gateway as a replay it
+ re-tokenizes itself, so every fact it holds about the call starts existing
+ only once forwarding starts. `requests` survived that gap because adoption
+ is a fact of the turn; the token counts had nowhere to come from.
+
+ Same enumeration as the sibling above, for the same reason: the property is
+ that no downstream ending decides what upstream reported, so the endings are
+ read off the response double rather than listed here.
+ """
+
+ failure_points = [
+ name for name in inspect.signature(FakeStreamResponse).parameters if name.endswith("_error")
+ ]
+ assert failure_points
+
+ prelude = (
+ b'event: message_start\ndata: {"type":"message_start","message":'
+ b'{"usage":{"input_tokens":900,"cache_read_input_tokens":128}}}\n\n'
+ )
+
+ async def exercise(point: str) -> None:
+ state = tmp_path / f"prelude_{point}"
+ state.mkdir()
+ source = _source("src_meterprel01", "Prelude-billed body")
+ engine_view = ProtocolSSEState("anthropic")
+ engine_view.observe(prelude)
+ assert engine_view.usage is not None
+ service = _service(
+ state,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id),
+ (prelude,),
+ observed=engine_view,
+ )
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id=f"turn_meter_prelude_{point}",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=True,
+ )
+ with patch(
+ "core.handlers.model_hub.turn_gateway.web.StreamResponse",
+ return_value=FakeStreamResponse(**{point: ConnectionResetError("client left")}),
+ ):
+ with pytest.raises(ConnectionError):
+ await asyncio.wait_for(gateway._handle_request(request), timeout=5)
+ await gateway.close()
+
+ metered = _usage_of(service, source.id)
+ assert metered.get("requests") == 1, point
+ assert metered.get("token_reports") == 1, point
+ assert metered.get("input_tokens") == 1028, point
+
+ for point in failure_points:
+ asyncio.run(exercise(point))
+
+
def test_a_turn_cancelled_before_it_read_the_body_is_still_a_call_that_happened(
tmp_path: Path,
) -> None:
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index c80e8c6d2..6c18054ae 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -43,6 +43,7 @@ PROVENANCE = ROOT / "core/handlers/model_hub/provenance.py"
ROUTER = ROOT / "modules/agents/model_hub.py"
ADAPTER = ROOT / "vibe/model_hub_runtime/adapter.py"
CLIENT = ROOT / "vibe/model_hub_runtime/client.py"
+INVOKE_CONTRACT = ROOT / "core/handlers/model_hub/adapter.py"
FIXTURES = Path(__file__).parent / "fixtures" / "model_hub"
STREAM_TRANSPORT_FIXTURES = json.loads((FIXTURES / "stream_transport_boundaries.json").read_text(encoding="utf-8"))[
"cases"
@@ -579,6 +580,62 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:
assert all(handle in set(ast.walk(recorder)) for handle in handles)
+def test_every_body_fact_the_turn_reads_can_come_from_the_engine_that_read_it() -> None:
+ # Review 4965405530: the gateway forwards a body the engine had already begun
+ # reading, and each round of this class was one more fact of that body that
+ # existed only in bytes the gateway itself had pulled — so every ending that
+ # opens before the first pull answered it wrong, one fact at a time. The
+ # property is not which facts those are: it is that a fact read from the
+ # gateway's own tracker is a fact about the forwarded body, and every one of
+ # them can be answered by the observation that saw the body first.
+ execution = next(
+ node
+ for node in ast.walk(_tree(TURN_GATEWAY))
+ if isinstance(node, ast.ClassDef) and node.name == "_TurnExecution"
+ )
+
+ def reads(owner: ast.AST, attribute: str) -> bool:
+ return any(
+ isinstance(node, ast.Attribute)
+ and node.attr == attribute
+ and isinstance(node.value, ast.Name)
+ and node.value.id == "self"
+ for node in ast.walk(owner)
+ )
+
+ body_facts = [
+ node
+ for node in execution.body
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and any(
+ isinstance(decorator, ast.Name) and decorator.id == "property"
+ for decorator in node.decorator_list
+ )
+ and reads(node, "wire_state")
+ ]
+ assert body_facts
+ assert [fact.name for fact in body_facts if not reads(fact, "upstream_observation")] == []
+
+ # Which the engine can only answer if the whole boundary crosses: a member the
+ # contract declares and the one real implementation drops is a fact that stops
+ # at the hand-off, and the reader above would be asking a fake for it.
+ def members(tree: ast.AST, name: str) -> set[str]:
+ owner = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ClassDef) and node.name == name
+ )
+ return {
+ node.name
+ for node in owner.body
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+ declared = members(_tree(INVOKE_CONTRACT), "InvokeHandle")
+ assert "observed" in declared
+ assert declared <= members(_tree(CLIENT), "EngineInvokeHandle")
+
+
def test_model_identity_is_decided_only_by_its_owner() -> None:
# Review 4959575659 finding 11: config, resolution, and metering only agree on
# what "the same model" is while one function decides it. A module that reaches
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index ce1de2cbe..52c7e8c9b 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -154,10 +154,12 @@ class EngineInvokeHandle:
stream: AsyncIterator[bytes] | None,
outcome: asyncio.Future[RawCallOutcome],
stream_closer: Callable[[], Awaitable[None]] | None = None,
+ observed: ProtocolSSEState | None = None,
) -> None:
self._stream = stream
self._outcome = outcome
self._stream_closer = stream_closer
+ self._observed = observed
self._close_lock = asyncio.Lock()
self._stream_closed = False
@@ -165,6 +167,10 @@ class EngineInvokeHandle:
def stream(self) -> AsyncIterator[bytes] | None:
return self._stream
+ @property
+ def observed(self) -> ProtocolSSEState | None:
+ return self._observed
+
@property
def outcome_available(self) -> bool:
return self._outcome.done()
@@ -413,7 +419,7 @@ class EngineClient:
response.close()
await session.close()
if prelude_outcome.kind == RawOutcomeKind.SUCCESS:
- handle = buffered_prelude_handle(prelude, prelude_outcome)
+ handle = buffered_prelude_handle(prelude, prelude_outcome, wire_state)
ownership_transferred = True
return handle
prelude.close()
@@ -441,6 +447,7 @@ class EngineClient:
stream=response_stream,
outcome=outcome_future,
stream_closer=close_response_stream,
+ observed=wire_state,
)
ownership_transferred = True
return handle
@@ -890,6 +897,7 @@ def buffered_handle(payload: bytes, outcome: RawCallOutcome) -> EngineInvokeHand
def buffered_prelude_handle(
prelude: _StreamPrelude,
outcome: RawCallOutcome,
+ observed: ProtocolSSEState,
) -> EngineInvokeHandle:
async def body() -> AsyncIterator[bytes]:
try:
@@ -903,7 +911,12 @@ def buffered_prelude_handle(
future = asyncio.get_running_loop().create_future()
future.set_result(outcome)
- return EngineInvokeHandle(stream=body(), outcome=future, stream_closer=close)
+ return EngineInvokeHandle(
+ stream=body(),
+ outcome=future,
+ stream_closer=close,
+ observed=observed,
+ )
def _outcome(