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): own the label join, bound the write queue, serve usage natively

cyha85a88569478
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index cf6759ecd..a00038837 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -3623,16 +3623,24 @@ class ModelHubService:
def usage_summary(self, *, days: int = USAGE_DEFAULT_WINDOW_DAYS) -> dict:
"""Report metered token usage, labelled from current Source config.
- Labels are joined here rather than persisted: a Source label is
- user-supplied text that the ledger has no business storing, and a join
- keeps a rename visible immediately instead of freezing old copies.
+ Config is what this method owns: which identities exist right now and what
+ they are called. The join itself belongs to the ledger, because only the
+ ledger knows how a row is keyed — the version of this method that looked a
+ label up by `row["source_id"]` is what that rule looks like once it has
+ leaked to a caller, and it silently dropped the label of every identity the
+ key fold exists for.
+
+ A model's own identity is its label, which matters for the same reason:
+ a folded row publishes a key, not the identifier the user typed.
"""
- summary = self.usage.summary(days=days, now=self.now())
- labels = {source.id: source.display_name for source in self.store.load().sources}
- for source in summary["sources"]:
- source["label"] = labels.get(source["source_id"])
- return summary
+ config = self.store.load()
+ return self.usage.summary(
+ days=days,
+ now=self.now(),
+ source_labels={source.id: source.display_name for source in config.sources},
+ model_labels={model.id: model.id for source in config.sources for model in source.models},
+ )
def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
events = self.events.list(limit=limit, before=before)
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index d351bd8da..00b817b08 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -24,10 +24,10 @@ import json
import logging
import threading
from concurrent.futures import ThreadPoolExecutor
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
-from typing import Callable, Final, Optional, Sequence
+from typing import Callable, Final, Mapping, Optional, Sequence
from .identifiers import persisted_ledger_key, usage_ledger_key
from .state_file import write_state_document
@@ -196,6 +196,27 @@ def _normalize_row(row: object) -> Optional[dict]:
return normalized
+def _keyed_labels(labels: Optional[Mapping[str, Optional[str]]]) -> dict[str, Optional[str]]:
+ """Key one identity-to-label mapping the way the rows it will join were keyed.
+
+ The read half of the rule `record_many` applies on the write half: an identity
+ a caller holds is not the key its rows carry, and a long one differs from it
+ entirely. Deriving here rather than in the caller is what keeps a join from
+ silently missing exactly the identities the fold exists for.
+
+ Two identities that key the same are the same identity spelled differently —
+ `usage_ledger_key` is injective over anything else — so the later one wins, as
+ it would in the mapping the caller built.
+ """
+
+ keyed: dict[str, Optional[str]] = {}
+ for identity, label in (labels or {}).items():
+ key = usage_ledger_key(identity)
+ if key is not None:
+ keyed[key] = label
+ return keyed
+
+
def _recency(row: dict) -> tuple[str, datetime]:
"""Order rows oldest-metered first, so the bound evicts what costs least.
@@ -344,7 +365,9 @@ class BoundedUsageLedger:
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.
+ replaces, never a summary of them. A call that already speaks for several
+ (`UsageCall.requests`) folds by the same arithmetic onto the same row those
+ calls would each have reached.
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
@@ -373,8 +396,8 @@ class BoundedUsageLedger:
"day": local_usage_day(metered_at).isoformat(),
"source_id": source_key,
"model_id": model_key,
- "requests": 1,
- "token_reports": 1 if usage is not None else 0,
+ "requests": call.requests,
+ "token_reports": call.requests 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,
@@ -453,12 +476,35 @@ class BoundedUsageLedger:
rows = self._read()
return [row for row in rows if first_day <= row["day"] <= last_day]
- def summary(self, *, days: int = USAGE_DEFAULT_WINDOW_DAYS, now: datetime) -> dict:
- """Aggregate the window into the label-free settings-page read shape."""
+ def summary(
+ self,
+ *,
+ days: int = USAGE_DEFAULT_WINDOW_DAYS,
+ now: datetime,
+ source_labels: Optional[Mapping[str, Optional[str]]] = None,
+ model_labels: Optional[Mapping[str, Optional[str]]] = None,
+ ) -> dict:
+ """Aggregate the window into the read shape the settings page consumes.
+
+ Labels are joined here rather than persisted, because a display name is
+ user-supplied text this ledger has no business storing and a join keeps a
+ rename visible immediately instead of freezing old copies. They arrive as
+ *identities* and are keyed here rather than by the caller, because a row is
+ keyed and the component holding config is not the one that knows that: the
+ caller that keyed its own map looked a label up by `row["source_id"]`, so a
+ source whose ID is past the admission bound reported no label while still
+ existing, and its renames never appeared.
+
+ A model's label is its own identity, which only matters for a folded row.
+ There the key is a head plus a digest, so a tab drawing `model_id` would
+ show a string nobody typed; the label carries the identity back.
+ """
bounded_days = max(1, min(int(days), self.retention_days))
today = local_usage_day(now)
rows = self.window(days=bounded_days, now=now)
+ keyed_source_labels = _keyed_labels(source_labels)
+ keyed_model_labels = _keyed_labels(model_labels)
totals = _empty_totals()
sources: dict[str, dict] = {}
@@ -470,6 +516,7 @@ class BoundedUsageLedger:
row["source_id"],
{
"source_id": row["source_id"],
+ "label": keyed_source_labels.get(row["source_id"]),
**_empty_totals(),
"last_metered_at": None,
"models": {},
@@ -482,7 +529,11 @@ class BoundedUsageLedger:
)
model = source["models"].setdefault(
row["model_id"],
- {"model_id": row["model_id"], **_empty_totals()},
+ {
+ "model_id": row["model_id"],
+ "label": keyed_model_labels.get(row["model_id"]),
+ **_empty_totals(),
+ },
)
_accumulate(model, row)
@@ -536,16 +587,70 @@ def _ledger_executor() -> ThreadPoolExecutor:
@dataclass(frozen=True)
class UsageCall:
- """One metered upstream call, in the shape the ledger folds it in."""
+ """One metered upstream call, in the shape the ledger folds it in.
+
+ Or several of them. `requests` is how many calls this value speaks for, so a
+ queue can fold the ones that will land on a single row before they reach the
+ disk without a second shape existing for a folded call. Every call folded
+ together agrees on whether tokens were reported — that is part of what makes
+ them one row — so `token_reports` stays derivable from `usage` instead of
+ becoming a second additive field able to disagree with `requests`.
+ """
source_id: str
model_id: str
usage: Optional[ProtocolUsageReport]
at: datetime
+ requests: int = 1
+
+ @property
+ def fold_key(self) -> tuple[str, str, str, bool]:
+ """What makes two calls one row, in the terms available before the write.
+
+ The ledger's own row key plus whether tokens were reported, which is the
+ part that keeps a fold arithmetically identical to the calls it replaces.
+ The day is this call's own bucket, exactly as `record` describes: the write
+ may still clamp it to the moment it persists, and two buckets clamped onto
+ one day meet again in `record_many`, which folds by row key regardless.
+ """
+
+ return (
+ local_usage_day(_aware(self.at)).isoformat(),
+ self.source_id,
+ self.model_id,
+ self.usage is not None,
+ )
+
+ def folded_with(self, other: "UsageCall") -> "UsageCall":
+ """Fold a call that shares this one's row into a single value.
+
+ Arithmetically the calls it replaces: counts add, token counts add, and
+ the stamp is the later of the two — which is what the row would have kept
+ anyway, since `record_many` keeps the newer stamp. Nothing is bounded here;
+ every counter is bounded where rows are normalized, so a fold that
+ saturates the ceiling saturates it identically.
+ """
+
+ reports = [report for report in (self.usage, other.usage) if report is not None]
+ usage = None
+ if reports:
+ usage = ProtocolUsageReport.of(
+ input_tokens=sum(report.input_tokens for report in reports),
+ cached_input_tokens=sum(report.cached_input_tokens for report in reports),
+ output_tokens=sum(report.output_tokens for report in reports),
+ )
+ return replace(
+ self,
+ usage=usage,
+ at=max(_aware(self.at), _aware(other.at)),
+ requests=self.requests + other.requests,
+ )
@dataclass
-class _QueuedCall:
+class _QueuedRow:
+ """One queued row and the future every call folded into it is waiting on."""
+
call: UsageCall
done: "asyncio.Future[None]"
@@ -560,20 +665,28 @@ class UsageWriter:
never the row, and a population added later inherits that by construction
rather 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.
+ Queue, not fan-out, and folded rather than capped. Calls accumulate while the
+ flush ahead of them is on disk and the next flush takes all of them in one
+ transaction; the ones heading for a single row fold into a single queued row as
+ they arrive. The backlog is therefore bounded by the identities config holds
+ rather than by how hard the hub is driven or by how long one write takes — a
+ flush stuck on an unresponsive disk cannot grow it past that bound, which is
+ the whole of what "bounded" can mean here. The alternatives both cost
+ something this module exists to prevent: a capacity means choosing rows to
+ drop, which loses billed usage, and blocking the caller stalls a served turn
+ on a disk that is already failing.
"""
def __init__(self, ledger: BoundedUsageLedger):
self.ledger = ledger
- self._pending: list[_QueuedCall] = []
+ self._pending: dict[tuple[str, str, str, bool], _QueuedRow] = {}
# 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._writing: tuple[_QueuedRow, ...] = ()
self._flush: Optional[asyncio.Task[None]] = None
+ # Whether the last flush lost its batch, so an outage is reported when it
+ # starts and ends rather than once per failed write.
+ self._dropping = False
def record(
self,
@@ -594,14 +707,18 @@ class UsageWriter:
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 result
- through `asyncio.shield`; one that does not can simply drop it.
+ through `asyncio.shield`; one that does not can simply drop it. Callers
+ whose calls fold together share one future, which is the same promise each
+ would have had alone: it completes when their row reaches the disk.
"""
- queued = _QueuedCall(
- call=UsageCall(source_id=source_id, model_id=model_id, usage=usage, at=at),
- done=asyncio.get_running_loop().create_future(),
- )
- self._pending.append(queued)
+ call = UsageCall(source_id=source_id, model_id=model_id, usage=usage, at=at)
+ queued = self._pending.get(call.fold_key)
+ if queued is None:
+ queued = _QueuedRow(call=call, done=asyncio.get_running_loop().create_future())
+ self._pending[call.fold_key] = queued
+ else:
+ queued.call = queued.call.folded_with(call)
if self._flush is None or self._flush.done():
self._flush = asyncio.create_task(self._flush_pending())
return queued.done
@@ -611,10 +728,12 @@ class UsageWriter:
"""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.
+ same as on disk. Calls, not queued rows — folding is how this object stays
+ bounded, and answering in rows would make a backlog look like it shrank
+ because the hub got busier.
"""
- return len(self._pending) + len(self._writing)
+ return sum(queued.call.requests for queued in (*self._pending.values(), *self._writing))
async def drain(self, *, timeout: float) -> int:
"""Wait out the calls still queued; answers how many did not reach disk.
@@ -638,8 +757,8 @@ class UsageWriter:
loop = asyncio.get_running_loop()
while self._pending:
- batch = self._pending
- self._pending = []
+ batch = tuple(self._pending.values())
+ self._pending = {}
self._writing = batch
try:
await loop.run_in_executor(
@@ -648,9 +767,51 @@ class UsageWriter:
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)
+ self._report_dropped(batch, exc)
+ else:
+ self._report_recovered()
finally:
- self._writing = []
+ self._writing = ()
for queued in batch:
if not queued.done.done():
queued.done.set_result(None)
+
+ def _report_dropped(self, batch: Sequence[_QueuedRow], exc: BaseException) -> None:
+ """Report that metering stopped, once per outage rather than per flush.
+
+ A ledger that cannot be written must not hold up the turns it meters, so a
+ failed batch is lost by design — but a state directory that has gone
+ read-only then looks exactly like a hub with nothing to record, which is
+ the one reading that makes this module's absence invisible. Saying it at
+ `debug` said it to nobody.
+
+ The transition carries the information, so the transition is what is
+ logged: bounded by how often the ledger changes state rather than by how
+ long an outage lasts, which is the bound a counter would be approximating.
+ """
+
+ calls = sum(queued.call.requests for queued in batch)
+ if self._dropping:
+ logger.debug(
+ "Model Hub usage metering still cannot write %s, dropped %d call(s): %s",
+ self.ledger.path,
+ calls,
+ exc,
+ )
+ return
+ self._dropping = True
+ logger.warning(
+ "Model Hub usage metering cannot write %s and is dropping metered calls "
+ "(%d lost in this batch); the usage tab will under-report until it recovers: %s",
+ self.ledger.path,
+ calls,
+ exc,
+ )
+
+ def _report_recovered(self) -> None:
+ """Close an outage the same way it was opened, so the gap has both edges."""
+
+ if not self._dropping:
+ return
+ self._dropping = False
+ logger.warning("Model Hub usage metering recovered; %s is writable again", self.ledger.path)
diff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.json
index 9bdf9f73f..58a5841a2 100644
--- a/docs/plans/model-hub-contracts/usage-summary.schema.json
+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json
@@ -144,6 +144,7 @@
"type": "object",
"required": [
"model_id",
+ "label",
"requests",
"token_reports",
"input_tokens",
@@ -153,9 +154,14 @@
"additionalProperties": false,
"properties": {
"model_id": {
+ "description": "Ledger key, which for a long identifier is a head plus a digest rather than the identifier itself. Display label, never model_id.",
"type": "string",
"minLength": 1
},
+ "label": {
+ "description": "The model identity this row was metered under, joined from current Source config; null once the model is gone.",
+ "type": ["string", "null"]
+ },
"requests": {
"$ref": "#/definitions/Count"
},
@@ -231,6 +237,7 @@
"models": [
{
"model_id": "claude-opus-4-6",
+ "label": "claude-opus-4-6",
"requests": 12,
"token_reports": 9,
"input_tokens": 148230,
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index 2964b0a4b..e80a32abc 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -811,6 +811,78 @@ pair fails it without being named, and a read-back test fixes which keys a row m
carry. Four mutations, four distinct failures: the late fold threshold, a re-deriving
read path, a truncation-only fold, and an unbounded read.
+### Round 15 (head `5507c5708`)
+
+CI went fully green and the review returned four P2 findings: one more instance of the
+identity-keying property — its third consecutive head, at a new call site — and three
+first instances in code this PR introduced. The diagnosis is recorded before the edits.
+
+**F1: the label join was keyed by the identity, not by the row.** `usage_summary` built
+`{source.id: source.display_name}` and looked it up with `row["source_id"]`, which is a
+*key*. A source whose ID is past the admission bound therefore reported `label: null`
+while still existing, and a rename never appeared. The reviewer's one-line fix — key the
+map with `usage_ledger_key` — is correct and insufficient: this is the third head on
+which a call site had to remember the keying rule, so the property-ownership rule
+applies and ownership has to move rather than the site being patched. The ledger is the
+only component that knows its rows are keyed, so `summary` now takes the labels as
+*identities* and keys them itself, and `usage_summary` no longer touches a row's key
+fields at all. The model half ships with it instead of waiting for the reviewer to reach
+it: a folded model row publishes a key that is not the identity the user typed, so the
+tab has to join that identity back the same way a source label is joined.
+
+**F2: the queue was bounded by arrival rate, not by anything we measure.** The writer's
+own docstring claimed the backlog "is bounded by what arrives during a single fsync
+however hard the hub is driven". That is only a bound while an fsync is fast — under a
+hung disk it is a restatement of "unbounded", which is the same failure mode as rounds
+13 and 14: prose asserting a bound the code does not enforce. The three ways out are not
+equal. A capacity that drops loses exactly the billed usage this module exists to keep;
+backpressure stalls a served turn on a hung disk; folding loses nothing, because the
+ledger already folds calls onto `(day, source, model)` rows when it writes them. So the
+queue now folds on arrival: calls that share a day, a source, a model, and whether they
+reported tokens become one queued row carrying a `requests` count, and the pending set
+is bounded by the identities config holds rather than by traffic. Grouping on *whether*
+tokens were reported is what keeps `token_reports` derivable from `requests`, so no
+second additive field is needed and `token_reports <= requests` holds by construction.
+
+**F3: a dropped batch was invisible.** The `OSError`/`ValueError` branch logged at
+`debug`, so metering that stops because the state directory is read-only looks exactly
+like metering that has nothing to record. It now warns on the transition into that state
+and on recovery out of it, which bounds the volume by the number of state changes rather
+than by the number of failed flushes — a counter would need arithmetic to say the same
+thing less precisely.
+
+**F4: the new route expanded the compat surface.** `GET /api/models/usage` was added as
+`@app.route`, which the repo's Web UI Server rule reserves for the migration scaffold,
+and it reached the ledger through the sync 300s RPC from the compat threadpool. It is
+now a native FastAPI route awaiting an async client method. The guard that keeps it that
+way is the mirror image of the one already covering the controller: the ledger read
+blocks on the same lock writers hold across fsync, so *every* path into it must be off
+the thread that would otherwise be serving requests, in the UI process as much as in the
+controller.
+
+**Evidence.** `MH-USAGE-008` states F1's property as a join that survives folding: a
+source whose ID is past the admission bound gets its label, and a rename shows up
+immediately. `MH-USAGE-009` states F2's bound as one that traffic cannot move — 512
+calls over four identities leave four queued rows and still meter 512 requests — and a
+drop test fixes F3's transition warning. Three structure guards close the two classes
+against the next call site: `usage_ledger_key` has exactly one importer and
+`usage_summary` may not subscript a row's key fields; every UI function that reaches the
+read must be async, awaited, and served through the native dispatch, and the client
+method behind it may not be sync; and the list of ledger reads both loops scan for is
+asserted to be the whole of what the service exposes, so a second reader fails a test
+rather than escaping both name lists. Eight mutations, eight distinct failures.
+
+Making the read async also exposed a latent defect in the response-conformance driver,
+which enumerates every route in `api-response.schema.json` and drives it against a stub.
+The stub was the controller service, so the driver had been asserting that the routes
+work against a shape no deployment has — the routes call the *client*, whose
+`usage_summary` is async precisely because the service's is sync. `GET /api/models/usage`
+returned HTTP 500 there while working in the browser. The stub now takes its sync/async
+shape from `ModelHubRemoteService` itself rather than from a list of method names, so the
+next async-only read is carried without an edit. With that fixed, the driver validates a
+real summary against `usage-summary.schema.json`, which is what makes `label` a contract
+rather than a field the ledger happens to emit.
+
## Todo
- [x] Usage taxonomy and extraction in `stream_wire.py`
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 0f5e9c082..f567bb7ae 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -161,6 +161,18 @@ scenarios:
kind: persistence
layer: unit
test: tests/test_model_hub_usage.py::test_no_two_identities_a_config_holds_can_share_one_row
+ - id: MH-USAGE-008
+ name: Every metered row is labelled under the identity it was metered for, however it was keyed
+ status: covered
+ kind: compatibility
+ layer: unit
+ test: tests/test_model_hub_usage.py::test_a_label_reaches_the_row_of_every_identity_the_ledger_can_key
+ - id: MH-USAGE-009
+ name: A metering backlog is bounded by configured identities rather than by request rate
+ status: covered
+ kind: concurrency
+ layer: unit
+ test: tests/test_model_hub_usage.py::test_the_write_queue_is_bounded_by_identities_not_by_arrival_rate
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 920272156..7b6c29e81 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -541,6 +541,35 @@ def _seed_response_conformance_service(tmp_path: Path) -> ModelHubService:
return service
+def _as_ui_client(service):
+ """Give a controller service the sync/async shape the UI routes are written against.
+
+ The routes call `ModelHubRemoteService`, and one of its reads is deliberately
+ async where the service's is sync: `usage_summary` blocks on the lock the
+ ledger's writers hold across an fsync, so the RPC hop crosses a thread and the
+ UI side awaits rather than occupying a worker. A stub shaped like the service
+ instead makes every route look synchronous, which is a shape no deployment
+ has — the conformance driver below reported HTTP 500 on a route that works.
+
+ Derived from the client class rather than from a list of method names, so the
+ next async-only read is carried without editing this helper.
+ """
+
+ class UIClientShape:
+ def __getattr__(self, name):
+ attribute = getattr(service, name)
+ over_the_wire = getattr(ModelHubRemoteService, name, None)
+ if not inspect.iscoroutinefunction(over_the_wire) or inspect.iscoroutinefunction(attribute):
+ return attribute
+
+ async def awaited(*args, **kwargs):
+ return attribute(*args, **kwargs)
+
+ return awaited
+
+ return UIClientShape()
+
+
def test_api_response_registry_exactly_covers_contract_and_server_routes():
api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")
documented = {
@@ -687,7 +716,7 @@ def test_every_model_hub_endpoint_returns_its_contract_response(
monkeypatch.setenv("XDG_CONFIG_HOME", str(isolated_home / ".config"))
save_config(isolated_home)
service = _seed_response_conformance_service(tmp_path)
- monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))
client = app.test_client()
base_url = "http://127.0.0.1:15131"
request_kwargs = {
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 34956e0c8..4e3d78d15 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -6579,8 +6579,10 @@ def test_a_burst_of_metering_neither_borrows_the_shared_pool_nor_grows_unbounded
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]
+ # up behind the first, which is the whole of the bound. It carries one row
+ # rather than seven, because the seven were headed for one row anyway; the
+ # requests below are what proves that folded and lost are different things.
+ assert transactions == [1, 1]
metered = _usage_of(service, source.id)
assert metered["requests"] == 8
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index d6a2dac47..4b0924343 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -43,7 +43,16 @@ PROVENANCE = ROOT / "core/handlers/model_hub/provenance.py"
ROUTER = ROOT / "modules/agents/model_hub.py"
ADAPTER = ROOT / "vibe/model_hub_runtime/adapter.py"
CLIENT = ROOT / "vibe/model_hub_runtime/client.py"
+HUB_CLIENT = ROOT / "vibe/model_hub_client.py"
+UI_SERVER = ROOT / "vibe/ui_server.py"
INVOKE_CONTRACT = ROOT / "core/handlers/model_hub/adapter.py"
+# Every name a caller reaches the usage ledger's read through. Two processes
+# forbid reaching it the easy way for one reason -- the read blocks on the lock
+# the writers hold across an fsync -- so the rule is declared once here instead
+# of restated in each loop's scan, where a second reader would escape both.
+LEDGER_READ_NAMES = frozenset({"usage_summary"})
+LEDGER_TOUCH_NAMES = LEDGER_READ_NAMES | {"usage"}
+PRODUCT_PACKAGES = ("core", "config", "modules", "vibe")
FIXTURES = Path(__file__).parent / "fixtures" / "model_hub"
STREAM_TRANSPORT_FIXTURES = json.loads((FIXTURES / "stream_transport_boundaries.json").read_text(encoding="utf-8"))[
"cases"
@@ -271,6 +280,22 @@ def _call_name(node: ast.AST) -> str | None:
return None
+def _parents(tree: ast.AST) -> dict[ast.AST, ast.AST]:
+ return {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
+
+
+def _reaches_the_ledger(node: ast.AST) -> bool:
+ # ``self.usage.<anything>`` -- the ledger object itself, not the writer beside
+ # it, which is a different property with a different rule.
+ return (
+ isinstance(node, ast.Attribute)
+ and isinstance(node.value, ast.Attribute)
+ and node.value.attr == "usage"
+ and isinstance(node.value.value, ast.Name)
+ and node.value.value.id == "self"
+ )
+
+
def _bool_keyword(call: ast.Call, name: str) -> bool | None:
return next(
(
@@ -676,12 +701,8 @@ def test_the_usage_ledger_is_never_touched_from_the_controller_loop() -> None:
# caller happened to remember it. Every RPC entry into it is checked here so
# the next one cannot quietly be the exception.
tree = _tree(RPC)
- parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
- touches = [
- node
- for node in ast.walk(tree)
- if isinstance(node, ast.Attribute) and node.attr in {"usage_summary", "usage"}
- ]
+ parents = _parents(tree)
+ touches = [node for node in ast.walk(tree) if isinstance(node, ast.Attribute) and node.attr in LEDGER_TOUCH_NAMES]
assert touches
for touch in touches:
enclosing = touch
@@ -694,6 +715,91 @@ def test_the_usage_ledger_is_never_touched_from_the_controller_loop() -> None:
assert off_loop, f"{touch.attr} is reached on the controller loop"
+def test_the_ledger_read_is_the_whole_of_what_both_loops_are_told_to_watch() -> None:
+ # Review 4966281026: two processes now scan for this read by name, and a
+ # second read added to the service would satisfy neither name list and so
+ # pass both scans. The list is therefore declared once and asserted here to
+ # be the whole of what the service exposes -- a new reader fails next to the
+ # declaration that has to grow with it, rather than in a review round.
+ readers = {
+ name for name, fn in _functions(_tree(SERVICE)).items() if any(map(_reaches_the_ledger, ast.walk(fn)))
+ }
+ assert readers == set(LEDGER_READ_NAMES)
+
+
+def test_the_ledger_read_reaches_the_web_ui_awaited_and_off_the_compat_surface() -> None:
+ # Review 4966281026 finding 4: the same property as the controller guard
+ # above, one process over. The read blocks on the writers' lock across an
+ # fsync, so reaching it from the compat surface -- whose handlers are sync and
+ # run in a threadpool worker -- occupies a UI worker for as long as the disk
+ # takes. Awaiting it on the native surface is what keeps that cost on the
+ # event loop's own terms.
+ tree = _tree(UI_SERVER)
+ parents = _parents(tree)
+ touches = [node for node in ast.walk(tree) if isinstance(node, ast.Attribute) and node.attr in LEDGER_TOUCH_NAMES]
+ assert touches
+ for touch in touches:
+ awaited = False
+ native = False
+ enclosing = touch
+ while enclosing in parents:
+ enclosing = parents[enclosing]
+ if isinstance(enclosing, ast.Await):
+ awaited = True
+ if isinstance(enclosing, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ assert isinstance(enclosing, ast.AsyncFunctionDef), f"{enclosing.name} reaches {touch.attr} sync"
+ native = native or any(
+ _call_name(node) == "_dispatch_native_ui_request" for node in ast.walk(enclosing)
+ )
+ assert awaited, f"{touch.attr} is called rather than awaited"
+ assert native, f"{touch.attr} is served off the native FastAPI surface"
+
+ # The client the route reaches it through has to keep the same shape: one sync
+ # method here would move the block back into a worker with nothing in
+ # `ui_server.py` to show for it.
+ for name, fn in _functions(_tree(HUB_CLIENT)).items():
+ if name not in LEDGER_READ_NAMES:
+ continue
+ assert isinstance(fn, ast.AsyncFunctionDef), f"{name} is a sync RPC"
+ assert not any(_call_name(node) == "_rpc_sync" for node in ast.walk(fn))
+
+
+def test_a_usage_row_is_labelled_without_its_caller_knowing_how_it_was_keyed() -> None:
+ # Review 4966281026 finding 1: a row's key is an identity or a bounded head
+ # plus a digest of it, and which one is a fold only this module performs. Three
+ # heads running, the reviewer has found a caller keying its own lookup at a
+ # new call site each time -- so the class is closed by leaving no caller with
+ # a key to join on. The service hands identities down and the ledger keys both
+ # sides of the join itself.
+ importers = set()
+ for package in PRODUCT_PACKAGES:
+ for path in (ROOT / package).rglob("*.py"):
+ source = path.read_text(encoding="utf-8")
+ if "usage_ledger_key" not in source:
+ continue
+ if any(
+ isinstance(node, ast.ImportFrom) and any(alias.name == "usage_ledger_key" for alias in node.names)
+ for node in ast.walk(ast.parse(source))
+ ):
+ importers.add(path)
+ assert importers == {USAGE}
+
+ reader = _functions(_tree(SERVICE))["usage_summary"]
+ # Subscripting a row is how the fold leaked the first two times: the caller
+ # read `row["source_id"]` and looked a label up under an identity the row does
+ # not carry, reporting every folded row as unlabelled while it still existed.
+ assert not [
+ node
+ for node in ast.walk(reader)
+ if isinstance(node, ast.Subscript)
+ and isinstance(node.slice, ast.Constant)
+ and node.slice.value in {"source_id", "model_id", "sources", "models"}
+ ]
+ handoffs = [node for node in ast.walk(reader) if _call_name(node) == "summary"]
+ assert len(handoffs) == 1
+ assert {keyword.arg for keyword in handoffs[0].keywords} >= {"source_labels", "model_labels"}
+
+
def test_g4_terminal_projection_has_no_execution_channel() -> None:
# Adding ``supply_channel`` to a projection helper must fail this scan.
for path in (SERVICE, PROVENANCE, ROUTER):
diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.py
index 198da05fd..417c61485 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -12,10 +12,12 @@ settlement scaffolding it depends on.
from __future__ import annotations
+import asyncio
import json
import logging
import os
import stat
+import threading
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
@@ -40,6 +42,7 @@ from core.handlers.model_hub.stream_wire import (
from core.handlers.model_hub.usage import (
USAGE_RETENTION_DAYS,
BoundedUsageLedger,
+ UsageWriter,
local_usage_day,
)
@@ -1352,3 +1355,217 @@ def test_one_local_day_holds_moments_from_two_utc_days(tmp_path: Path) -> None:
assert len(rows) == 1
assert rows[0]["day"] == "2026-07-23"
assert rows[0]["requests"] == 2
+
+
+def _keying_populations(prefix: str) -> tuple[str, ...]:
+ """One identity from each population `usage_ledger_key` can put a key in.
+
+ A key is either the identity itself or a bounded head plus a digest of it, and
+ which one depends on a length no caller of the ledger is asked about. Naming
+ the populations here rather than a list of interesting strings is what makes a
+ join test cover the fold without enumerating it.
+ """
+
+ def padded(length: int) -> str:
+ return f"{prefix}{'a' * (length - len(prefix))}"
+
+ return (
+ padded(len(prefix) + 8),
+ padded(MODEL_ID_MAX_LENGTH),
+ padded(MODEL_ID_MAX_LENGTH + 1),
+ padded(USAGE_LEDGER_KEY_MAX_LENGTH * 2),
+ )
+
+
+def test_a_label_reaches_the_row_of_every_identity_the_ledger_can_key(tmp_path: Path) -> None:
+ """MH-USAGE-008, review 4966281026: a join is keyed the way its rows were.
+
+ A label arrives as an identity and a row carries a key, and only this module
+ knows that those differ. The version of the read that took an already-keyed
+ mapping is what the rule looks like once it has leaked to a caller: the caller
+ keyed its own map, looked a label up by `row["source_id"]`, and every identity
+ the fold exists for silently reported no label at all while still existing —
+ and never showed a rename either.
+
+ Stated over the populations a key can be in rather than over the pair that
+ exposed it, so an identity shape that becomes reachable later is covered here
+ the moment it exists. The source IDs are `src_`-prefixed because config admits
+ `src_[a-z0-9]{8,}` with no upper bound, so a folded Source key is reachable
+ from a config that validates, not only from a legacy file.
+ """
+
+ sources = _keying_populations("src_")
+ models = _keying_populations("model-")
+ # The test is only the test while the seeds span both populations: an all-verbatim
+ # set would pass against a read that never keyed anything.
+ assert {identity == usage_ledger_key(identity) for identity in (*sources, *models)} == {
+ True,
+ False,
+ }
+
+ ledger = _ledger(tmp_path)
+ for source_id in sources:
+ for model_id in models:
+ ledger.record(source_id=source_id, model_id=model_id, usage=None, at=NOW)
+
+ def summarize(naming: str) -> dict:
+ return ledger.summary(
+ days=30,
+ now=NOW,
+ source_labels={identity: f"{naming} {identity}" for identity in sources},
+ # A model's label is its own identity: a folded row publishes a head
+ # plus a digest, so a tab drawing `model_id` would show a string
+ # nobody typed.
+ model_labels={identity: identity for identity in models},
+ )
+
+ for naming in ("named", "renamed"):
+ by_source = {source["source_id"]: source for source in summarize(naming)["sources"]}
+ assert set(by_source) == {usage_ledger_key(identity) for identity in sources}
+ for source_id in sources:
+ source = by_source[usage_ledger_key(source_id)]
+ assert source["label"] == f"{naming} {source_id}"
+ by_model = {model["model_id"]: model for model in source["models"]}
+ assert set(by_model) == {usage_ledger_key(identity) for identity in models}
+ for model_id in models:
+ assert by_model[usage_ledger_key(model_id)]["label"] == model_id
+
+
+def test_a_label_no_config_still_holds_is_absent_rather_than_stale(tmp_path: Path) -> None:
+ """MH-USAGE-008: the join is why a deleted Source reads as deleted.
+
+ Persisting the label would freeze a copy of user-supplied text in a file this
+ ledger keeps for two months. Joining it means a row whose identity config no
+ longer holds publishes no label — which is the honest reading, since the usage
+ happened and the thing that produced it is gone.
+ """
+
+ ledger = _ledger(tmp_path)
+ ledger.record(source_id="src_gone0001", model_id="model-gone", usage=None, at=NOW)
+
+ source = ledger.summary(days=30, now=NOW, source_labels={}, model_labels={})["sources"][0]
+
+ assert source["label"] is None
+ assert source["models"][0]["label"] is None
+
+
+# --- Ownership: one queue, bounded by identity, loud when it loses a batch -----
+
+
+def test_the_write_queue_is_bounded_by_identities_not_by_arrival_rate(tmp_path: Path) -> None:
+ """MH-USAGE-009, review 4966281026: a backlog bound traffic cannot move.
+
+ The queue exists so a served turn never waits on a disk, which means whatever
+ arrives while a flush is out has to go somewhere. Bounding it by a capacity
+ would mean choosing rows to drop — losing exactly the billed usage this module
+ exists to keep — and blocking the caller would stall a turn on a disk that is
+ already failing. So it folds: calls heading for one row become one queued row
+ as they arrive, and the backlog is bounded by the identities config holds
+ rather than by how hard the hub is driven.
+
+ Driven with the flush held open, because that is the only window in which a
+ backlog exists at all. 512 calls over four identities leave four queued rows,
+ and all 512 are still metered — a bound that dropped calls would pass the
+ first assertion and fail the last.
+ """
+
+ async def exercise() -> None:
+ ledger = _ledger(tmp_path)
+ writer = UsageWriter(ledger)
+ identities = (
+ ("src_a", "model-x"),
+ ("src_a", "model-y"),
+ ("src_b", "model-x"),
+ ("src_b", "model-y"),
+ )
+ fold = ledger.record_many
+ batches: list[int] = []
+ holding = threading.Event()
+ release = threading.Event()
+
+ def counting(calls) -> None:
+ batches.append(len(calls))
+ if len(batches) == 1:
+ holding.set()
+ assert release.wait(5)
+ fold(calls)
+
+ ledger.record_many = counting
+
+ # One call opens a flush and holds it on the writing thread; everything
+ # below therefore arrives while a write is out, which is the scenario.
+ writer.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
+ while not holding.is_set():
+ await asyncio.sleep(0.01)
+
+ for index in range(512):
+ source_id, model_id = identities[index % len(identities)]
+ writer.record(
+ source_id=source_id,
+ model_id=model_id,
+ usage=ProtocolUsageReport(input_tokens=1, output_tokens=1),
+ at=NOW,
+ )
+
+ assert len(writer._pending) == len(identities)
+ # Calls, not rows: a backlog must not look like it shrank because the hub
+ # got busier.
+ assert writer.unpersisted == 512 + 1
+ release.set()
+
+ assert await writer.drain(timeout=5) == 0
+ # One transaction for the held call, one for every call behind it.
+ assert batches == [1, len(identities)]
+
+ totals = ledger.summary(days=1, now=NOW)["totals"]
+ assert totals["requests"] == 512 + 1
+ assert totals["token_reports"] == 512
+ assert totals["input_tokens"] == 512
+ assert totals["output_tokens"] == 512
+
+ asyncio.run(exercise())
+
+
+def test_a_ledger_that_cannot_be_written_is_reported_once_per_outage(
+ tmp_path: Path, caplog: pytest.LogCaptureFixture
+) -> None:
+ """MH-USAGE-009: metering that stopped must not look like a hub with nothing to say.
+
+ A failed batch is lost by design — a ledger that cannot be reached must not
+ hold up the turns it meters — but a read-only state directory then reads
+ exactly like an idle hub, which is the one reading that makes this module's
+ absence invisible. Both edges of the outage are logged and nothing in between,
+ so the volume follows how often the ledger changes state rather than how long
+ it stays broken.
+ """
+
+ async def exercise() -> None:
+ ledger = _ledger(tmp_path)
+ writer = UsageWriter(ledger)
+ fold = ledger.record_many
+ broken = True
+
+ def refuse(calls) -> None:
+ if broken:
+ raise OSError("read-only file system")
+ fold(calls)
+
+ ledger.record_many = refuse
+
+ with caplog.at_level(logging.WARNING, logger="core.handlers.model_hub.usage"):
+ for attempt in range(3):
+ await writer.record(
+ source_id="src_a", model_id=f"model-{attempt}", usage=None, at=NOW
+ )
+ outage = [record.getMessage() for record in caplog.records]
+
+ broken = False
+ await writer.record(source_id="src_a", model_id="model-back", usage=None, at=NOW)
+ recovery = [record.getMessage() for record in caplog.records][len(outage) :]
+
+ assert len(outage) == 1 and "dropping metered calls" in outage[0]
+ assert len(recovery) == 1 and "recovered" in recovery[0]
+ # The three lost batches really were lost; only the recovered one landed.
+ assert ledger.summary(days=1, now=NOW)["totals"]["requests"] == 1
+
+ asyncio.run(exercise())
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 669dba5b3..0d4830e83 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -370,6 +370,41 @@ def test_thread_settings_routes_use_native_fastapi(monkeypatch):
assert deleted_scopes == [("telegram", "-1001", "42")]
+def test_the_usage_read_is_served_natively_rather_than_from_a_compat_worker(monkeypatch):
+ """Review 4966281026 finding 4: this read blocks, so where it is served matters.
+
+ Summarising the ledger takes the lock its writers hold across an fsync. The
+ compat surface hands a sync handler to a threadpool worker, so serving it
+ there occupies a UI worker for as long as the disk takes — while the native
+ surface awaits it on the loop, which is what the async client below exists
+ for. `ui_compat` names its endpoints `<name>_compat_endpoint`, so the route
+ table is where the two are told apart.
+ """
+
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+ asked: list[int] = []
+
+ class LedgerClient:
+ async def usage_summary(self, *, days: int) -> dict:
+ asked.append(days)
+ return {"window_days": days}
+
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: LedgerClient())
+
+ route = next(
+ route
+ for route in app.routes
+ if getattr(route, "path", None) == "/api/models/usage" and "GET" in route.methods
+ )
+ assert route.endpoint.__name__ == "model_hub_usage_get"
+
+ response = app.test_client().get("/api/models/usage?days=7")
+
+ assert response.status_code == 200
+ assert response.get_json()["usage"] == {"window_days": 7}
+ assert asked == [7]
+
+
def test_scope_settings_routes_report_localized_stale_agent_binding_conflicts(monkeypatch):
from core.services import settings as settings_service
from storage.settings_service import StaleScopeAgentBindingError
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 23dd43995..b56123113 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -207,8 +207,11 @@ class ModelHubRemoteService:
def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
return _rpc_sync("list_events", {"limit": limit, "before": before})
- def usage_summary(self, *, days: int = USAGE_DEFAULT_WINDOW_DAYS) -> dict:
- return _rpc_sync("usage_summary", {"days": days})
+ async def usage_summary(self, *, days: int = USAGE_DEFAULT_WINDOW_DAYS) -> dict:
+ # Async, unlike the other reads here: this one blocks on the lock the
+ # ledger's writers hold across an fsync, so a sync call would hold a UI
+ # worker for as long as the disk takes. See `usage.BoundedUsageLedger`.
+ return await _rpc("usage_summary", {"days": days})
def agent_chain(self, backend: str, model_id: str) -> dict:
return _rpc_sync(
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 1243160c1..9be18cd54 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4465,20 +4465,28 @@ def model_hub_events_get():
return _model_hub_error(exc)
[email protected]("/api/models/usage", methods=["GET"])
-def model_hub_usage_get():
- from core.handlers.model_hub import ModelHubError
- from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS
[email protected]("/api/models/usage", include_in_schema=False)
+async def model_hub_usage_get(starlette_request: FastAPIRequest):
+ # Native rather than on the compat surface, and awaited rather than called:
+ # this read blocks on the lock the usage ledger's writers hold across an
+ # fsync, so reaching it from a threadpool worker would occupy that worker for
+ # as long as the disk takes. The controller side of the same rule is in
+ # `rpc.py`, which keeps the read off the event loop there.
+ async def handler():
+ from core.handlers.model_hub import ModelHubError
+ from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS
- try:
- days = int(request.args.get("days") or USAGE_DEFAULT_WINDOW_DAYS)
- except (TypeError, ValueError):
- days = USAGE_DEFAULT_WINDOW_DAYS
- try:
- usage = _model_hub_service().usage_summary(days=days)
- return _model_hub_success(usage=usage)
- except ModelHubError as exc:
- return _model_hub_error(exc)
+ try:
+ days = int(starlette_request.query_params.get("days") or USAGE_DEFAULT_WINDOW_DAYS)
+ except (TypeError, ValueError):
+ days = USAGE_DEFAULT_WINDOW_DAYS
+ try:
+ usage = await _model_hub_service().usage_summary(days=days)
+ return _model_hub_success(usage=usage)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
@app.route("/api/models/agents/<backend>/chain", methods=["GET"])