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): let the gateway own the ledger write, not the turn
cyh8394984560e2
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex daafb9c59..2fb8e1afe 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -102,7 +102,10 @@ class _TurnExecution:# wire tracker to read them from.buffered_usage: ProtocolUsageReport | None = Nonebuffered_outcome: StreamTerminalOutcome | None = None- usage_recorded: bool = False+ # The gateway-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@propertydef reported_usage(self) -> ProtocolUsageReport | None:@@ -203,6 +206,9 @@ class ModelHubTurnGateway:now=self._now,))+ # Strong references to the writes in flight, so the gateway outlives the+ # turns that queued them and shutdown has something to drain.+ self._usage_writes: set[asyncio.Task[None]] = set()self._start_lock = asyncio.Lock()self._runner: web.AppRunner | None = Noneself._site: web.SockSite | None = None@@ -273,6 +279,17 @@ class ModelHubTurnGateway:self._base_url = Noneif runner is not None:await runner.cleanup()+ # After the runner, so the handlers it cancels have queued their last+ # writes first. Bounded like every other owned drain: a ledger that+ # cannot be reached must not hold shutdown open.+ pending = tuple(self._usage_writes)+ if pending:+ _done, unfinished = await asyncio.wait(pending, timeout=self._transport_timeout)+ if unfinished:+ logger.warning(+ "Model Hub usage metering left %d write(s) unfinished at shutdown",+ len(unfinished),+ )async def _ensure_started(self) -> None:if self._runner is not None:@@ -747,23 +764,62 @@ class ModelHubTurnGateway:The ledger read-modify-write is file I/O, so it runs off the event loop;metering is a report, never a control input, and a ledger failure must notchange the turn the caller sees.++ Which also means the turn cannot own the write. The gateway holds it, and+ the only await here is shielded, so an ending is a *when* in one more+ sense: it decides when a call is metered and never whether the metering+ survives. Nothing suspends between reading the facts and owning the write,+ so a cancellation lands either before this turn was ever going to be+ metered or after the write is already someone else's to finish.++ Shielded rather than detached because the ordinary path should still leave+ the row on disk before the turn ends — a caller reading the tab right after+ its own call sees it. Cancellation is the one ending that ordering cannot+ survive, and it is the ledger's guarantee that gives way, not the write."""resolved = execution.resolved- if execution.usage_recorded or resolved is None:+ if execution.usage_write is not None or resolved is None:returnusage = execution.reported_usageif not execution.reached_model and usage is None:return- execution.usage_recorded = True- try:- await asyncio.to_thread(- self.usage.record,+ write = asyncio.create_task(+ self._persist_usage(source_id=resolved.source_id,model_id=resolved.model_id,usage=usage,at=self._now(),)+ )+ execution.usage_write = write+ self._usage_writes.add(write)+ write.add_done_callback(self._usage_writes.discard)+ await asyncio.shield(write)++ async def _persist_usage(+ self,+ *,+ source_id: str,+ model_id: str,+ usage: ProtocolUsageReport | None,+ at: datetime,+ ) -> None:+ """Run one ledger write off the loop, absorbing whatever it costs.++ `at` is captured by the caller when the turn 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.+ """++ try:+ await asyncio.to_thread(+ self.usage.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 turn: %s", exc)diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex 1aff07b7e..45793c7da 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -453,6 +453,59 @@ in `test_model_hub_l3.py` would have started failing once the wall clock driftedthe retention horizon from it. Ledger construction now carries the same fake clock asits service.+### Round 8 (head `a481bc864`)++One P2 finding, and class C a fifth time: a forwarded call permanently omitted.+`usage_recorded` was set before the cancellable `asyncio.to_thread()` await, so a+downstream disconnect while that write sat queued behind a saturated executor+cancelled the write *and* left the flag saying it was done. Cleanup could not retry,+and the buffered path had already recorded settlement, so the boundary's own+`_settle_boundary_termination` never ran either.++Breaker diagnosis, as orchestrator. The four earlier instances were all "an ending+decides something about metering", and round 7 closed the *what* — no ending is asked+what the call did. This one is a different seam of the same class: the write's+**lifetime** was still bound to the turn. `_record_usage`'s docstring already claimed+metering is a report and never a control input, while the code made the report's+existence depend on the turn's control flow. Same shape as round 6's finding — code+contradicting its own written policy — so the ruling is the same: make the code mean+what it says, locally and reversibly, and continue.++The gateway already owns the pattern. Its cancellation boundary comment reads *"Only+the request is canceled. Owned teardown and settlement are shielded and drained before+this boundary re-raises"* — metering was the one piece of work never given that+treatment. So:++- `_TurnExecution.usage_recorded: bool` becomes `usage_write: asyncio.Task[None] | None`.+ The record that a turn was metered *is* the owner of its write, rather than a flag+ that something whose own death could take the write had started one.+- `_record_usage` creates that task, registers it in a gateway-held set, and only then+ awaits — shielded. Nothing suspends between reading the facts and owning the write,+ so a cancellation lands either before this turn was ever going to be metered or after+ the write is already someone else's to finish. An ending is now a *when* in one more+ sense: it decides when a call is metered, never whether the metering survives.+- Shielded rather than detached, deliberately. The ordinary path should still leave the+ row on disk before the turn ends, so a caller reading the tab right after its own call+ sees it. Cancellation is the one ending that ordering cannot survive, and there it is+ the ledger's read-your-write guarantee that gives way, not the write.+- `close()` drains the outstanding writes, bounded by the transport timeout like every+ other owned drain, and warns on overrun. `core/controller.py` already closes the+ gateway on shutdown, so this is a real drain rather than a decorative one.++`test_a_cancelled_turn_cannot_take_the_ledger_write_it_queued_with_it` reproduces the+window exactly rather than mocking around it: it pins the loop to a one-thread executor+and occupies that thread, so the ledger write is genuinely queued-not-started, asserts+the ledger is still empty (the scenario is only the scenario while the write is+queued), cancels the turn, then releases and drains. Replacing the shield with a plain+`await write` fails it with `KeyError: 'requests'` — the reviewer's permanent omission,+verbatim.++The structure guard `test_usage_metering_has_one_owner_per_call_population` now names+the gateway owner as the pair `_record_usage` + `_persist_usage`, and pays for the+second name with the constraint that makes it one owner: `_persist_usage` has exactly+one call site and it is inside `_record_usage`, the same single-caller assertion+`_meter_call` already carries.+## 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.pyindex 8708df3e7..f717b8769 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -5,6 +5,7 @@ import asyncioimport jsonimport threadingfrom collections import deque+from concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom types import SimpleNamespace@@ -6351,6 +6352,76 @@ def test_a_cancelled_buffered_turn_is_counted_even_when_it_reported_no_tokens(asyncio.run(exercise())+def test_a_cancelled_turn_cannot_take_the_ledger_write_it_queued_with_it(+ tmp_path: Path,+) -> 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.+ """++ 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,+ sources=[source],+ live_handles=[+ LiveInvokeHandle(+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id),+ (b'{"usage":{"input_tokens":512,"output_tokens":16}}',),+ )+ ],+ )+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]+ gateway = ModelHubTurnGateway(service)+ request = _prepared_gateway_request(+ gateway,+ turn_id="turn_meter_owned_write",+ requested_model=requested_model,+ source_id=source.id,+ stream=False,+ )++ turn = asyncio.create_task(gateway._handle_request(request))+ while not gateway._usage_writes:+ 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)++ release.set()+ await occupant+ await gateway.close()+ executor.shutdown()++ metered = _usage_of(service, source.id)+ assert metered["requests"] == 1+ assert metered["input_tokens"] == 512+ assert metered["output_tokens"] == 16++ 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*.diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex 0df02adc8..ac3e267d7 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -529,10 +529,12 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:# count or silently drop a billed call.service_tree = _tree(SERVICE)gateway_tree = _tree(TURN_GATEWAY)- owners = (- _functions(service_tree)["_meter_call"],- _functions(gateway_tree)["_record_usage"],- )+ recorder = _functions(gateway_tree)["_record_usage"]+ # The gateway owner is a pair: `_record_usage` decides, `_persist_usage` carries+ # the write off the loop so no turn's cancellation can take it. That is still one+ # owner only while the second half has exactly one caller, asserted below.+ persister = _functions(gateway_tree)["_persist_usage"]+ owners = (_functions(service_tree)["_meter_call"], recorder, persister)writes = _ledger_writes(service_tree) + _ledger_writes(gateway_tree)assert writesassert all(any(write in set(ast.walk(owner)) for owner in owners) for write in writes)@@ -542,17 +544,21 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:]assert len(meter_calls) == 1assert meter_calls[0] in set(ast.walk(invoke))+ persist_calls = [+ node for node in ast.walk(gateway_tree) if _call_name(node) == "_persist_usage"+ ]+ assert len(persist_calls) == 1+ assert persist_calls[0] in set(ast.walk(recorder))# Any of the gateway's endings may report the forwarded call, so exactly-once- # rests on its idempotence flag; a caller that pre-checks or clears the flag- # would move that decision outside the owner.- recorder = _functions(gateway_tree)["_record_usage"]- flags = [+ # rests on the write it owns; a caller that pre-checks or clears that handle+ # would move the decision outside the owner.+ handles = [nodefor node in ast.walk(gateway_tree)- if isinstance(node, ast.Attribute) and node.attr == "usage_recorded"+ if isinstance(node, ast.Attribute) and node.attr == "usage_write"]- assert flags- assert all(flag in set(ast.walk(recorder)) for flag in flags)+ assert handles+ assert all(handle in set(ast.walk(recorder)) for handle in handles)def test_model_identity_is_decided_only_by_its_owner() -> None: