Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): meter at body adoption and bound the ledger backlog
cyhd9e19d977375
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex ae0947cfb..35500fa52 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -88,6 +88,9 @@ class _TurnExecution:"""Resources and settlement state owned by one gateway request boundary."""resolved: ResolvedInvocation | None = None+ # Set the moment this gateway takes the upstream body, which is also the+ # moment it takes the call's metering from the resolver. Assigned before+ # anything downstream can fail, so it outlives every ending after it.handle: InvokeHandle | None = Nonesettlement_task: asyncio.Task[tuple[RawCallOutcome | None, HandleSettlement]] | None = Nonesettlement_origin: HandleTerminationOrigin | None = None@@ -105,7 +108,7 @@ class _TurnExecution:# The writer-owned task that persists this turn's row, and by its existence# the record that this turn has already been metered. A flag would only say# the write was started by something whose own death could still take it.- usage_write: asyncio.Task[None] | None = None+ usage_write: asyncio.Future[None] | None = None@propertydef reported_usage(self) -> ProtocolUsageReport | None:@@ -135,11 +138,27 @@ class _TurnExecution:body: a complete model answer was served upstream exactly as a stream thatreached its terminal was, and an error envelope reached no model exactly asa 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."""if self.wire_state is not None:return self.wire_state.reached_model- return self.buffered_outcome == "served"+ if self.buffered_outcome is not None:+ return self.buffered_outcome == "served"+ return self.handle is not None@dataclass(frozen=True)diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex bb370a48c..5e395c7dc 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -25,9 +25,11 @@ import loggingimport osimport tempfileimport threading+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclassfrom datetime import date, datetime, timedelta, timezonefrom pathlib import Path-from typing import Callable, Final, Optional+from typing import Callable, Final, Optional, Sequencefrom .identifiers import canonical_model_idfrom .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReport@@ -342,42 +344,68 @@ class BoundedUsageLedger:metered later than the write that records it."""+ self.record_many((UsageCall(source_id=source_id, model_id=model_id, usage=usage, at=at),))++ def record_many(self, calls: Sequence["UsageCall"]) -> None:+ """Fold a batch of metered calls into their days' rows in one transaction.++ The batch is the reason a backlog cannot grow: one read, one retention+ pass and one fsync serve however many calls arrived while the previous+ batch was being written, so the queue drains in bursts of whatever size+ it reached rather than one durable write at a time. Folding is what makes+ that safe — every call still lands in its own day's row with its own+ stamp, so a batch of ten is arithmetically the ten separate writes it+ replaces, never a summary of them.++ One `persisted_at` reading covers the batch, for the same reason `record`+ takes its own: it is the moment these calls reached the disk, and none of+ them was metered later than that.+ """++ if not calls:+ returnwith self._lock:persisted_at = _aware(self._now())- metered_at = min(_aware(at), persisted_at)- increment = _normalize_row(- {- "day": local_usage_day(metered_at).isoformat(),- "source_id": source_id,- "model_id": model_id,- "requests": 1,- "token_reports": 1 if usage is not None else 0,- "input_tokens": usage.input_tokens if usage else 0,- "cached_input_tokens": usage.cached_input_tokens if usage else 0,- "output_tokens": usage.output_tokens if usage else 0,- "last_metered_at": metered_at.isoformat(),- }- )- if increment is None:- # Unreachable for anything the hub admits: both boundaries that- # accept a model id store the canonical form this row is keyed by.- # Loud rather than silent so a future boundary that forgets shows- # up as lost metering instead of as a quietly incomplete tab.- logger.warning(- "Model Hub usage metering skipped a call with an unusable identifier",- extra={"source_id_usable": canonical_model_id(source_id) is not None},- )- returnrows = {_row_key(row): row for row in self._read()}- existing = rows.get(_row_key(increment))- if existing is None:- rows[_row_key(increment)] = increment- else:- _accumulate(existing, increment)- existing["last_metered_at"] = _newer_timestamp(- existing["last_metered_at"],- increment["last_metered_at"],+ folded = False+ for call in calls:+ metered_at = min(_aware(call.at), persisted_at)+ usage = call.usage+ increment = _normalize_row(+ {+ "day": local_usage_day(metered_at).isoformat(),+ "source_id": call.source_id,+ "model_id": call.model_id,+ "requests": 1,+ "token_reports": 1 if usage is not None else 0,+ "input_tokens": usage.input_tokens if usage else 0,+ "cached_input_tokens": usage.cached_input_tokens if usage else 0,+ "output_tokens": usage.output_tokens if usage else 0,+ "last_metered_at": metered_at.isoformat(),+ })+ if increment is None:+ # Unreachable for anything the hub admits: both boundaries that+ # accept a model id store the canonical form this row is keyed by.+ # Loud rather than silent so a future boundary that forgets shows+ # up as lost metering instead of as a quietly incomplete tab.+ logger.warning(+ "Model Hub usage metering skipped a call with an unusable identifier",+ extra={"source_id_usable": canonical_model_id(call.source_id) is not None},+ )+ continue+ existing = rows.get(_row_key(increment))+ if existing is None:+ rows[_row_key(increment)] = increment+ else:+ _accumulate(existing, increment)+ existing["last_metered_at"] = _newer_timestamp(+ existing["last_metered_at"],+ increment["last_metered_at"],+ )+ folded = True+ if not folded:+ returnretained = self._retained(list(rows.values()), persisted_at)self._write(retained)@@ -485,20 +513,69 @@ class BoundedUsageLedger:}+_LEDGER_EXECUTOR_LOCK: Final = threading.Lock()+_LEDGER_EXECUTOR: Optional[ThreadPoolExecutor] = None+++def _ledger_executor() -> ThreadPoolExecutor:+ """The one thread ledger writes run on, created when something is first metered.++ Deliberately not the loop's default executor. `record_many` holds the ledger's+ lock across an fsync, so submitting one job per completed call there would+ occupy that many shared workers while all but one waited on the lock — and+ whatever else in the process reaches for a thread would wait behind metering+ for no gain, since the lock admits one writer regardless. Owning the+ serialization makes it explicit instead of emergent, and it costs a single+ idle thread once anything has been metered at all.+ """++ global _LEDGER_EXECUTOR+ with _LEDGER_EXECUTOR_LOCK:+ if _LEDGER_EXECUTOR is None:+ _LEDGER_EXECUTOR = ThreadPoolExecutor(max_workers=1, thread_name_prefix="model-hub-usage")+ return _LEDGER_EXECUTOR+++@dataclass(frozen=True)+class UsageCall:+ """One metered upstream call, in the shape the ledger folds it in."""++ source_id: str+ model_id: str+ usage: Optional[ProtocolUsageReport]+ at: datetime+++@dataclass+class _QueuedCall:+ call: UsageCall+ done: "asyncio.Future[None]"++class UsageWriter:"""Async ownership of every ledger write, so nothing can take one along.Metering has two populations — a call either hands its body onward or it doesnot — but the property that a queued write outlives whatever queued it belongs- to neither of them. It lives here once. A write is this object's task from the+ to neither of them. It lives here once. A write is this object's from themoment it exists, so a caller cancelled mid-flight loses its own ordering andnever the row, and a population added later inherits that by constructionrather than by remembering to.++ Queue, not fan-out. Calls accumulate while the flush ahead of them is on+ disk, and the next flush takes all of them in one transaction, so the backlog+ is bounded by what arrives during a single fsync however hard the hub is+ driven — without a capacity to pick, and without ever dropping a row, which+ would lose exactly the billed usage this module exists to keep."""def __init__(self, ledger: BoundedUsageLedger):self.ledger = ledger- self._writes: set[asyncio.Task[None]] = set()+ self._pending: list[_QueuedCall] = []+ # The batch on its way to disk, kept visible so a drain that times out+ # can count it: in the executor is not the same as persisted.+ self._writing: list[_QueuedCall] = []+ self._flush: Optional[asyncio.Task[None]] = Nonedef record(self,@@ -507,59 +584,75 @@ class UsageWriter:model_id: str,usage: Optional[ProtocolUsageReport],at: datetime,- ) -> "asyncio.Task[None]":- """Own one write and start it, handing back the task that will finish it.+ ) -> "asyncio.Future[None]":+ """Own one call and queue it, handing back what will finish it.Synchronous on purpose: nothing may suspend between a caller deciding tometer a call and this object owning the result, or a cancellation couldland in a window where the call is neither metered nor still meterable.- A caller that wants the row on disk before it returns awaits the task+ `at` is the caller's own reading from when its call ended, carried rather+ than re-read, because the flush that persists this can start well after+ it and a queued write is still a report about the moment it finished.++ A caller that wants the row on disk before it returns awaits the resultthrough `asyncio.shield`; one that does not can simply drop it."""- write = asyncio.create_task(- self._persist(source_id=source_id, model_id=model_id, usage=usage, at=at)+ queued = _QueuedCall(+ call=UsageCall(source_id=source_id, model_id=model_id, usage=usage, at=at),+ done=asyncio.get_running_loop().create_future(),)- self._writes.add(write)- write.add_done_callback(self._writes.discard)- return write+ self._pending.append(queued)+ if self._flush is None or self._flush.done():+ self._flush = asyncio.create_task(self._flush_pending())+ return queued.done++ @property+ def unpersisted(self) -> int:+ """How many metered calls this writer still owes the ledger.++ Queued and in-flight both count: handed to the writing thread is not the+ same as on disk.+ """++ return len(self._pending) + len(self._writing)async def drain(self, *, timeout: float) -> int:- """Wait out the writes still in flight; answers how many did not finish.+ """Wait out the calls still queued; answers how many did not reach disk.Bounded, because a ledger that cannot be reached must not hold a shutdownopen — the same trade every owned drain in the hub makes."""- pending = tuple(self._writes)- if not pending:- return 0- _done, unfinished = await asyncio.wait(pending, timeout=timeout)- return len(unfinished)+ flush = self._flush+ if flush is not None and not flush.done():+ await asyncio.wait((flush,), timeout=timeout)+ return self.unpersisted- async def _persist(- self,- *,- source_id: str,- model_id: str,- usage: Optional[ProtocolUsageReport],- at: datetime,- ) -> None:- """Run one ledger write off the loop, absorbing whatever it costs.+ async def _flush_pending(self) -> None:+ """Write queued calls a batch at a time until nothing is left waiting.- `at` is captured by the caller when its call ended, not read here: this- coroutine can start well after that, and a queued write is still a report- about the moment the call finished.+ The loop ends only with the queue empty and without having awaited since+ it saw that, which is what lets `record` treat a finished flush as proof+ that it must start the next one."""- try:- await asyncio.to_thread(- self.ledger.record,- source_id=source_id,- model_id=model_id,- usage=usage,- at=at,- )- except (OSError, ValueError) as exc:- logger.debug("Model Hub usage metering skipped one call: %s", exc)+ loop = asyncio.get_running_loop()+ while self._pending:+ batch = self._pending+ self._pending = []+ self._writing = batch+ try:+ await loop.run_in_executor(+ _ledger_executor(),+ self.ledger.record_many,+ tuple(queued.call for queued in batch),+ )+ except (OSError, ValueError) as exc:+ logger.debug("Model Hub usage metering skipped %d call(s): %s", len(batch), exc)+ finally:+ self._writing = []+ for queued in batch:+ if not queued.done.done():+ queued.done.set_result(None)diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex ddf50be8f..9529704e3 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -15,6 +15,12 @@ generation they were authored in, and sentences such as "Minimum v5 set" or`adapter-interface.py`'s dated header describe what that generation said. Only`contract_version` — the value a consumer reads and the closure below guards — moves.+Which of the two a sentence means is not left to the reader. A claim about the current+value spells `contract_version`, which is the token the closure guard matches, so a bare+`vN` is a generation name by construction. Prose that restated the number in its own+words is exactly how `api.md` came to advertise one value in its envelopes and another+in its own declarations.+The contracts and their consumers must coexist on one tested PR head before Model Hubcan be enabled. CI evaluates that head, not individual commits. A green intermediatecommit is not evidence that the complete final protocol has landed.@@ -90,7 +96,7 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-The terminal value 6 must coexist in all registered version locations on the same tested head:+`contract_version` 6 must coexist in all registered version locations on the same tested head:- `mirror-registry.json`- `agent-chain.schema.json`@@ -112,9 +118,10 @@ The terminal value 6 must coexist in all registered version locations on the sam- `ui/src/components/settings/models/*.test.*``tests/test_model_hub_config.py::test_every_versioned_object_ends_at_the_terminal_version_the_code_writes`-enforces the closure over whatever schemas this directory holds rather than over this-list, so a versioned object added later is covered without an edit here. This list stays-as the reader's map of where the value is published.+enforces the closure over whatever files this directory holds rather than over this list+— versioned objects by their shape, and every `contract_version` a document writes as+text — so an object or declaration added later is covered without an edit here. This+list stays as the reader's map of where the value is published.One object diverges, and only in what it accepts. Every versioned object except`TurnProvenance` is an envelope built and consumed inside one request, so it is pinneddiff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 50df584aa..0bf860548 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1,6 +1,6 @@# Model Hub — REST API contract-Status: **Normative v5** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.+Status: **Normative, `contract_version` 6** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.Success envelope: `{ok: true, contract_version: 6, ...}`.Failure envelope:@@ -16,8 +16,9 @@ table. The contract guard requires the two endpoint sets to be identical, requirexercised HTTP response for every registry entry, and validates that response againstthe route's named schema.-The shared envelope and every versioned nested contract use terminal version 5. Model-Hub has not shipped, so there is no internal contract migration or compatibility path.+The shared envelope and every versioned nested contract carry `contract_version` 6, the+terminal value. Model Hub has not shipped, so there is no internal contract migration or+compatibility path.## Route table@@ -52,7 +53,7 @@ Hub has not shipped, so there is no internal contract migration or compatibility| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. || POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same one-time matching and placement as Add Source; original files remain byte-identical. || GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object is contract v5; `not_started` is installed lazy-start idleness, not an alarm. |+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 6; `not_started` is installed lazy-start idleness, not an alarm. || POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. || POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Explicitly starts the managed engine. Uses the existing mutation authentication and CSRF guards; status reads never start it. |diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex fd0eb91e5..f122780e3 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -548,6 +548,78 @@ owner hands off to the writer exactly once with nothing else in either module reanything. A third population cannot be written with its own write lifetime; it inheritsone or it fails a test.+### Round 10 (head `2520031c4`)++Three findings, and class C a seventh time. The breaker is tripped, so this round starts+with the diagnosis rather than an edit.++**The class, restated over all seven heads.** Every member has the same shape: *a+metering fact is recorded later than the moment it became true*, so any ending between+those two moments loses the row permanently. What moved each round was only which gap+was left. Heads 1 and 2 and round 3 moved *what* is metered (which populations exist);+rounds 7 and 8 and 9 moved the *lifetime* of the write (who owns it once it is queued).+Round 10 is the last remaining gap and a different axis from both: *when the fact is+published to the object that will be asked for it*.++Concretely, `_TurnExecution.reached_model` derived its answer from two later+observations — a wire tracker, or a buffered verdict. The gateway adopts the upstream+body at `turn_gateway.py:619`, then prepares the downstream response, then starts+reading. A client that disconnects inside `response.prepare()` leaves neither+observation behind, so cleanup asked a question that had a true answer and got nothing.++**Why a third derivation would not close it.** Rounds 8 and 9 each added a mechanism to+carry the answer further; round 10's reviewer found the one ending that arrives before+any mechanism exists. Adding a fourth publication point only moves the gap earlier+again. The terminal form removes the derivation: *adoption is itself the proof*. The+gateway holds a body iff the call reached the model, the field is assigned before+anything downstream can fail, and nothing after it can unset it.++**Verified contract-preserving before shipping.** The pairing looked like a double-count+risk, because `ResolvedInvocation` (`service.py:279`) carries both a `handle` and an+`outcome`. `_invoke` (`service.py:4904`) settles it: `if handle.stream is not None:+return handle, None` — the resolver meters exactly the calls it completed itself, and+hands over exactly the ones it did not. The two populations are already partitioned by+`handle.stream is not None`, which is also the condition under which the gateway adopts.+The new branch is therefore purely additive: it fires only where the row used to be+dropped.++**Closing the unflagged sibling in the same edit.** The review reached the streaming+path. The buffered path has the same gap — cancelled mid-`outcome()`, before any verdict+exists — and `test_a_turn_cancelled_before_it_read_the_body_is_still_a_call_that_happened`+pins it. Its assertion is the honest one: `requests == 1` with `token_reports == 0`, which+is how the ledger says the vendor billed a call nobody got to read.++The streaming test is written as an invariant, not a list: it derives its failure points+from `FakeStreamResponse`'s own `*_error` parameters, so a downstream step that becomes+failable later is covered when it can fail rather than when someone remembers this test.++**P2 — ledger writes off the shared pool.** `record()` submitted one `asyncio.to_thread`+job per completed call into the loop's *default* executor, where `BoundedUsageLedger`'s+lock immediately serialized them across an `fsync`. A burst therefore occupied shared+workers that unrelated controller work needs, all but one of them waiting, and nothing+bounded the backlog. The fix owns the serialization instead of suffering it:+`UsageWriter` is now a queue whose flush takes everything that accumulated during the+previous write and hands it to `BoundedUsageLedger.record_many` as one transaction, on a+dedicated single-worker executor. The backlog is bounded by what arrives during one+fsync however hard the hub is driven, no row is ever dropped, and a batch of ten is+arithmetically the ten writes it replaces rather than a summary of them.++**P3 — the version-number class, closed rather than patched.** The reviewer flagged+`api.md`'s declaration that "every versioned nested contract uses terminal version 5"+while the same file's envelopes advertise 6 — the second contract-version finding on+this PR. The class is nameable, so the remaining members were enumerated instead of+waited for: the status header (line 3) and the `RuntimeDependency` note (line 55) made+the same stale claim and the review had not reached either.++The root cause is that `api.md` is listed under the README's version closure while the+closure test globbed only `*.schema.json`, so eighteen machine-checkable literals were+guarded and every prose declaration was not. The fix is one rule plus one guard: a claim+about the current value is written as `contract_version <n>` — the token the guard+matches — so a bare `vN` is a generation name by construction, and the closure test now+reads every non-schema file in the directory. The four legitimately historical `v5`+sentences the README already blessed stay untouched, and are now distinguishable+mechanically rather than by judgment.+## Todo- [x] Usage taxonomy and extraction in `stream_wire.py`diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex b981c3915..18087135e 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -741,6 +741,26 @@ def test_every_versioned_object_ends_at_the_terminal_version_the_code_writes():assert persisted <= checkedassert "api-response.schema.json" in checked+ # The schemas above are structured, so their versions are read from the shape.+ # Every other file beside them publishes the same number as text, and nothing+ # compared those: `api.md` carried the terminal value in eighteen envelopes+ # while three of its own declarations still named the previous one, which is+ # two review rounds spent on one stale sentence at a time. Matching the token+ # a consumer reads, rather than a list of sentences, is what makes the next+ # declaration fail here instead of in review — and it is why a claim about the+ # current value is written as `contract_version <n>` while a bare `vN` names+ # the generation a sentence was authored in.+ stated = 0+ for path in sorted(CONTRACTS.iterdir()):+ if not path.is_file() or path.name.endswith(".schema.json"):+ continue+ for value in re.findall(+ r"contract_version[^0-9]{0,12}(\d+)", path.read_text(encoding="utf-8")+ ):+ stated += 1+ assert int(value) == terminal, path.name+ assert stated+# The UI declares the same number as a literal type, and `tsc` is the only# thing that would have caught it drifting — one language boundary away from# every check above, which is where this bump went half-applied a second time.diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 63bed55cb..ba8945f96 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -2,10 +2,12 @@ from __future__ import annotationsimport astimport asyncio+import inspectimport jsonimport threadingfrom collections import dequefrom concurrent.futures import ThreadPoolExecutor+from contextlib import contextmanagerfrom datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom types import SimpleNamespace@@ -71,7 +73,7 @@ from core.handlers.model_hub.turn_gateway import (render_protocol_terminal_event,)from core.handlers.model_hub.stream_wire import ProtocolUsageReport-from core.handlers.model_hub.usage import BoundedUsageLedger+from core.handlers.model_hub.usage import BoundedUsageLedger, _ledger_executorfrom core.run_settlement import (SETTLED_BY_NO_TERMINAL_RESULT,SETTLED_BY_STOPPED,@@ -849,6 +851,30 @@ class BrokenUpstreamInvokeHandle:return self._outcome+@contextmanager+def _occupied_ledger_writer():+ """Hold the one thread ledger writes run on, so a queued write cannot start.++ That is the window where cancelling whoever awaits a write used to cancel the+ write itself, and it is only reachable while the writing thread is busy.+ """++ occupied = threading.Event()+ release = threading.Event()++ def occupy() -> None:+ occupied.set()+ release.wait(5)++ occupant = _ledger_executor().submit(occupy)+ assert occupied.wait(5)+ try:+ yield+ finally:+ release.set()+ occupant.result(timeout=5)++class FakeStreamResponse:def __init__(self,@@ -6357,27 +6383,13 @@ def test_a_cancelled_turn_cannot_take_the_ledger_write_it_queued_with_it() -> None:"""Review 4964754924: the gateway owns the write, so no ending can cancel it.- Occupy the loop's only executor thread and the ledger write is queued but not- started — the window where cancelling the awaiting task also cancels the work.- The turn dies there, and the row still lands, because what the turn owns is- the decision to meter and not the write that carries it out.+ Occupy the writing thread and the ledger write is queued but not started —+ the window where cancelling the awaiting task also cancels the work. The turn+ dies there, and the row still lands, because what the turn owns is the+ decision to meter and not the write that carries it out."""async def exercise() -> None:- loop = asyncio.get_running_loop()- executor = ThreadPoolExecutor(max_workers=1)- loop.set_default_executor(executor)- occupied = threading.Event()- release = threading.Event()-- def occupy() -> None:- occupied.set()- release.wait(5)-- occupant = loop.run_in_executor(executor, occupy)- while not occupied.is_set():- await asyncio.sleep(0.01)-source = _source("src_meterown01", "Owned write")service = _service(tmp_path,@@ -6399,20 +6411,18 @@ def test_a_cancelled_turn_cannot_take_the_ledger_write_it_queued_with_it(stream=False,)- turn = asyncio.create_task(gateway._handle_request(request))- while not gateway._usage_writer._writes:- await asyncio.sleep(0.01)- # The scenario is only the scenario while the write is still queued.- assert _usage_of(service, source.id) == {}+ with _occupied_ledger_writer():+ turn = asyncio.create_task(gateway._handle_request(request))+ while not gateway._usage_writer.unpersisted:+ await asyncio.sleep(0.01)+ # The scenario is only the scenario while the write is still queued.+ assert _usage_of(service, source.id) == {}- turn.cancel()- with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(turn, timeout=5)+ turn.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(turn, timeout=5)- release.set()- await occupantawait gateway.close()- executor.shutdown()metered = _usage_of(service, source.id)assert metered["requests"] == 1@@ -6428,26 +6438,12 @@ def test_a_cancelled_resolve_cannot_take_the_ledger_write_it_queued_with_it("""Review 4964894667: the same window at the other metering owner.A call the resolver consumed itself still reports tokens the vendor billed.- Occupy the loop's only executor thread and its row is queued but not started;- the caller is cancelled there, and the row lands anyway. Neither owner keeps- a write of its own, so neither can lose one — `UsageWriter` holds both.+ Occupy the writing thread and its row is queued but not started; the caller+ is cancelled there, and the row lands anyway. Neither owner keeps a write of+ its own, so neither can lose one — `UsageWriter` holds both."""async def exercise() -> None:- loop = asyncio.get_running_loop()- executor = ThreadPoolExecutor(max_workers=1)- loop.set_default_executor(executor)- occupied = threading.Event()- release = threading.Event()-- def occupy() -> None:- occupied.set()- release.wait(5)-- occupant = loop.run_in_executor(executor, occupy)- while not occupied.is_set():- await asyncio.sleep(0.01)-source = _source("src_meterown02", "Owned resolve write")service = _service(tmp_path,@@ -6467,30 +6463,28 @@ def test_a_cancelled_resolve_cannot_take_the_ledger_write_it_queued_with_it()requested_model = _canonicalize_fixed_test_routes(service)["codex"]- resolve = asyncio.create_task(- service.resolve(- backend="codex",- model_id=requested_model,- request=ModelHubRequest(- {"model": requested_model, "input": "ping"},- protocol="openai_responses",- ),- supply_channel="hub",+ with _occupied_ledger_writer():+ resolve = asyncio.create_task(+ service.resolve(+ backend="codex",+ model_id=requested_model,+ request=ModelHubRequest(+ {"model": requested_model, "input": "ping"},+ protocol="openai_responses",+ ),+ supply_channel="hub",+ ))- )- while not service.usage_writer._writes:- await asyncio.sleep(0.01)- # The scenario is only the scenario while the write is still queued.- assert _usage_of(service, source.id) == {}+ while not service.usage_writer.unpersisted:+ await asyncio.sleep(0.01)+ # The scenario is only the scenario while the write is still queued.+ assert _usage_of(service, source.id) == {}- resolve.cancel()- with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(resolve, timeout=5)+ resolve.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(resolve, timeout=5)- release.set()- await occupantassert await service.usage_writer.drain(timeout=5) == 0- executor.shutdown()metered = _usage_of(service, source.id)assert metered["requests"] == 1@@ -6500,6 +6494,84 @@ def test_a_cancelled_resolve_cannot_take_the_ledger_write_it_queued_with_it(asyncio.run(exercise())+def test_a_burst_of_metering_neither_borrows_the_shared_pool_nor_grows_unbounded(+ tmp_path: Path,+) -> None:+ """Review 4965076681: the writes queue on their own thread, a batch at a time.++ `record_many` holds the ledger's lock across an fsync, so one shared-pool job+ per completed call would park that many workers on a lock that admits one,+ and unrelated `asyncio.to_thread` work would wait behind metering for nothing.+ Hold the loop's default executor for the whole test and metering still lands:+ it was never borrowing from there.++ What bounds the queue is in the same run. Calls that arrive while a flush is+ on disk are taken together by the next one, so a burst costs transactions in+ proportion to how long the disk takes rather than to how hard the hub is+ driven — and every row still lands, which dropping them would not do.+ """++ async def exercise() -> None:+ loop = asyncio.get_running_loop()+ shared = ThreadPoolExecutor(max_workers=1)+ loop.set_default_executor(shared)+ borrowed_started = threading.Event()+ give_back = threading.Event()++ def borrow() -> None:+ borrowed_started.set()+ give_back.wait(5)++ borrower = loop.run_in_executor(shared, borrow)+ assert borrowed_started.wait(5)++ source = _source("src_meterburst1", "Burst")+ service = _service(tmp_path, sources=[source])+ transactions: list[int] = []+ fold = service.usage.record_many++ def counting(calls) -> None:+ transactions.append(len(calls))+ fold(calls)++ service.usage.record_many = counting+ writer = service.usage_writer++ def meter() -> None:+ writer.record(+ source_id=source.id,+ model_id="gpt-5-codex",+ usage=ProtocolUsageReport.of(+ input_tokens=1, cached_input_tokens=0, output_tokens=1+ ),+ at=NOW,+ )++ with _occupied_ledger_writer():+ meter()+ # White-box on purpose: the batch boundary is the thing under test,+ # and it is only observable once the first flush is holding one.+ while not writer._writing:+ await asyncio.sleep(0.01)+ for _ in range(7):+ meter()++ assert await writer.drain(timeout=5) == 0+ # Eight calls, two trips to disk — the second took every call that piled+ # up behind the first, which is the whole of the bound.+ assert transactions == [1, 7]++ metered = _usage_of(service, source.id)+ assert metered["requests"] == 8+ assert metered["input_tokens"] == 8++ give_back.set()+ await borrower+ shared.shutdown()++ asyncio.run(exercise())++def test_no_ending_of_a_turn_decides_for_itself_what_the_call_did() -> None:"""The metering facts have one owner, so an ending is a *when*, not a *what*.@@ -6522,6 +6594,112 @@ def test_no_ending_of_a_turn_decides_for_itself_what_the_call_did() -> None:assert all(len(call.args) == 1 and not call.keywords for call in calls)+def test_no_downstream_ending_after_adoption_can_drop_the_turn_from_the_ledger(+ tmp_path: Path,+) -> None:+ """Review 4965076681: the gateway takes the body before it can serve it.++ Between adopting the upstream body and reading it, the gateway prepares a+ downstream response — and a client that leaves in that gap leaves behind+ neither a wire tracker nor a buffered verdict for the boundary to read. The+ vendor billed the call either way, so what the ledger must not depend on is+ *where* the turn died.++ Driven off `FakeStreamResponse`'s own failure points instead of a list of+ them: a downstream step that becomes failable later is covered the moment it+ can fail, rather than the moment someone remembers this test.+ """++ failure_points = [+ name for name in inspect.signature(FakeStreamResponse).parameters if name.endswith("_error")+ ]+ assert failure_points++ async def exercise(point: str) -> None:+ state = tmp_path / point+ state.mkdir()+ source = _source("src_meterdrop01", "Adopted body")+ service = _service(+ state,+ sources=[source],+ live_handles=[+ LiveInvokeHandle(+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id),+ (+ b'event: response.output_text.delta\ndata: {"type":'+ b'"response.output_text.delta","sequence_number":1}\n\n',+ ),+ )+ ],+ )+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]+ gateway = ModelHubTurnGateway(service)+ request = _prepared_gateway_request(+ gateway,+ turn_id=f"turn_meter_{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()++ assert _usage_of(service, source.id).get("requests") == 1, 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:+ """The same gap on the buffered path, which the review did not reach.++ A non-streaming turn adopts the whole body and reads it in one go, so a+ client that disconnects while that read is in flight leaves the boundary+ exactly as empty-handed as the prepare gap does. Same adoption, same answer,+ and `token_reports` at zero is the ledger saying nobody got to read the+ tokens rather than that there were none.+ """++ async def exercise() -> None:+ source = _source("src_meterdrain01", "Adopted buffered body")+ handle = BlockingLiveInvokeHandle(+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id)+ )+ service = _service(tmp_path, sources=[source], live_handles=[handle])+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]+ gateway = ModelHubTurnGateway(service)+ request = _prepared_gateway_request(+ gateway,+ turn_id="turn_meter_cancelled_drain",+ requested_model=requested_model,+ source_id=source.id,+ stream=False,+ )++ turn = asyncio.create_task(gateway._handle_request(request))+ await asyncio.wait_for(handle.started.wait(), timeout=5)+ # The scenario is only the scenario while nothing has been read yet.+ assert _usage_of(service, source.id) == {}++ turn.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(turn, timeout=5)+ await gateway.close()++ metered = _usage_of(service, source.id)+ assert metered["requests"] == 1+ assert metered["token_reports"] == 0++ asyncio.run(exercise())++def test_gateway_meters_a_failed_turn_that_upstream_already_billed(tmp_path: Path,) -> None:@@ -6812,7 +6990,7 @@ def test_neither_metering_owner_writes_the_ledger_on_the_event_loop(async def exercise() -> None:recording_threads: list[int] = []- def capture(**_kwargs: object) -> None:+ def capture(_calls: object) -> None:recording_threads.append(threading.get_ident())resolver_source = _source("src_meterloop01", "Resolver owner")@@ -6832,7 +7010,7 @@ def test_neither_metering_owner_writes_the_ledger_on_the_event_loop()],)- resolver_service.usage.record = capture+ resolver_service.usage.record_many = capturerequested_model = _canonicalize_fixed_test_routes(resolver_service)["codex"]await resolver_service.resolve(backend="codex",@@ -6857,7 +7035,7 @@ def test_neither_metering_owner_writes_the_ledger_on_the_event_loop()],)- gateway_service.usage.record = capture+ gateway_service.usage.record_many = capturegateway_model = _canonicalize_fixed_test_routes(gateway_service)["codex"]gateway = ModelHubTurnGateway(gateway_service)await gateway._handle_request(@@ -6892,7 +7070,7 @@ def test_a_usage_ledger_failure_cannot_change_the_served_turn(tmp_path: Path) ->)],)- service.usage.record = Mock(side_effect=OSError("read-only state directory"))+ service.usage.record_many = Mock(side_effect=OSError("read-only state directory"))requested_model = _canonicalize_fixed_test_routes(service)["codex"]gateway = ModelHubTurnGateway(service)request = _prepared_gateway_request(@@ -6907,7 +7085,7 @@ def test_a_usage_ledger_failure_cannot_change_the_served_turn(tmp_path: Path) ->assert result.status == 200assert result.body == body- service.usage.record.assert_called_once()+ service.usage.record_many.assert_called_once()assert service.store.load().sources[0].state.status == "standby"asyncio.run(exercise())diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex a438bf93c..c80e8c6d2 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -313,7 +313,7 @@ def _ledger_writes(tree: ast.AST) -> tuple[ast.Attribute, ...]:nodefor node in ast.walk(tree)if isinstance(node, ast.Attribute)- and node.attr == "record"+ and node.attr in {"record", "record_many"}and isinstance(node.value, ast.Attribute)and node.value.attr in {"usage", "ledger"})@@ -543,7 +543,7 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:for node in ast.walk(_tree(USAGE))if isinstance(node, ast.ClassDef) and node.name == "UsageWriter")- persist = _functions(writer)["_persist"]+ persist = _functions(writer)["_flush_pending"]writes = _ledger_writes(writer)assert writesassert all(write in set(ast.walk(persist)) for write in writes)