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): give both metering populations one write owner
cyh2520031c4444
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 2d31e8d1b..09960dd8c 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -110,7 +110,7 @@ from .resolver import (source_runnable,)from .revocations import CredentialRevocationJournal-from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger+from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, UsageWriterCONTRACT_VERSION = 6AGENT_CHAIN_CONTRACT_VERSION = 6@@ -595,6 +595,9 @@ class ModelHubService:paths.get_state_dir() / "model_hub_usage.json",now=now,)+ # One writer per ledger, shared with the gateway: both metering populations+ # then have the same owner for the lifetime of what they write.+ self.usage_writer = UsageWriter(self.usage)self.native_oauth_adapter = native_oauth_adapter or UnavailableNativeOAuthAdapter()self.oauth_flows = oauth_flows or OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json",@@ -4942,20 +4945,23 @@ class ModelHubService: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 outcome the caller sees.++ Which is also why the write is the writer's and not this call's: a resolve+ cancelled downstream while its row sat queued would otherwise discard usage+ the vendor had already billed. Shielded rather than dropped so the ordinary+ path still leaves the row on disk before the caller sees its outcome."""if outcome.usage is None:return- try:- await asyncio.to_thread(- self.usage.record,+ await asyncio.shield(+ self.usage_writer.record(source_id=source_id,model_id=model_id,usage=outcome.usage,at=self.now(),)- except (OSError, ValueError) as exc:- logger.debug("Model Hub usage metering skipped one call: %s", exc)+ )async def _classify_source_outcome(self,diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex 2fb8e1afe..ae0947cfb 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -44,7 +44,7 @@ from .stream_wire import (render_protocol_terminal_event,render_protocol_terminal_frame,)-from .usage import BoundedUsageLedger+from .usage import BoundedUsageLedger, UsageWriterfrom .service import (HandleSettlement,HandleTerminationOrigin,@@ -102,7 +102,7 @@ class _TurnExecution:# wire tracker to read them from.buffered_usage: ProtocolUsageReport | None = Nonebuffered_outcome: StreamTerminalOutcome | None = None- # The gateway-owned task that persists this turn's row, and by its existence+ # 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@@ -206,9 +206,14 @@ 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()+ # The service's writer whenever both write the same ledger, so one drain+ # covers both metering populations rather than one per population.+ service_writer = getattr(service, "usage_writer", None)+ self._usage_writer = (+ service_writer+ if isinstance(service_writer, UsageWriter) and service_writer.ledger is self.usage+ else UsageWriter(self.usage)+ )self._start_lock = asyncio.Lock()self._runner: web.AppRunner | None = Noneself._site: web.SockSite | None = None@@ -282,14 +287,12 @@ class ModelHubTurnGateway:# 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),- )+ unfinished = await self._usage_writer.drain(timeout=self._transport_timeout)+ if unfinished:+ logger.warning(+ "Model Hub usage metering left %d write(s) unfinished at shutdown",+ unfinished,+ )async def _ensure_started(self) -> None:if self._runner is not None:@@ -765,11 +768,11 @@ class ModelHubTurnGateway: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+ Which also means the turn cannot own the write. `UsageWriter` holds it, andthe only await here is shielded, so an ending is a *when* in one moresense: 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+ survives. Nothing suspends between reading the facts and handing the write+ over, so a cancellation lands either before this turn was ever going to bemetered or after the write is already someone else's to finish.Shielded rather than detached because the ordinary path should still leave@@ -784,44 +787,13 @@ class ModelHubTurnGateway:usage = execution.reported_usageif not execution.reached_model and usage is None:return- 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 = self._usage_writer.record(+ 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)+ await asyncio.shield(execution.usage_write)async def _write_stream_terminal_copy(self,diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex a79f10082..bb370a48c 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -19,6 +19,7 @@ usage.from __future__ import annotations+import asyncioimport jsonimport loggingimport os@@ -482,3 +483,83 @@ class BoundedUsageLedger:],"days": [by_day[day] for day in sorted(by_day)],}+++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 does+ not — 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+ moment it exists, so a caller cancelled mid-flight loses its own ordering and+ never the row, and a population added later inherits that by construction+ rather than by remembering to.+ """++ def __init__(self, ledger: BoundedUsageLedger):+ self.ledger = ledger+ self._writes: set[asyncio.Task[None]] = set()++ def record(+ self,+ *,+ source_id: str,+ 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.++ Synchronous on purpose: nothing may suspend between a caller deciding to+ meter a call and this object owning the result, or a cancellation could+ land 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+ through `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)+ )+ self._writes.add(write)+ write.add_done_callback(self._writes.discard)+ return write++ async def drain(self, *, timeout: float) -> int:+ """Wait out the writes still in flight; answers how many did not finish.++ Bounded, because a ledger that cannot be reached must not hold a shutdown+ open — 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)++ 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.++ `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.+ """++ 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)diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex 45793c7da..fd0eb91e5 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -506,6 +506,48 @@ second name with the constraint that makes it one owner: `_persist_usage` has exone call site and it is inside `_record_usage`, the same single-caller assertion`_meter_call` already carries.+### Round 9 (head `839498456`)++One P2 finding, and class C a sixth time — at the address round 8 should have covered.+`ModelHubService._meter_call` still awaited `asyncio.to_thread()` inline, so a bodyless+attempt that upstream had already billed (a failover error carrying usage) lost its row+to exactly the window round 8 closed at the gateway: cancellation reaching the queued+executor future before `record()` starts.++This is not a new class, it is the sibling the round-8 note could already have named.+The skill's rule is explicit — *the moment you can enumerate the members the reviewer+has not reached yet, close the class now* — and round 8 knew metering has exactly two+owners, because the guard that asserts it was edited in the same commit. Patching the+second site would buy the same finding back at whatever third population arrives.++So the closure is ownership, not a second patch. Write-lifetime is a third property:+neither population decides it, both need it, and it had no owner. `UsageWriter` in+`usage.py` is that owner.++- `UsageWriter.record()` is **synchronous** on purpose. Nothing may suspend between a+ caller deciding to meter a call and the writer owning the result, or a cancellation+ could land in the window where the call is neither metered nor still meterable. It+ starts the task, keeps a strong reference, and hands the task back.+- Both owners keep their existing shape: decide, hand off, `await asyncio.shield(...)`.+ A caller that wants the row on disk before it returns awaits; one that does not can+ drop the task. Read-your-write survives on the ordinary path, and only cancellation+ gives up ordering — never the write.+- `drain(timeout=...)` replaces the gateway's private set. The gateway reuses+ `service.usage_writer` whenever both write the same ledger, so one bounded drain at+ `close()` covers both populations rather than one drain per population.++`test_a_cancelled_resolve_cannot_take_the_ledger_write_it_queued_with_it` mirrors the+round-8 test at the resolver: one-thread executor occupied, row queued-not-started,+ledger asserted empty, caller cancelled, then released and drained. Dropping the shield+fails it with `KeyError: 'requests'` — the same permanent omission, at the other owner.++The structure guard is what makes this a closure rather than a second patch. It now+asserts that **neither** `service.py` nor `turn_gateway.py` touches the ledger at all,+that every ledger write in `usage.py` is inside `UsageWriter._persist`, and that each+owner hands off to the writer exactly once with nothing else in either module recording+anything. A third population cannot be written with its own write lifetime; it inherits+one or it fails a test.+## 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 f717b8769..63bed55cb 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -6400,7 +6400,7 @@ def test_a_cancelled_turn_cannot_take_the_ledger_write_it_queued_with_it()turn = asyncio.create_task(gateway._handle_request(request))- while not gateway._usage_writes:+ 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) == {}@@ -6422,6 +6422,84 @@ def test_a_cancelled_turn_cannot_take_the_ledger_write_it_queued_with_it(asyncio.run(exercise())+def test_a_cancelled_resolve_cannot_take_the_ledger_write_it_queued_with_it(+ tmp_path: Path,+) -> None:+ """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.+ """++ 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,+ sources=[source],+ outcomes=[+ _outcome(+ RawOutcomeKind.SUCCESS,+ status=200,+ source_id=source.id,+ usage=ProtocolUsageReport.of(+ input_tokens=512,+ cached_input_tokens=0,+ output_tokens=16,+ ),+ )+ ],+ )+ 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",+ )+ )+ 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) == {}++ resolve.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(resolve, timeout=5)++ release.set()+ await occupant+ assert await service.usage_writer.drain(timeout=5) == 0+ 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 ac3e267d7..a438bf93c 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -315,7 +315,7 @@ def _ledger_writes(tree: ast.AST) -> tuple[ast.Attribute, ...]:if isinstance(node, ast.Attribute)and node.attr == "record"and isinstance(node.value, ast.Attribute)- and node.value.attr == "usage"+ and node.value.attr in {"usage", "ledger"})@@ -530,25 +530,43 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:service_tree = _tree(SERVICE)gateway_tree = _tree(TURN_GATEWAY)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)+ owners = (_functions(service_tree)["_meter_call"], recorder)+ # Reviews 4964754924 / 4964894667: an owner decides *that* a call is metered,+ # but how long that write outlives whoever queued it is a third property and+ # belongs to neither population. `UsageWriter` owns it once, so neither owner+ # may touch the ledger itself and a population added later inherits the+ # lifetime by construction instead of by remembering to.+ assert not _ledger_writes(service_tree)+ assert not _ledger_writes(gateway_tree)+ writer = next(+ node+ for node in ast.walk(_tree(USAGE))+ if isinstance(node, ast.ClassDef) and node.name == "UsageWriter"+ )+ persist = _functions(writer)["_persist"]+ writes = _ledger_writes(writer)assert writes- assert all(any(write in set(ast.walk(owner)) for owner in owners) for write in writes)+ assert all(write in set(ast.walk(persist)) for write in writes)+ # Which leaves each owner one job at the writer, and leaves nothing else in+ # either module recording anything at all.+ handoffs = [+ node+ for tree in (service_tree, gateway_tree)+ for node in ast.walk(tree)+ if _call_name(node) == "record"+ ]+ assert handoffs+ assert all(any(handoff in set(ast.walk(owner)) for owner in owners) for handoff in handoffs)+ assert all(+ len([handoff for handoff in handoffs if handoff in set(ast.walk(owner))]) == 1+ for owner in owners+ )invoke = _functions(service_tree)["_invoke"]meter_calls = [node for node in ast.walk(service_tree) if _call_name(node) == "_meter_call"]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 the write it owns; a caller that pre-checks or clears that handle# would move the decision outside the owner.