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 "what upstream reported" one owner per call population

cyh617aefb800e6
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 2686205c3..2acdc5a61 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -98,8 +98,24 @@ class _TurnExecution:
# without reaching the end of the chunk loop can still read the tokens the
# upstream had already reported.
wire_state: _SSEWireState | None = None
+ # The same fact for a response the gateway buffered whole, which has no wire
+ # tracker to read it from.
+ buffered_usage: ProtocolUsageReport | None = None
usage_recorded: bool = False
+ @property
+ def reported_usage(self) -> ProtocolUsageReport | None:
+ """Tokens upstream reported for this turn, whichever shape it answered in.
+
+ One owner for the question, because a boundary that ends the turn early
+ cannot know which shape the response took — and a turn the vendor billed
+ was billed in both.
+ """
+
+ if self.wire_state is not None:
+ return self.wire_state.usage
+ return self.buffered_usage
+
@dataclass(frozen=True)
class _RenderedTurnOutcome:
@@ -599,6 +615,14 @@ class ModelHubTurnGateway:
payload = bytearray()
async for chunk in handle.stream:
payload.extend(chunk)
+ # Published before settling, not after: settling can be cancelled by a
+ # downstream disconnect, and a report only this frame's local knew about
+ # would leave the boundary with nothing to meter.
+ execution.buffered_usage = observe_protocol_response(
+ protocol,
+ streamed=False,
+ data=bytes(payload),
+ ).usage
outcome, settlement = await self._settle_turn_handle(
execution,
terminalizer,
@@ -611,14 +635,9 @@ class ModelHubTurnGateway:
)
assert outcome is not None
assert settlement.decision is not None
- buffered_usage = observe_protocol_response(
- protocol,
- streamed=False,
- data=bytes(payload),
- ).usage
await self._record_usage(
execution,
- usage=buffered_usage,
+ usage=execution.reported_usage,
served=settlement.decision.action == "return",
)
if settlement.decision.action != "return":
@@ -769,15 +788,16 @@ class ModelHubTurnGateway:
) -> None:
# Ahead of the settlement guard: a downstream disconnect can arrive after
# the upstream already reported its tokens, so the turn was billed even
- # though the chunk loop never reached its own metering call. The recorder
- # is idempotent, so an ending that already metered costs nothing here.
+ # though the request path never reached its own metering call. The recorder
+ # is idempotent, so an ending that already metered costs nothing here, and
+ # it reads the turn's own report rather than one shape's tracker — a
+ # buffered response cancelled mid-settlement was billed the same way.
wire_state = execution.wire_state
- if wire_state is not None:
- await self._record_usage(
- execution,
- usage=wire_state.usage,
- served=wire_state.reached_model,
- )
+ await self._record_usage(
+ execution,
+ usage=execution.reported_usage,
+ served=wire_state is not None and wire_state.reached_model,
+ )
if execution.settlement_recorded:
return
_outcome, settlement = await self._settle_turn_handle(
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index 9e5a198c2..ad0500823 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -123,16 +123,20 @@ def _instant(value: object) -> Optional[datetime]:
def _timestamp(value: object) -> Optional[str]:
- """Read one persisted instant as text, dropping anything unparseable.
-
- The read surface promises a date-time, so a corrupt or hand-edited value
- degrades the field to absent rather than travelling out through the API.
+ """Read one persisted instant as the canonical text for that instant.
+
+ The read surface promises a date-time with an offset, and `_instant` accepts
+ every spelling `datetime.fromisoformat` does — naive, space-separated, second-
+ less. Publishing the original text would let a hand-edited `2026-08-18T03:14`
+ travel out through the API as something the schema does not describe, so the
+ field carries what the parser understood rather than what the file said. An
+ unparseable value degrades the field to absent.
"""
- text = _text(value)
- if text is None or _instant(text) is None:
+ parsed = _instant(_text(value))
+ if parsed is None:
return None
- return text
+ return parsed.isoformat()
def _normalize_row(row: object) -> Optional[dict]:
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index f22b090e4..e7b420358 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -238,6 +238,34 @@ the work continued rather than stopping for a decision. The recurring signal was
and was answered the way the property-ownership rule prescribes: consolidate the
owner, then resume.
+### Round 3 (head `1ddff18d`)
+
+Three more P2 findings, two of them class C again — a third findings-bearing head for
+that class. Diagnosis over patching, per the same ruling: class C had two *remaining*
+seams, both the same shape as the original one. "What upstream reported for this call"
+was still being re-derived at each site that needed it, so any site that ended the call
+by another route answered the question with nothing.
+
+- **Seam 1, engine client** (`vibe/model_hub_runtime/client.py`). The prelude reader
+ owned the wire tracker as a local and returned it alongside the outcome, so an exit
+ that *raised* — a read timeout, a frame-limit error, a transport drop — lost whatever
+ the wire had already reported. Anthropic reports input tokens on `message_start`,
+ which lands while the prelude is still buffering, so this is a call the vendor billed.
+ The tracker now belongs to the caller, and one closure (`ended`) is the sole exit for
+ the whole population `_meter_call` meters; it attaches the report in one place instead
+ of at nine construction sites.
+- **Seam 2, turn gateway** (`core/handlers/model_hub/turn_gateway.py`). For a streamed
+ turn the report lived in `execution.wire_state`; for a buffered one it lived in a
+ request-frame local. `_settle_boundary_termination` runs at the boundary and could
+ only see the former, so a downstream disconnect during settlement dropped a billed
+ buffered turn. `_TurnExecution.reported_usage` now owns the question for both shapes,
+ and the buffered observation is published before anything cancellable runs.
+- **Class B again** (finding 3, `_timestamp`). The read surface promises an
+ offset-bearing date-time while `_instant` accepts every spelling
+ `datetime.fromisoformat` does. Publishing the raw text let a hand-edited
+ `2026-08-18T03:14` leave through the API as something the schema does not describe.
+ The field now carries what the parser understood, not what the file said.
+
## Todo
- [x] Usage taxonomy and extraction in `stream_wire.py`
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 4090c00f8..eea5d4852 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -6225,6 +6225,70 @@ def test_a_stream_that_forwarded_output_is_metered_without_a_token_report(
asyncio.run(exercise())
+def test_a_buffered_response_cancelled_while_settling_is_still_metered(
+ tmp_path: Path,
+) -> None:
+ """Review 4960016618: the boundary meters the turn's report, not one shape's.
+
+ Upstream delivered a complete billed response and the client then went away
+ while the turn was settling. The buffered shape has no wire tracker for the
+ boundary to read, so a report that lived only in the request frame's local
+ would vanish exactly when the turn was already billed.
+ """
+
+ async def exercise() -> None:
+ source = _source("src_meterbuf01", "Cancelled buffered turn")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(
+ RawOutcomeKind.SUCCESS,
+ status=200,
+ source_id=source.id,
+ stream_started=True,
+ ),
+ (b'{"usage":{"input_tokens":704,"output_tokens":21}}',),
+ )
+ ],
+ )
+ settling = asyncio.Event()
+ release = asyncio.Event()
+ settle_handle_outcome = service.settle_handle_outcome
+
+ async def blocked_settlement(*args: object, **kwargs: object):
+ settling.set()
+ await release.wait()
+ return await settle_handle_outcome(*args, **kwargs)
+
+ service.settle_handle_outcome = blocked_settlement
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_buffered_cancel",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=False,
+ )
+
+ turn = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(settling.wait(), timeout=1)
+ turn.cancel()
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(turn, timeout=1)
+
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1
+ assert metered["token_reports"] == 1
+ assert metered["input_tokens"] == 704
+ assert metered["output_tokens"] == 21
+
+ asyncio.run(exercise())
+
+
def test_gateway_meters_a_failed_turn_that_upstream_already_billed(
tmp_path: Path,
) -> None:
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 5749cc4ae..818fe9321 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -34,7 +34,11 @@ from core.handlers.model_hub.classification import (
terminal_outcome_category,
)
from core.handlers.model_hub.request import ModelHubRequest
-from core.handlers.model_hub.stream_wire import SSE_MAX_FRAME_BYTES, SSE_MAX_LINE_BYTES
+from core.handlers.model_hub.stream_wire import (
+ SSE_MAX_FRAME_BYTES,
+ SSE_MAX_LINE_BYTES,
+ ProtocolUsageReport,
+)
from vibe.model_hub_runtime import adapter as runtime_adapter_module
from vibe.model_hub_runtime import client as client_module
from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
@@ -106,13 +110,14 @@ def test_stream_prelude_does_not_charge_released_keepalives_to_frame_budget() ->
async def run() -> tuple[bytes, object, object]:
prelude = client_module._StreamPrelude()
- state, outcome = await client_module._read_stream_prelude(
+ state = client_module.ProtocolSSEState("anthropic")
+ outcome = await client_module._read_stream_prelude(
response=response,
first=first,
prelude=prelude,
+ wire_state=state,
source=source,
model_id="claude-sonnet-4-5",
- protocol="anthropic",
timeout=1,
)
payload = b"".join([chunk async for chunk in prelude.chunks()])
@@ -126,6 +131,71 @@ def test_stream_prelude_does_not_charge_released_keepalives_to_frame_budget() ->
assert outcome is None
+def test_a_prelude_that_dies_after_reporting_tokens_carries_them_to_the_resolver(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Review 4960016618: usage reported before model output survives the failure.
+
+ Anthropic bills input tokens on `message_start`, which arrives while the
+ prelude is still buffering. A read that then times out never hands a body
+ onward, so the resolver is the only half of metering that will ever see this
+ call — and it can only see what the returned outcome carries.
+ """
+
+ async def run() -> None:
+ message_start = (
+ b'event: message_start\ndata: {"type":"message_start","message":{"usage":'
+ b'{"input_tokens":900,"cache_read_input_tokens":128}}}\n\n'
+ )
+ reads = iter([message_start])
+
+ class Content:
+ async def read(self, _size: int) -> bytes:
+ try:
+ return next(reads)
+ except StopIteration:
+ raise asyncio.TimeoutError from None
+
+ class Response:
+ status = 200
+ headers = {"Content-Type": "text/event-stream"}
+ content = Content()
+
+ def close(self) -> None:
+ return None
+
+ class Session:
+ async def post(self, *_args, **_kwargs):
+ return Response()
+
+ async def close(self) -> None:
+ return None
+
+ source = SourceRecord(
+ source_id="src_billedhalt",
+ vendor="anthropic",
+ protocol="anthropic",
+ base_url="https://billed.example.test",
+ credential_ref="cred_billedhalt",
+ allowed_origins=("codex",),
+ model_ids=("claude-sonnet-4-5",),
+ prefix="billed",
+ )
+ monkeypatch.setattr(client_module.aiohttp, "ClientSession", lambda **_: Session())
+ client = EngineClient(
+ EngineConnection("http://127.0.0.1:15221", "management", "gateway")
+ )
+
+ handle = await client.invoke(source, "claude-sonnet-4-5", {}, stream=True)
+ outcome = await handle.outcome()
+
+ assert handle.stream is None
+ assert outcome.kind == RawOutcomeKind.TIMEOUT
+ assert outcome.usage == ProtocolUsageReport(input_tokens=1028, cached_input_tokens=128)
+
+ asyncio.run(run())
+
+
def test_stream_prelude_total_budget_ends_as_network_failure_and_cleans_spill(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.py
index c3995ebeb..6fc8e38d4 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -755,6 +755,44 @@ def test_a_persisted_report_count_above_its_requests_is_repaired_on_read(
}
+def test_a_persisted_instant_is_published_in_the_shape_the_schema_promises(
+ tmp_path: Path,
+) -> None:
+ """Review 4960016618: the read surface publishes an offset-bearing date-time.
+
+ `datetime.fromisoformat` accepts spellings the API schema does not describe —
+ naive, space-separated, minute-less — so the field carries what the parser
+ understood rather than the text the file happened to hold. A naive value is
+ read in the same local calendar the day buckets use.
+ """
+
+ ledger = _ledger(tmp_path)
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ ledger.path.write_text(
+ json.dumps(
+ [
+ {
+ "day": local_usage_day(NOW).isoformat(),
+ "source_id": "src_a",
+ "model_id": "model-x",
+ "requests": 1,
+ "token_reports": 1,
+ "input_tokens": 4,
+ "cached_input_tokens": 0,
+ "output_tokens": 2,
+ "last_metered_at": "2026-07-23 12:00",
+ }
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ published = ledger.window(days=30, now=NOW)[0]["last_metered_at"]
+
+ assert published == datetime(2026, 7, 23, 12, 0).astimezone().isoformat()
+ assert datetime.fromisoformat(published).tzinfo is not None
+
+
def test_a_written_row_is_validated_the_same_way_a_persisted_one_is(
tmp_path: Path,
) -> None:
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index 81708cee3..ce1de2cbe 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -9,7 +9,7 @@ import urllib.error
import urllib.parse
import urllib.request
from collections.abc import Awaitable, Callable
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from typing import Any, AsyncIterator, BinaryIO, Mapping
import aiohttp
@@ -273,6 +273,25 @@ class EngineClient:
model_output_started = False
ownership_transferred = False
prelude: _StreamPrelude | None = None
+ # Held here rather than inside the prelude reader so every way out of this
+ # call can still see what the wire already reported. A stream that reports
+ # usage before its first model output — Anthropic's `message_start` does —
+ # and then times out has already been billed for those input tokens.
+ wire_state: ProtocolSSEState | None = None
+
+ def ended(outcome: RawCallOutcome) -> EngineInvokeHandle:
+ """Finish a call whose body never becomes the gateway's to forward.
+
+ The sole exit for that population, so the tokens the wire reported are
+ attached in one place instead of at each construction site: the resolver
+ meters exactly what this returns, and an outcome that lost its report on
+ the way out is a call the vendor billed and the ledger never saw.
+ """
+
+ if outcome.usage is None and wire_state is not None and wire_state.usage is not None:
+ outcome = replace(outcome, usage=wire_state.usage)
+ return completed_handle(outcome)
+
try:
response = await asyncio.wait_for(
session.post(
@@ -312,7 +331,7 @@ class EngineClient:
assert outcome is not None
response.close()
await session.close()
- return completed_handle(outcome)
+ return ended(outcome)
first = await asyncio.wait_for(
response.content.read(_STREAM_CHUNK_BYTES),
@@ -321,7 +340,7 @@ class EngineClient:
if not first:
response.close()
await session.close()
- return completed_handle(
+ return ended(
_outcome(
kind=RawOutcomeKind.NETWORK_ERROR,
source=source,
@@ -344,7 +363,7 @@ class EngineClient:
except _ResponseTooLargeError:
response.close()
await session.close()
- return completed_handle(
+ return ended(
_protocol_error_outcome(
ProtocolObservation(
outcome="protocol_error",
@@ -375,17 +394,18 @@ class EngineClient:
return (
buffered_handle(first, outcome)
if outcome.kind == RawOutcomeKind.SUCCESS
- else completed_handle(outcome)
+ else ended(outcome)
)
prelude = _StreamPrelude()
- wire_state, prelude_outcome = await _read_stream_prelude(
+ wire_state = ProtocolSSEState(request_protocol)
+ prelude_outcome = await _read_stream_prelude(
response=response,
first=first,
prelude=prelude,
+ wire_state=wire_state,
source=source,
model_id=model_id,
- protocol=request_protocol,
timeout=self.timeout,
)
model_output_started = wire_state.model_output_started
@@ -397,7 +417,7 @@ class EngineClient:
ownership_transferred = True
return handle
prelude.close()
- return completed_handle(prelude_outcome)
+ return ended(prelude_outcome)
loop = asyncio.get_running_loop()
outcome_future: asyncio.Future[RawCallOutcome] = loop.create_future()
@@ -428,7 +448,7 @@ class EngineClient:
if response is not None:
response.close()
await session.close()
- return completed_handle(
+ return ended(
_outcome(
kind=RawOutcomeKind.TIMEOUT,
source=source,
@@ -442,7 +462,7 @@ class EngineClient:
if response is not None:
response.close()
await session.close()
- return completed_handle(
+ return ended(
_protocol_error_outcome(
ProtocolObservation(outcome="protocol_error", message=str(exc)),
source,
@@ -455,7 +475,7 @@ class EngineClient:
if response is not None:
response.close()
await session.close()
- return completed_handle(
+ return ended(
_outcome(
kind=RawOutcomeKind.NETWORK_ERROR,
source=source,
@@ -612,16 +632,20 @@ async def _read_stream_prelude(
response: aiohttp.ClientResponse,
first: bytes,
prelude: _StreamPrelude,
+ wire_state: ProtocolSSEState,
source: SourceRecord,
model_id: str,
- protocol: str,
timeout: float,
-) -> tuple[ProtocolSSEState, RawCallOutcome | None]:
- """Buffer transport metadata until the sole first-model-output fact."""
+) -> RawCallOutcome | None:
+ """Buffer transport metadata until the sole first-model-output fact.
+
+ The tracker belongs to the caller: this coroutine can also end by raising a
+ transport error, and what the wire reported before that has to survive the
+ raise for the call to be metered.
+ """
- wire_state = ProtocolSSEState(protocol)
if not prelude.write(first):
- return wire_state, _prelude_ended_outcome(source, model_id, response.status)
+ return _prelude_ended_outcome(source, model_id, response.status)
wire_state.observe(first)
while not wire_state.model_output_started:
outcome = _observed_stream_terminal_outcome(
@@ -631,7 +655,7 @@ async def _read_stream_prelude(
response.status,
)
if outcome is not None:
- return wire_state, outcome
+ return outcome
chunk = await asyncio.wait_for(
response.content.read(_STREAM_CHUNK_BYTES),
timeout=timeout,
@@ -644,15 +668,12 @@ async def _read_stream_prelude(
response.status,
)
if completion is not None:
- return wire_state, completion
- return (
- wire_state,
- _prelude_ended_outcome(source, model_id, response.status),
- )
+ return completion
+ return _prelude_ended_outcome(source, model_id, response.status)
if not prelude.write(chunk):
- return wire_state, _prelude_ended_outcome(source, model_id, response.status)
+ return _prelude_ended_outcome(source, model_id, response.status)
wire_state.observe(chunk)
- return wire_state, None
+ return None
def _prelude_ended_outcome(