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.

feat(model-hub): meter token usage from proxied turns

cyh847d681d7b3a
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index cf8d40e93..96d619424 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -6,6 +6,7 @@ import asyncio
from typing import Any
from .service import ModelHubError, ModelHubService
+from .usage import USAGE_DEFAULT_WINDOW_DAYS
async def _refresh_agent_presence(service: ModelHubService) -> None:
@@ -95,6 +96,8 @@ async def dispatch_model_hub_rpc(
)
if operation == "list_events":
return service.list_events(limit=payload.get("limit", 20), before=payload.get("before"))
+ if operation == "usage_summary":
+ return service.usage_summary(days=payload.get("days", USAGE_DEFAULT_WINDOW_DAYS))
if operation == "get_agent_chain":
return service.agent_chain(payload.get("backend"), payload.get("model_id"))
if operation == "probe_agent":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index c3c5d9144..6cca0d8be 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -110,6 +110,7 @@ from .resolver import (
source_runnable,
)
from .revocations import CredentialRevocationJournal
+from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger
CONTRACT_VERSION = 5
AGENT_CHAIN_CONTRACT_VERSION = 5
@@ -569,6 +570,7 @@ class ModelHubService:
adapter: EngineAdapter,
events: BoundedEventLog,
provenance: Optional[BoundedProvenanceStore] = None,
+ usage: Optional[BoundedUsageLedger] = None,
native_oauth_adapter: Optional[NativeOAuthAdapter] = None,
oauth_flows: Optional[OAuthFlowRegistry] = None,
revocations: Optional[CredentialRevocationJournal] = None,
@@ -589,6 +591,9 @@ class ModelHubService:
self.provenance = provenance or BoundedProvenanceStore(
paths.get_state_dir() / "model_hub_turn_provenance.json"
)
+ self.usage = usage or BoundedUsageLedger(
+ paths.get_state_dir() / "model_hub_usage.json"
+ )
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",
@@ -3601,6 +3606,20 @@ class ModelHubService:
"interrupted": would_interrupt,
}
+ 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.
+ """
+
+ 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
+
def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
events = self.events.list(limit=limit, before=before)
for event in events:
@@ -5297,6 +5316,7 @@ def create_default_service(
store=V2ModelHubConfigStore(),
adapter=adapter,
events=BoundedEventLog(paths.get_state_dir() / "model_hub_resolution_events.json"),
+ usage=BoundedUsageLedger(paths.get_state_dir() / "model_hub_usage.json"),
native_oauth_adapter=native_oauth_adapter,
oauth_flows=OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json"),
revocations=CredentialRevocationJournal(paths.get_state_dir() / "model_hub_pending_revocations.json"),
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index 862e62d08..154aaf61b 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -147,6 +147,30 @@ ProtocolObservationOutcome = Literal["served", "failed_terminal", "protocol_erro
ErrorEnvelopePath = tuple[str, ...]
+# Token counts are vendor-reported, never self-measured, so one hostile or buggy
+# response must not be able to poison a persisted aggregate. The ceiling is fixed
+# in our code; it is never derived from a value the upstream declares.
+USAGE_TOKEN_CEILING: Final = 1_000_000_000
+
+
+@dataclass(frozen=True)
+class ProtocolUsageReport:
+ """One protocol-normalized token report observed on the wire."""
+
+ input_tokens: int = 0
+ cached_input_tokens: int = 0
+ output_tokens: int = 0
+
+ def merge(self, other: "ProtocolUsageReport") -> "ProtocolUsageReport":
+ """Combine two reports for the same turn by taking the larger of each."""
+
+ return ProtocolUsageReport(
+ input_tokens=max(self.input_tokens, other.input_tokens),
+ cached_input_tokens=max(self.cached_input_tokens, other.cached_input_tokens),
+ output_tokens=max(self.output_tokens, other.output_tokens),
+ )
+
+
@dataclass(frozen=True)
class ProtocolObservation:
outcome: ProtocolObservationOutcome | None = None
@@ -155,6 +179,7 @@ class ProtocolObservation:
error_envelope_paths: tuple[ErrorEnvelopePath, ...] = ()
sequence_number: int | None = None
message: str | None = None
+ usage: ProtocolUsageReport | None = None
@dataclass(frozen=True)
@@ -176,6 +201,23 @@ class ProtocolModelOutputEnvelope:
require_nonempty: bool = False
+@dataclass(frozen=True)
+class ProtocolUsageTaxonomy:
+ """Declare where one protocol reports token usage and how to compose it.
+
+ Leaf paths are relative to a container. Values found under the leaves of one
+ logical field are summed within a single container, because a protocol may
+ split one quantity across sibling members; candidates from different
+ containers are then merged by taking the larger, because protocols repeat a
+ cumulative report across frames.
+ """
+
+ container_paths: tuple[tuple[str, ...], ...]
+ input_paths: tuple[tuple[str, ...], ...]
+ cached_input_paths: tuple[tuple[str, ...], ...]
+ output_paths: tuple[tuple[str, ...], ...]
+
+
@dataclass(frozen=True)
class ProtocolStreamTaxonomy:
terminal_envelopes: tuple[ProtocolTerminalEnvelope, ...]
@@ -185,6 +227,7 @@ class ProtocolStreamTaxonomy:
buffered_error_envelope_paths: tuple[ErrorEnvelopePath, ...]
terminal_event_name: str | None
render_terminal_event: Callable[[str, str, int], dict[str, object]]
+ usage: ProtocolUsageTaxonomy
PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {
@@ -225,6 +268,23 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {
buffered_error_envelope_paths=(("error",),),
terminal_event_name="error",
render_terminal_event=_anthropic_terminal_event,
+ usage=ProtocolUsageTaxonomy(
+ # https://platform.claude.com/docs/en/build-with-claude/streaming
+ # message_start nests the report under `message`; message_delta and
+ # buffered responses report it at the top level.
+ container_paths=(("message", "usage"), ("usage",)),
+ # https://platform.claude.com/docs/en/docs/build-with-claude/prompt-caching
+ # `input_tokens` excludes both cache members, so the input total is
+ # their sum. Only cache reads are input served from cache; cache
+ # creation is fresh input that was also written to the cache.
+ input_paths=(
+ ("input_tokens",),
+ ("cache_read_input_tokens",),
+ ("cache_creation_input_tokens",),
+ ),
+ cached_input_paths=(("cache_read_input_tokens",),),
+ output_paths=(("output_tokens",),),
+ ),
),
"openai_responses": ProtocolStreamTaxonomy(
terminal_envelopes=(
@@ -302,6 +362,17 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {
buffered_error_envelope_paths=(("error",),),
terminal_event_name="error",
render_terminal_event=_responses_terminal_event,
+ usage=ProtocolUsageTaxonomy(
+ # https://platform.openai.com/docs/api-reference/responses/object#responses/object-usage
+ # Terminal response events nest the completed response; buffered
+ # responses are that object.
+ container_paths=(("response", "usage"), ("usage",)),
+ # `input_tokens` already includes cached input, so the cached count
+ # is an informational subset and never an addend.
+ input_paths=(("input_tokens",),),
+ cached_input_paths=(("input_tokens_details", "cached_tokens"),),
+ output_paths=(("output_tokens",),),
+ ),
),
"openai_chat": ProtocolStreamTaxonomy(
terminal_envelopes=(
@@ -352,6 +423,15 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {
buffered_error_envelope_paths=(("error",),),
terminal_event_name=None,
render_terminal_event=_chat_terminal_event,
+ usage=ProtocolUsageTaxonomy(
+ # https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage
+ # Streaming chat reports usage only when the client asked for it via
+ # `stream_options.include_usage`, on a dedicated final chunk.
+ container_paths=(("usage",),),
+ input_paths=(("prompt_tokens",),),
+ cached_input_paths=(("prompt_tokens_details", "cached_tokens"),),
+ output_paths=(("completion_tokens",),),
+ ),
),
}
@@ -405,6 +485,48 @@ def is_protocol_model_output(
)
+def _usage_sum(container: Mapping[str, object], paths: tuple[tuple[str, ...], ...]) -> int | None:
+ """Sum one logical field's leaves, rejecting anything not a bounded count."""
+
+ total: int | None = None
+ for path in paths:
+ for value in _path_values(container, path):
+ if not isinstance(value, int) or isinstance(value, bool):
+ continue
+ if value < 0 or value > USAGE_TOKEN_CEILING:
+ continue
+ total = value if total is None else total + value
+ if total is None:
+ return None
+ return min(total, USAGE_TOKEN_CEILING)
+
+
+def extract_protocol_usage(
+ protocol: str,
+ payload: Mapping[str, object],
+) -> ProtocolUsageReport | None:
+ """Read one document's token report, or None when it carries none."""
+
+ taxonomy = PROTOCOL_STREAM_TAXONOMY[protocol].usage
+ report: ProtocolUsageReport | None = None
+ for container_path in taxonomy.container_paths:
+ for container in _path_values(payload, container_path):
+ if not isinstance(container, Mapping):
+ continue
+ input_tokens = _usage_sum(container, taxonomy.input_paths)
+ cached_input_tokens = _usage_sum(container, taxonomy.cached_input_paths)
+ output_tokens = _usage_sum(container, taxonomy.output_paths)
+ if input_tokens is None and cached_input_tokens is None and output_tokens is None:
+ continue
+ candidate = ProtocolUsageReport(
+ input_tokens=input_tokens or 0,
+ cached_input_tokens=cached_input_tokens or 0,
+ output_tokens=output_tokens or 0,
+ )
+ report = candidate if report is None else report.merge(candidate)
+ return report
+
+
def _try_parse_payload(data: bytes) -> object | None:
"""Parse untrusted observation data without leaking parser failures."""
@@ -433,6 +555,8 @@ def observe_protocol_response(
if not isinstance(payload, dict):
return ProtocolObservation(outcome="served" if not streamed else None)
+ usage = extract_protocol_usage(protocol, payload)
+
if not streamed:
if any(
isinstance(value, Mapping)
@@ -443,8 +567,9 @@ def observe_protocol_response(
outcome="failed_terminal",
error_payload=data,
error_envelope_paths=taxonomy.buffered_error_envelope_paths,
+ usage=usage,
)
- return ProtocolObservation(outcome="served")
+ return ProtocolObservation(outcome="served", usage=usage)
sequence_number: int | None = None
if taxonomy.sequence_number_path is not None:
@@ -480,10 +605,12 @@ def observe_protocol_response(
envelope.error_envelope_paths if envelope.terminal_outcome == "failed_terminal" else ()
),
sequence_number=sequence_number,
+ usage=usage,
)
return ProtocolObservation(
model_output_started=model_output_started,
sequence_number=sequence_number,
+ usage=usage,
)
@@ -498,6 +625,7 @@ class ProtocolSSEState:
error_envelope_paths: tuple[ErrorEnvelopePath, ...] = ()
last_sequence_number: int = -1
model_output_started: bool = False
+ usage: ProtocolUsageReport | None = None
def observe(self, chunk: bytes) -> None:
for frame in self.tokenizer.feed(chunk):
@@ -529,6 +657,10 @@ class ProtocolSSEState:
)
if observation.model_output_started:
self.model_output_started = True
+ if observation.usage is not None:
+ self.usage = (
+ observation.usage if self.usage is None else self.usage.merge(observation.usage)
+ )
if observation.outcome in {"served", "failed_terminal"}:
self.terminal_outcome = observation.outcome
if observation.error_payload is not None:
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 721f30825..0cc6e2f4d 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -10,6 +10,7 @@ from collections import deque
from collections.abc import Callable
from contextlib import AsyncExitStack, suppress
from dataclasses import dataclass
+from datetime import datetime, timezone
from typing import Final, Optional
from aiohttp import web
@@ -37,10 +38,13 @@ from .provenance import (
from .request import ModelHubRequest
from .stream_wire import (
ProtocolSSEState,
+ ProtocolUsageReport,
StreamTerminalOutcome,
+ observe_protocol_response,
render_protocol_terminal_event,
render_protocol_terminal_frame,
)
+from .usage import BoundedUsageLedger
from .service import (
HandleSettlement,
HandleTerminationOrigin,
@@ -66,6 +70,10 @@ _REQUEST_PROTOCOLS: Final = {
logger = logging.getLogger(__name__)
+def _gateway_utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
_PROTOCOL_HEADERS: Final = frozenset(
{
"anthropic-beta",
@@ -110,12 +118,17 @@ class ModelHubTurnGateway:
service: ModelHubService,
*,
correlation: Optional[TurnCorrelationRegistry] = None,
+ usage: Optional[BoundedUsageLedger] = None,
language_provider: Callable[[], str] | None = None,
transport_timeout: float = ENGINE_TRANSPORT_TIMEOUT_SECONDS,
+ now: Callable[[], datetime] | None = None,
) -> None:
self.service = service
self._language_provider = language_provider or (lambda: "en")
self._transport_timeout = transport_timeout
+ # One clock per hub: the service already owns it, so a test that fixes the
+ # service clock gets deterministic usage days without a second injection.
+ self._now = now or getattr(service, "now", None) or _gateway_utc_now
self._resource_leak_records: deque[tuple[str, str | None]] = deque(maxlen=100)
self.correlation = correlation or TurnCorrelationRegistry(
getattr(
@@ -124,6 +137,11 @@ class ModelHubTurnGateway:
BoundedProvenanceStore(paths.get_state_dir() / "model_hub_turn_provenance.json"),
)
)
+ self.usage = (
+ usage
+ or getattr(service, "usage", None)
+ or BoundedUsageLedger(paths.get_state_dir() / "model_hub_usage.json")
+ )
self._start_lock = asyncio.Lock()
self._runner: web.AppRunner | None = None
self._site: web.SockSite | None = None
@@ -571,6 +589,16 @@ class ModelHubTurnGateway:
)
assert outcome is not None
assert settlement.decision is not None
+ buffered_usage = observe_protocol_response(
+ protocol,
+ streamed=False,
+ data=bytes(payload),
+ ).usage
+ self._record_usage(
+ resolved,
+ usage=buffered_usage,
+ served=settlement.decision.action == "return",
+ )
if settlement.decision.action != "return":
return self._outcome_response(
outcome,
@@ -612,6 +640,11 @@ class ModelHubTurnGateway:
terminalizer,
settlement,
)
+ self._record_usage(
+ resolved,
+ usage=wire_state.usage,
+ served=wire_state.terminal_outcome == "served",
+ )
await self._write_stream_terminal_copy(
response,
protocol,
@@ -622,6 +655,38 @@ class ModelHubTurnGateway:
await self._downstream_io(response.write_eof())
return response
+ def _record_usage(
+ self,
+ resolved: ResolvedInvocation,
+ *,
+ usage: ProtocolUsageReport | None,
+ served: bool,
+ ) -> None:
+ """Fold one proxied turn into the usage ledger, best-effort.
+
+ A turn counts when it reached the model: either the hub returned upstream
+ output downstream, or upstream reported usage for it — a vendor that
+ reported tokens billed us even when the stream ended in an error. Turns
+ that never reached the model already have their own surface in the
+ resolution feed and source health, so counting them here would duplicate
+ that concept.
+
+ Metering is a report, never a control input, so a ledger failure must not
+ change the turn the caller sees.
+ """
+
+ if not served and usage is None:
+ return
+ try:
+ self.usage.record(
+ source_id=resolved.source_id,
+ model_id=resolved.model_id,
+ usage=usage,
+ at=self._now(),
+ )
+ except (OSError, ValueError) as exc:
+ logger.debug("Model Hub usage metering skipped one turn: %s", exc)
+
async def _write_stream_terminal_copy(
self,
response: web.StreamResponse,
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
new file mode 100644
index 000000000..4670a5cec
--- /dev/null
+++ b/core/handlers/model_hub/usage.py
@@ -0,0 +1,290 @@
+"""Bounded, credential-free persistence for Model Hub token usage.
+
+The turn gateway is the only place in the product that sees a complete upstream
+model response, so it is the only place that can count tokens. This module owns
+what happens to those counts afterwards: one bounded daily aggregate per served
+source and model, and the read shape the settings page consumes.
+
+Two properties are deliberate. `requests` is self-measured by our own code and is
+always available; token counts are vendor-reported and may be absent, which is
+why `token_reports` is tracked separately instead of treating a missing report as
+zero usage. And nothing here ever feeds admission, routing, or cooldown — a
+hostile upstream must not be able to change resolution behavior by lying about
+usage.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+import threading
+from datetime import date, datetime, timedelta
+from pathlib import Path
+from typing import Final, Optional
+
+from .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReport
+
+# Roughly two months of daily rows: long enough for a monthly view plus the
+# previous cycle, short enough that the file stays small on a busy machine.
+USAGE_RETENTION_DAYS: Final = 62
+USAGE_MAX_ROWS: Final = 400
+USAGE_DEFAULT_WINDOW_DAYS: Final = 30
+# Source and model identifiers are already bounded by their own validators; this
+# is the persistence-side backstop that keeps one row from growing without limit.
+_MAX_IDENTIFIER_LENGTH: Final = 200
+
+_COUNTER_KEYS: Final = (
+ "requests",
+ "token_reports",
+ "input_tokens",
+ "cached_input_tokens",
+ "output_tokens",
+)
+
+
+def local_usage_day(moment: datetime) -> date:
+ """Bucket one moment into a local-calendar day.
+
+ Avibe is local-first and the settings page already presents local days, so a
+ day boundary here is the user's midnight, not UTC's.
+ """
+
+ return moment.astimezone().date()
+
+
+def _bounded_counter(value: object) -> int:
+ """Read one persisted counter, degrading anything unusable to zero."""
+
+ if not isinstance(value, int) or isinstance(value, bool):
+ return 0
+ if value < 0:
+ return 0
+ return min(value, USAGE_TOKEN_CEILING)
+
+
+def _identifier(value: object) -> Optional[str]:
+ if not isinstance(value, str):
+ return None
+ trimmed = value.strip()
+ if not trimmed or len(trimmed) > _MAX_IDENTIFIER_LENGTH:
+ return None
+ return trimmed
+
+
+def _normalize_row(row: object) -> Optional[dict]:
+ """Project one persisted row onto the current shape, or drop it."""
+
+ if not isinstance(row, dict):
+ return None
+ day = _identifier(row.get("day"))
+ source_id = _identifier(row.get("source_id"))
+ model_id = _identifier(row.get("model_id"))
+ if day is None or source_id is None or model_id is None:
+ return None
+ try:
+ date.fromisoformat(day)
+ except ValueError:
+ return None
+ normalized = {
+ "day": day,
+ "source_id": source_id,
+ "model_id": model_id,
+ **{key: _bounded_counter(row.get(key)) for key in _COUNTER_KEYS},
+ }
+ last_served_at = _identifier(row.get("last_served_at"))
+ normalized["last_served_at"] = last_served_at
+ return normalized
+
+
+def _row_key(row: dict) -> tuple[str, str, str]:
+ return (row["day"], row["source_id"], row["model_id"])
+
+
+def _empty_totals() -> dict:
+ return {key: 0 for key in _COUNTER_KEYS}
+
+
+def _accumulate(target: dict, row: dict) -> None:
+ for key in _COUNTER_KEYS:
+ target[key] = min(target[key] + row[key], USAGE_TOKEN_CEILING)
+
+
+def _newer_timestamp(current: Optional[str], candidate: Optional[str]) -> Optional[str]:
+ if candidate is None:
+ return current
+ if current is None:
+ return candidate
+ return max(current, candidate)
+
+
+class BoundedUsageLedger:
+ """Persist served-turn token counts as a bounded daily aggregate."""
+
+ def __init__(
+ self,
+ path: Path,
+ *,
+ max_rows: int = USAGE_MAX_ROWS,
+ retention_days: int = USAGE_RETENTION_DAYS,
+ ):
+ self.path = path
+ self.max_rows = max_rows
+ self.retention_days = retention_days
+ self._lock = threading.RLock()
+
+ def _read(self) -> list[dict]:
+ if not self.path.exists():
+ return []
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return []
+ if not isinstance(payload, list):
+ return []
+ rows: dict[tuple[str, str, str], dict] = {}
+ for item in payload:
+ row = _normalize_row(item)
+ if row is None:
+ continue
+ existing = rows.get(_row_key(row))
+ if existing is None:
+ rows[_row_key(row)] = row
+ continue
+ _accumulate(existing, row)
+ existing["last_served_at"] = _newer_timestamp(
+ existing["last_served_at"],
+ row["last_served_at"],
+ )
+ return sorted(rows.values(), key=_row_key)
+
+ def _write(self, rows: list[dict]) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ content = json.dumps(
+ sorted(rows, key=_row_key)[-self.max_rows :],
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ dir=self.path.parent,
+ delete=False,
+ ) as tmp:
+ tmp.write(content)
+ tmp.flush()
+ os.fsync(tmp.fileno())
+ temp_name = tmp.name
+ os.chmod(temp_name, 0o600)
+ os.replace(temp_name, self.path)
+
+ def record(
+ self,
+ *,
+ source_id: str,
+ model_id: str,
+ usage: Optional[ProtocolUsageReport],
+ at: datetime,
+ ) -> None:
+ """Fold one served turn into its day's row."""
+
+ safe_source_id = _identifier(source_id)
+ safe_model_id = _identifier(model_id)
+ if safe_source_id is None or safe_model_id is None:
+ return
+ increment = {
+ "day": local_usage_day(at).isoformat(),
+ "source_id": safe_source_id,
+ "model_id": safe_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_served_at": at.isoformat(),
+ }
+ with self._lock:
+ rows = {_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_served_at"] = _newer_timestamp(
+ existing["last_served_at"],
+ increment["last_served_at"],
+ )
+ retained = self._retained(list(rows.values()), local_usage_day(at))
+ self._write(retained)
+
+ def _retained(self, rows: list[dict], today: date) -> list[dict]:
+ oldest = (today - timedelta(days=self.retention_days - 1)).isoformat()
+ return [row for row in rows if row["day"] >= oldest]
+
+ def window(self, *, days: int, now: datetime) -> list[dict]:
+ """Return the rows inside the trailing local-day window, oldest first."""
+
+ bounded_days = max(1, min(int(days), self.retention_days))
+ today = local_usage_day(now)
+ first_day = (today - timedelta(days=bounded_days - 1)).isoformat()
+ last_day = today.isoformat()
+ with self._lock:
+ 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."""
+
+ bounded_days = max(1, min(int(days), self.retention_days))
+ today = local_usage_day(now)
+ rows = self.window(days=bounded_days, now=now)
+
+ totals = _empty_totals()
+ sources: dict[str, dict] = {}
+ by_day: dict[str, dict] = {}
+ for row in rows:
+ _accumulate(totals, row)
+
+ source = sources.setdefault(
+ row["source_id"],
+ {
+ "source_id": row["source_id"],
+ **_empty_totals(),
+ "last_served_at": None,
+ "models": {},
+ },
+ )
+ _accumulate(source, row)
+ source["last_served_at"] = _newer_timestamp(
+ source["last_served_at"],
+ row["last_served_at"],
+ )
+ model = source["models"].setdefault(
+ row["model_id"],
+ {"model_id": row["model_id"], **_empty_totals()},
+ )
+ _accumulate(model, row)
+
+ day = by_day.setdefault(row["day"], {"day": row["day"], **_empty_totals()})
+ _accumulate(day, row)
+
+ return {
+ "window_days": bounded_days,
+ "from_day": (today - timedelta(days=bounded_days - 1)).isoformat(),
+ "to_day": today.isoformat(),
+ "totals": totals,
+ "sources": [
+ {
+ **{key: value for key, value in source.items() if key != "models"},
+ "models": sorted(
+ source["models"].values(),
+ key=lambda model: (-model["requests"], model["model_id"]),
+ ),
+ }
+ for source in sorted(
+ sources.values(),
+ key=lambda source: (-source["requests"], source["source_id"]),
+ )
+ ],
+ "days": [by_day[day] for day in sorted(by_day)],
+ }
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 255a4b019..c76a0daae 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -26,6 +26,7 @@
{"method": "PUT", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {"hops": [{"source_id": "src_conform001", "model_id": "claude-opus-4-6"}]}}},
{"method": "POST", "path": "/api/models/agents/<backend>/probe", "response_schema": "ProbeResponse", "exercise": {"path": "/api/models/agents/claude/probe", "status": 200, "json": {"model": "claude-opus-4-6"}}},
{"method": "GET", "path": "/api/models/events?limit=<n>&before=<id>", "response_schema": "EventsResponse", "exercise": {"path": "/api/models/events?limit=20", "status": 200}},
+ {"method": "GET", "path": "/api/models/usage?days=<n>", "response_schema": "UsageResponse", "exercise": {"path": "/api/models/usage?days=30", "status": 200}},
{"method": "POST", "path": "/api/models/oauth/start", "response_schema": "OAuthFlowResponse", "exercise": {"path": "/api/models/oauth/start", "status": 200, "json": {"vendor": "anthropic", "channel": "hub"}}},
{"method": "GET", "path": "/api/models/oauth/status/<flow_id>", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/status/oaf_00000001", "status": 200}},
{"method": "POST", "path": "/api/models/oauth/submit", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/submit", "status": 200, "json": {"flow_id": "oaf_00000001", "value": "contract-code"}}},
@@ -263,6 +264,16 @@
"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}
}
},
+ "UsageResponse": {
+ "type": "object",
+ "required": ["ok", "contract_version", "usage"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": true},
+ "contract_version": {"const": 5},
+ "usage": {"$ref": "model-hub/usage-summary.schema.json"}
+ }
+ },
"OAuthFlowResponse": {
"type": "object",
"required": ["ok", "contract_version", "flow"],
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index e384dc495..10e6ad6cb 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -44,6 +44,7 @@ Hub has not shipped, so there is no internal contract migration or compatibility
| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; the handler never reads `sources.order`, and the submitted `hops` carry no Source-order semantics. It is the `mutation.route_replace` row of the authoritative mutation matrix. A visible noninterrupting hop removal is ordinary success; only a resulting protected-supply interruption enters the guard. |
| POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. |
| GET `/api/models/events?limit=<n>&before=<id>` | → `{events: ResolutionEvent[]}` | Bounded source-resolution feed. |
+| GET `/api/models/usage?days=<n>` | → `{usage: UsageSummary}` | Bounded metered token report over a trailing local-day window. `days` is clamped to the retained window; a Source with no metered turn is absent rather than reported as zero. |
| POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. |
| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. |
| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. |
@@ -985,6 +986,30 @@ Model-scoped kinds require a string. `agent: system` is invalid on backend-scope
`supply_interrupted`. Source endpoints use canonical ids and are checked for existence
when emitted.
+## Usage metering
+
+Usage is a report, never a control input. Nothing in resolution, admission, or
+cooldown reads these numbers, so an upstream that misreports usage cannot change
+which Source serves the next turn.
+
+`requests` is self-measured by the gateway and is always present. Token counts are
+vendor-reported and may be absent for a served turn — streaming chat completions
+report usage only when the client asked for it — so `token_reports` counts the
+turns that carried a report and a missing report is never read as zero usage. Every
+reported integer is bounded by a ceiling fixed in server code, never by a total the
+response declares.
+
+Input composition follows each protocol rather than one invented total.
+`cached_input_tokens` is always the subset of `input_tokens` that was served from
+cache: Anthropic's own `input_tokens` excludes both cache members, so the reported
+input total is their sum; OpenAI's already includes cached input, so the cached
+count is informational only.
+
+Days are local-calendar days on the Avibe host. `from_day` and `to_day` bound the
+requested window even when no turn fell inside it; `days[]` contains only days that
+carry a metered turn. `label` is joined from current Source config, so it is `null`
+for a Source that has since been removed and follows a rename immediately.
+
## Runtime installation and host support
Every runtime response carries `host_platform`, and every status carries `error_key`.
diff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.json
new file mode 100644
index 000000000..e50738206
--- /dev/null
+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json
@@ -0,0 +1,254 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/usage-summary.schema.json",
+ "title": "Model Hub usage summary",
+ "description": "Metered token usage over a trailing local-day window, aggregated from the turns the gateway proxied. A report only: no consumer of this document may feed it back into resolution, admission, or cooldown.",
+ "type": "object",
+ "required": [
+ "window_days",
+ "from_day",
+ "to_day",
+ "totals",
+ "sources",
+ "days"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "window_days": {
+ "description": "Requested window after clamping to the retained range.",
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 62
+ },
+ "from_day": {
+ "$ref": "#/definitions/LocalDay",
+ "description": "First local day of the window, present even when it carries no turn."
+ },
+ "to_day": {
+ "$ref": "#/definitions/LocalDay",
+ "description": "Last local day of the window, which is the host's today."
+ },
+ "totals": {
+ "$ref": "#/definitions/Counters"
+ },
+ "sources": {
+ "description": "One entry per Source with at least one metered turn in the window, busiest first.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/SourceUsage"
+ }
+ },
+ "days": {
+ "description": "One entry per local day carrying a metered turn, oldest first.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/DayUsage"
+ }
+ }
+ },
+ "definitions": {
+ "LocalDay": {
+ "type": "string",
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
+ },
+ "Count": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 1000000000
+ },
+ "Counters": {
+ "type": "object",
+ "required": [
+ "requests",
+ "token_reports",
+ "input_tokens",
+ "cached_input_tokens",
+ "output_tokens"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "requests": {
+ "$ref": "#/definitions/Count",
+ "description": "Self-measured served turns. Always available."
+ },
+ "token_reports": {
+ "$ref": "#/definitions/Count",
+ "description": "Served turns whose upstream response carried a token report. Never greater than requests; a shortfall means missing reports, not zero usage."
+ },
+ "input_tokens": {
+ "$ref": "#/definitions/Count",
+ "description": "Vendor-reported input tokens composed per protocol, including tokens served from cache."
+ },
+ "cached_input_tokens": {
+ "$ref": "#/definitions/Count",
+ "description": "Subset of input_tokens served from cache."
+ },
+ "output_tokens": {
+ "$ref": "#/definitions/Count"
+ }
+ }
+ },
+ "SourceUsage": {
+ "type": "object",
+ "required": [
+ "source_id",
+ "label",
+ "requests",
+ "token_reports",
+ "input_tokens",
+ "cached_input_tokens",
+ "output_tokens",
+ "last_served_at",
+ "models"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "label": {
+ "description": "Joined from current Source config; null once the Source is gone.",
+ "type": ["string", "null"]
+ },
+ "requests": {
+ "$ref": "#/definitions/Count"
+ },
+ "token_reports": {
+ "$ref": "#/definitions/Count"
+ },
+ "input_tokens": {
+ "$ref": "#/definitions/Count"
+ },
+ "cached_input_tokens": {
+ "$ref": "#/definitions/Count"
+ },
+ "output_tokens": {
+ "$ref": "#/definitions/Count"
+ },
+ "last_served_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "models": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#/definitions/ModelUsage"
+ }
+ }
+ }
+ },
+ "ModelUsage": {
+ "type": "object",
+ "required": [
+ "model_id",
+ "requests",
+ "token_reports",
+ "input_tokens",
+ "cached_input_tokens",
+ "output_tokens"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "model_id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "requests": {
+ "$ref": "#/definitions/Count"
+ },
+ "token_reports": {
+ "$ref": "#/definitions/Count"
+ },
+ "input_tokens": {
+ "$ref": "#/definitions/Count"
+ },
+ "cached_input_tokens": {
+ "$ref": "#/definitions/Count"
+ },
+ "output_tokens": {
+ "$ref": "#/definitions/Count"
+ }
+ }
+ },
+ "DayUsage": {
+ "type": "object",
+ "required": [
+ "day",
+ "requests",
+ "token_reports",
+ "input_tokens",
+ "cached_input_tokens",
+ "output_tokens"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "day": {
+ "$ref": "#/definitions/LocalDay"
+ },
+ "requests": {
+ "$ref": "#/definitions/Count"
+ },
+ "token_reports": {
+ "$ref": "#/definitions/Count"
+ },
+ "input_tokens": {
+ "$ref": "#/definitions/Count"
+ },
+ "cached_input_tokens": {
+ "$ref": "#/definitions/Count"
+ },
+ "output_tokens": {
+ "$ref": "#/definitions/Count"
+ }
+ }
+ }
+ },
+ "examples": [
+ {
+ "window_days": 30,
+ "from_day": "2026-07-20",
+ "to_day": "2026-08-18",
+ "totals": {
+ "requests": 12,
+ "token_reports": 9,
+ "input_tokens": 148230,
+ "cached_input_tokens": 96010,
+ "output_tokens": 4120
+ },
+ "sources": [
+ {
+ "source_id": "src_conform001",
+ "label": "Contract source",
+ "requests": 12,
+ "token_reports": 9,
+ "input_tokens": 148230,
+ "cached_input_tokens": 96010,
+ "output_tokens": 4120,
+ "last_served_at": "2026-08-18T03:14:00+00:00",
+ "models": [
+ {
+ "model_id": "claude-opus-4-6",
+ "requests": 12,
+ "token_reports": 9,
+ "input_tokens": 148230,
+ "cached_input_tokens": 96010,
+ "output_tokens": 4120
+ }
+ ]
+ }
+ ],
+ "days": [
+ {
+ "day": "2026-08-18",
+ "requests": 12,
+ "token_reports": 9,
+ "input_tokens": 148230,
+ "cached_input_tokens": 96010,
+ "output_tokens": 4120
+ }
+ ]
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
new file mode 100644
index 000000000..06c4196e5
--- /dev/null
+++ b/docs/plans/model-hub-usage-metering.md
@@ -0,0 +1,155 @@
+# Model Hub usage metering core
+
+Status: **in delivery** — stage 1 of two.
+
+## Background
+
+The Model Hub settings page ships two tabs. 来源与网关 is fully specified by 13
+`design.pen` frames and fully implemented. 用量与额度 renders a placeholder that
+promises "usage appears after a gateway source serves a request" — a promise
+nothing in the product can keep:
+
+- `ModelHubSourceUsageConfig` (`config/v2_config.py`) is validated and persisted
+ but has **zero writers**; all three construction sites emit empty defaults.
+- No `/api/models/*` route returns usage. `api.md` mentions `usage` once, only to
+ forbid it in create requests.
+- Token counts exist nowhere durable. `agent_runs`, `background_runs`,
+ `run_definitions`, and `runtime_records` have no token columns; backend adapters
+ surface per-turn counts transiently into a progress bubble and drop them.
+
+So the tab cannot be drawn truthfully before a metering core exists. This plan is
+that core: produce real data first, draw the tab second.
+
+## Goal
+
+Persist a bounded, credential-free, per-source token aggregate measured from the
+turns the hub actually proxies, and expose it through one read route.
+
+Non-goals, explicitly:
+
+- **No spend.** Converting tokens to money needs a per-model price table Avibe
+ does not ship and cannot keep current. `month_spend_cents` stays unwritten.
+- **No quota percentage.** No vendor API exposes a consumer subscription's cycle
+ usage. `cycle_used_pct` and `projected_exhaust_at` stay unwritten.
+- **No enforcement.** These numbers never gate admission, routing, or cooldown.
+ They are a report, not a control input. A hostile upstream must not be able to
+ change resolution behavior by lying about usage.
+
+## Where usage is observable
+
+`core/handlers/model_hub/turn_gateway.py` is the only place in the product that
+sees a complete upstream model response. `stream_wire.py` already tokenizes every
+SSE frame and parses every buffered body through one declarative per-protocol
+table (`PROTOCOL_STREAM_TAXONOMY`) to decide terminal outcome and first-output
+boundary. Usage extraction belongs in that same table — no second parser.
+
+Per protocol, the usage container and its leaves:
+
+| Protocol | Containers | input | cached input | output |
+| --- | --- | --- | --- | --- |
+| `anthropic` | `message.usage` (stream `message_start`), `usage` (stream `message_delta`, buffered body) | `input_tokens` + `cache_read_input_tokens` + `cache_creation_input_tokens` | `cache_read_input_tokens` | `output_tokens` |
+| `openai_responses` | `response.usage` (`response.completed` / `response.incomplete`), `usage` (buffered body) | `input_tokens` | `input_tokens_details.cached_tokens` | `output_tokens` |
+| `openai_chat` | `usage` (final chunk under `stream_options.include_usage`, buffered body) | `prompt_tokens` | `prompt_tokens_details.cached_tokens` | `completion_tokens` |
+
+Two composition rules make this order-insensitive and duplicate-frame-safe:
+
+- **Sum within one container.** Anthropic's `input_tokens` *excludes* cache
+ tokens, so the input total is the sum of three leaves — the same composition
+ `modules/agents/claude_agent.py` already applies. OpenAI's input counts
+ *include* cached tokens, so `cached_input_tokens` there is an informational
+ subset, never an addend.
+- **Take the max across containers and frames.** Anthropic reports cumulative
+ `output_tokens` on every `message_delta`; a max ignores intermediate values and
+ is immune to a frame being observed twice.
+
+## Self-measured versus vendor-reported
+
+`requests` is measured by our own code and always available. Token counts are
+reported by the upstream vendor and may be absent (`openai_chat` only emits usage
+when the client asked for it). The ledger therefore keeps a separate
+`token_reports` counter so the tab can say "12 requests, 9 with reported tokens"
+instead of implying that a missing report is zero usage.
+
+Every vendor-reported integer is validated as a non-negative, non-bool `int` under
+a fixed structural ceiling before it is accumulated, so one buggy or hostile
+response cannot permanently poison the aggregate. The ceiling is a constant in our
+code, never a value the upstream declares.
+
+## Persisted shape
+
+New state file `~/.avibe/state/model_hub_usage.json`, written through the same
+atomic pattern as `BoundedEventLog` / `BoundedProvenanceStore`: lock, read,
+mutate, `NamedTemporaryFile` + `flush` + `fsync` + `chmod 0o600` + `os.replace`.
+A read error or non-list payload degrades to `[]` — per the persisted-shape rule,
+a broken optional-feature file disables the feature and never fails startup.
+
+One row per `(day, source_id, model_id)` — exactly the dimensions the read surface
+reports. A `backend` dimension is deliberately absent: nothing in the summary
+groups by it, and a persisted column no reader consumes is a concept without an
+owner. It can be added when a reader needs it.
+
+```json
+{
+ "day": "2026-08-18",
+ "source_id": "src_abc",
+ "model_id": "claude-opus-4-6",
+ "requests": 12,
+ "token_reports": 9,
+ "input_tokens": 148230,
+ "cached_input_tokens": 96010,
+ "output_tokens": 4120,
+ "last_served_at": "2026-08-18T03:14:00+00:00"
+}
+```
+
+Days are **local-calendar** days: Avibe is a local-first product and the UI
+already presents local days (`ui/src/components/settings/models/localCalendar.ts`).
+
+No source label is persisted. Labels are user-supplied text that resolution events
+have to redact; the read path joins `source_id` against current config instead, so
+the ledger stays credential-free and immune to label drift.
+
+Bounds: rows older than 62 local days are dropped on write, then the newest 400
+rows are retained (oldest day evicted first).
+
+## Recording policy
+
+Record one row increment at each of the two settlement points in
+`ModelHubTurnGateway._resolved_response`, and only when the turn actually reached
+the model — buffered: the settlement decision is `return`; streaming: the wire
+terminal was `served`. A turn that upstream reported usage for is also recorded
+even if its stream ended in a terminal error, because the vendor billed it.
+
+Failures already have their own surface (resolution events plus source health);
+counting them here would duplicate that concept.
+
+## Read surface
+
+`GET /api/models/usage?days=<n>` → `{usage: UsageSummary}` with `days` bounded to
+`[1, 62]`, defaulting to 30. The summary is derived entirely from the rows:
+
+- `totals` — window-wide counters
+- `sources[]` — per source, with a `models[]` breakdown and `last_served_at`
+- `days[]` — one entry per local day, ascending, for a trend series
+
+Contract work: an `api.md` route-table row, an `x-model-hub-routes` entry plus a
+`UsageResponse` definition in `api-response.schema.json`, and a new
+`usage-summary.schema.json`. The existing conformance guard then exercises the
+route against a real server response.
+
+## Todo
+
+- [x] Usage taxonomy and extraction in `stream_wire.py`
+- [x] `BoundedUsageLedger` in `core/handlers/model_hub/usage.py`
+- [x] Gateway recording at both settlement points
+- [x] `ModelHubService.usage_summary` + RPC + `GET /api/models/usage`
+- [x] Contract row, response registry entry, and usage schema
+- [x] Unit and contract coverage
+- [ ] Stage 2: draw the 用量与额度 tab against this data
+
+## Stage 2 note
+
+The tab is currently named 用量与额度 / "Usage and quota". After this stage the
+用量 half is real and the 额度 half is still unobtainable, so the label needs a
+design decision before stage 2 ships — renaming the tab to 用量 is the honest
+option unless a quota source appears.
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 08388c578..0e5fd6e86 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -45,6 +45,8 @@ from core.handlers.model_hub.oauth import (
)
from core.handlers.model_hub.provenance import BoundedProvenanceStore
from core.handlers.model_hub.revocations import CredentialRevocationJournal
+from core.handlers.model_hub.stream_wire import ProtocolUsageReport
+from core.handlers.model_hub.usage import BoundedUsageLedger
from core.handlers.model_hub.service import (
CONTRACT_VERSION,
ModelHubError,
@@ -326,6 +328,7 @@ def _service(tmp_path, adapter=None):
adapter=adapter,
events=BoundedEventLog(tmp_path / "events.json"),
provenance=BoundedProvenanceStore(tmp_path / "provenance.json"),
+ usage=BoundedUsageLedger(tmp_path / "usage.json"),
native_oauth_adapter=adapter,
oauth_flows=OAuthFlowRegistry(
tmp_path / "oauth_flows.json",
@@ -513,6 +516,22 @@ def _seed_response_conformance_service(tmp_path: Path) -> ModelHubService:
provenance = copy.deepcopy(_schema("turn-provenance.schema.json")["examples"][0])
provenance["turn_id"] = "turn_contract01"
service.provenance.put(provenance)
+ service.usage.record(
+ source_id="src_conform001",
+ model_id="claude-opus-4-6",
+ usage=ProtocolUsageReport(
+ input_tokens=148230,
+ cached_input_tokens=96010,
+ output_tokens=4120,
+ ),
+ at=service.now(),
+ )
+ service.usage.record(
+ source_id="src_conform001",
+ model_id="claude-opus-4-6",
+ usage=None,
+ at=service.now(),
+ )
asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub"}))
return service
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index ead548ece..2aa95ba8f 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -68,6 +68,7 @@ from core.handlers.model_hub.turn_gateway import (
_SSEWireState,
render_protocol_terminal_event,
)
+from core.handlers.model_hub.usage import BoundedUsageLedger
from core.run_settlement import (
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLED_BY_STOPPED,
@@ -1155,6 +1156,7 @@ def _service(
adapter=ProbeAdapter(outcomes or [], live_handles),
events=BoundedEventLog(tmp_path / "events.json"),
provenance=BoundedProvenanceStore(tmp_path / "provenance.json"),
+ usage=BoundedUsageLedger(tmp_path / "usage.json"),
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
now=lambda: NOW,
requested_model_override=store.requested_model,
@@ -6059,3 +6061,227 @@ def test_known_opencode_turn_is_fail_closed_but_not_unknown(
service.get_turn_provenance("turn_opencode")
assert unavailable.value.code == "provenance_unavailable"
assert unavailable.value.detail == "models.provenance.attribution_ambiguous"
+
+
+def _usage_of(service: ModelHubService, source_id: str) -> dict:
+ summary = service.usage_summary(days=30)
+ matches = [source for source in summary["sources"] if source["source_id"] == source_id]
+ return matches[0] if matches else {}
+
+
+def test_gateway_meters_a_buffered_served_turn_from_the_upstream_body(
+ tmp_path: Path,
+) -> None:
+ async def exercise() -> None:
+ source = _source("src_meterbuf01", "Buffered meter")
+ body = json.dumps(
+ {
+ "id": "resp_buffered",
+ "usage": {
+ "input_tokens": 4096,
+ "input_tokens_details": {"cached_tokens": 3072},
+ "output_tokens": 128,
+ },
+ }
+ ).encode("utf-8")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id),
+ (body,),
+ )
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_buffered",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=False,
+ )
+
+ result = await gateway._handle_request(request)
+
+ assert result.status == 200
+ assert result.body == body
+ metered = _usage_of(service, source.id)
+ assert metered["label"] == "Buffered meter"
+ assert metered["requests"] == 1
+ assert metered["token_reports"] == 1
+ assert metered["input_tokens"] == 4096
+ assert metered["cached_input_tokens"] == 3072
+ assert metered["output_tokens"] == 128
+ assert [model["model_id"] for model in metered["models"]] == ["shared-model"]
+
+ asyncio.run(exercise())
+
+
+def test_gateway_meters_a_streamed_served_turn_from_the_wire(tmp_path: Path) -> None:
+ async def exercise() -> None:
+ source = _source("src_meterwire01", "Streamed meter")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(
+ RawOutcomeKind.SUCCESS,
+ status=200,
+ source_id=source.id,
+ stream_started=True,
+ ),
+ (
+ b'event: response.output_text.delta\ndata: {"type":'
+ b'"response.output_text.delta","sequence_number":1}\n\n',
+ b'event: response.completed\ndata: {"type":"response.completed",'
+ b'"sequence_number":2,"response":{"usage":{"input_tokens":900,'
+ b'"output_tokens":64}}}\n\n',
+ ),
+ )
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_streamed",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=True,
+ )
+ with patch(
+ "core.handlers.model_hub.turn_gateway.web.StreamResponse",
+ return_value=FakeStreamResponse(),
+ ):
+ await gateway._handle_request(request)
+
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1
+ assert metered["token_reports"] == 1
+ assert metered["input_tokens"] == 900
+ assert metered["output_tokens"] == 64
+
+ asyncio.run(exercise())
+
+
+def test_gateway_meters_a_failed_turn_that_upstream_already_billed(
+ tmp_path: Path,
+) -> None:
+ """A vendor that reported tokens billed us even when the stream failed."""
+
+ async def exercise() -> None:
+ source = _source("src_meterfail01", "Billed failure")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(
+ RawOutcomeKind.HTTP_ERROR,
+ status=500,
+ source_id=source.id,
+ stream_started=True,
+ ),
+ (
+ b'event: response.output_text.delta\ndata: {"type":'
+ b'"response.output_text.delta","sequence_number":1}\n\n',
+ b'event: error\ndata: {"type":"error","code":"server_error",'
+ b'"sequence_number":2,"usage":{"input_tokens":41,'
+ b'"output_tokens":0}}\n\n',
+ ),
+ )
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_billed_failure",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=True,
+ )
+ with patch(
+ "core.handlers.model_hub.turn_gateway.web.StreamResponse",
+ return_value=FakeStreamResponse(),
+ ):
+ await gateway._handle_request(request)
+
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1
+ assert metered["token_reports"] == 1
+ assert metered["input_tokens"] == 41
+ # The failure keeps its own surface; metering does not replace it.
+ assert service.store.load().sources[0].state.status != "standby"
+
+ asyncio.run(exercise())
+
+
+def test_gateway_meters_nothing_for_a_turn_that_never_reached_the_model(
+ tmp_path: Path,
+) -> None:
+ async def exercise() -> None:
+ source = _source("src_meternone01", "Unreached", status="needs_action")
+ service = _service(tmp_path, sources=[source])
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ service.store.config.agents["codex"].routes[requested_model] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(source.id, "removed-model"),)
+ )
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_unreached",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=False,
+ )
+
+ result = await gateway._handle_request(request)
+
+ assert result.status == 409
+ summary = service.usage_summary(days=30)
+ assert summary["sources"] == []
+ assert summary["totals"]["requests"] == 0
+
+ asyncio.run(exercise())
+
+
+def test_a_usage_ledger_failure_cannot_change_the_served_turn(tmp_path: Path) -> None:
+ """Metering is a report, so a ledger fault must stay invisible downstream."""
+
+ async def exercise() -> None:
+ source = _source("src_meterbust01", "Broken ledger")
+ body = json.dumps({"id": "resp_ok", "usage": {"input_tokens": 7}}).encode("utf-8")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id),
+ (body,),
+ )
+ ],
+ )
+ service.usage.record = Mock(side_effect=OSError("read-only state directory"))
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_broken_ledger",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=False,
+ )
+
+ result = await gateway._handle_request(request)
+
+ assert result.status == 200
+ assert result.body == body
+ service.usage.record.assert_called_once()
+ assert service.store.load().sources[0].state.status == "standby"
+
+ asyncio.run(exercise())
diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.py
new file mode 100644
index 000000000..4bdddd4c8
--- /dev/null
+++ b/tests/test_model_hub_usage.py
@@ -0,0 +1,587 @@
+"""Model Hub usage metering: wire extraction and bounded persistence.
+
+Two properties are under test. Extraction must read exactly what each protocol
+reports and refuse everything else, because token counts are the one number in
+the hub that a hostile upstream fully controls. Persistence must stay bounded and
+must survive an older or corrupt file, because the ledger is a shipped on-disk
+surface.
+
+Gateway recording is covered in ``test_model_hub_l3.py``, next to the turn
+settlement scaffolding it depends on.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import stat
+from datetime import date, datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+
+from core.handlers.model_hub.stream_wire import (
+ PROTOCOL_STREAM_TAXONOMY,
+ USAGE_TOKEN_CEILING,
+ ProtocolSSEState,
+ ProtocolUsageReport,
+ extract_protocol_usage,
+ observe_protocol_response,
+)
+from core.handlers.model_hub.usage import (
+ USAGE_RETENTION_DAYS,
+ BoundedUsageLedger,
+ local_usage_day,
+)
+
+NOW = datetime(2026, 7, 23, 12, 0, tzinfo=timezone.utc)
+
+
+def _frame(document: dict) -> bytes:
+ """Render one SSE frame the way the protocols that name events do.
+
+ Anthropic and OpenAI Responses both send `event:` alongside the discriminator
+ in the body, and both are required to match a terminal envelope. OpenAI Chat
+ sends unnamed frames, which is exactly the shape a body without `type` gets.
+ """
+
+ named = f"event: {document['type']}\n".encode("utf-8") if "type" in document else b""
+ return named + b"data: " + json.dumps(document).encode("utf-8") + b"\n\n"
+
+
+def _frames(*documents: dict) -> tuple[bytes, ...]:
+ return tuple(_frame(document) for document in documents)
+
+
+def _observed(protocol: str, *documents: dict) -> ProtocolUsageReport | None:
+ state = ProtocolSSEState(protocol)
+ for frame in _frames(*documents):
+ state.observe(frame)
+ return state.usage
+
+
+# --- Extraction: every protocol declares where it reports usage ---------------
+
+
+def test_every_observed_protocol_declares_a_usage_location() -> None:
+ """A new protocol cannot ship unmetered: the table demands the location."""
+
+ for protocol, taxonomy in PROTOCOL_STREAM_TAXONOMY.items():
+ usage = taxonomy.usage
+ assert usage.container_paths, protocol
+ assert usage.input_paths, protocol
+ assert usage.output_paths, protocol
+ assert usage.cached_input_paths, protocol
+
+
+def test_anthropic_input_total_sums_the_cache_members() -> None:
+ """Anthropic reports `input_tokens` net of cache, so input is the sum."""
+
+ report = extract_protocol_usage(
+ "anthropic",
+ {
+ "type": "message",
+ "usage": {
+ "input_tokens": 12,
+ "cache_read_input_tokens": 900,
+ "cache_creation_input_tokens": 88,
+ "output_tokens": 40,
+ },
+ },
+ )
+
+ assert report == ProtocolUsageReport(
+ input_tokens=1000,
+ cached_input_tokens=900,
+ output_tokens=40,
+ )
+
+
+def test_anthropic_stream_keeps_the_largest_cumulative_report() -> None:
+ """`message_delta` restates a running total, so the largest frame wins."""
+
+ usage = _observed(
+ "anthropic",
+ {"type": "message_start", "message": {"usage": {"input_tokens": 1000, "output_tokens": 1}}},
+ {"type": "content_block_delta", "delta": {"text": "hi"}},
+ {"type": "message_delta", "usage": {"output_tokens": 40}},
+ {"type": "message_delta", "usage": {"output_tokens": 250}},
+ {"type": "message_stop"},
+ )
+
+ assert usage == ProtocolUsageReport(input_tokens=1000, output_tokens=250)
+
+
+def test_a_replayed_usage_frame_cannot_double_count() -> None:
+ """Merging by the larger value makes retries and duplicates harmless."""
+
+ single = _observed(
+ "openai_responses",
+ {"type": "response.in_progress", "response": {"usage": {"input_tokens": 700, "output_tokens": 9}}},
+ )
+ replayed = _observed(
+ "openai_responses",
+ {"type": "response.in_progress", "response": {"usage": {"input_tokens": 700, "output_tokens": 9}}},
+ {"type": "response.in_progress", "response": {"usage": {"input_tokens": 700, "output_tokens": 9}}},
+ )
+
+ assert single == replayed == ProtocolUsageReport(input_tokens=700, output_tokens=9)
+
+
+def test_openai_responses_reports_cached_input_as_a_subset() -> None:
+ """`input_tokens` already includes cached input, so it is never an addend."""
+
+ usage = _observed(
+ "openai_responses",
+ {
+ "type": "response.completed",
+ "response": {
+ "usage": {
+ "input_tokens": 5000,
+ "input_tokens_details": {"cached_tokens": 4096},
+ "output_tokens": 77,
+ }
+ },
+ },
+ )
+
+ assert usage == ProtocolUsageReport(
+ input_tokens=5000,
+ cached_input_tokens=4096,
+ output_tokens=77,
+ )
+
+
+def test_usage_on_the_terminal_frame_is_observed_before_settlement() -> None:
+ """The frame that ends the stream is also the one that carries the report."""
+
+ state = ProtocolSSEState("openai_responses")
+ for frame in _frames(
+ {"type": "response.completed", "response": {"usage": {"input_tokens": 30, "output_tokens": 4}}},
+ {"type": "response.completed", "response": {"usage": {"input_tokens": 999999, "output_tokens": 4}}},
+ ):
+ state.observe(frame)
+
+ assert state.terminal_outcome == "served"
+ # The second frame arrives after settlement and is ignored entirely, so it
+ # cannot inflate the report either.
+ assert state.usage == ProtocolUsageReport(input_tokens=30, output_tokens=4)
+
+
+def test_openai_chat_reports_usage_only_on_its_final_chunk() -> None:
+ """Chat streaming carries usage on a dedicated chunk, then `[DONE]`."""
+
+ state = ProtocolSSEState("openai_chat")
+ state.observe(_frames({"choices": [{"delta": {"content": "hi"}}]})[0])
+ assert state.usage is None
+
+ state.observe(
+ _frames(
+ {
+ "choices": [],
+ "usage": {
+ "prompt_tokens": 610,
+ "prompt_tokens_details": {"cached_tokens": 512},
+ "completion_tokens": 22,
+ },
+ }
+ )[0]
+ )
+ state.observe(b"data: [DONE]\n\n")
+
+ assert state.terminal_outcome == "served"
+ assert state.usage == ProtocolUsageReport(
+ input_tokens=610,
+ cached_input_tokens=512,
+ output_tokens=22,
+ )
+
+
+def test_a_buffered_response_without_a_report_stays_unmetered() -> None:
+ """A missing report is absent, never zero: the caller tracks the shortfall."""
+
+ observation = observe_protocol_response(
+ "openai_chat",
+ streamed=False,
+ data=json.dumps({"choices": [{"message": {"content": "hi"}}]}).encode("utf-8"),
+ )
+
+ assert observation.outcome == "served"
+ assert observation.usage is None
+
+
+def test_a_buffered_error_still_carries_the_tokens_it_billed() -> None:
+ """A vendor that reported tokens billed us even when the turn failed."""
+
+ observation = observe_protocol_response(
+ "anthropic",
+ streamed=False,
+ data=json.dumps(
+ {
+ "error": {"type": "overloaded_error"},
+ "usage": {"input_tokens": 41, "output_tokens": 0},
+ }
+ ).encode("utf-8"),
+ )
+
+ assert observation.outcome == "failed_terminal"
+ assert observation.usage == ProtocolUsageReport(input_tokens=41)
+
+
+ "reported",
+ [
+ pytest.param(-1, id="negative"),
+ pytest.param(True, id="bool"),
+ pytest.param("120", id="string"),
+ pytest.param(12.5, id="float"),
+ pytest.param(None, id="null"),
+ pytest.param([120], id="list"),
+ pytest.param(USAGE_TOKEN_CEILING + 1, id="above-ceiling"),
+ ],
+)
+def test_an_unusable_token_value_is_dropped_not_coerced(reported: object) -> None:
+ """Only a bounded non-negative integer count is a token count."""
+
+ report = extract_protocol_usage(
+ "openai_chat",
+ {"usage": {"prompt_tokens": reported, "completion_tokens": 7}},
+ )
+
+ assert report == ProtocolUsageReport(output_tokens=7)
+
+
+def test_a_composed_input_total_cannot_exceed_our_own_ceiling() -> None:
+ """The ceiling lives in our code, never in a total the response declares."""
+
+ report = extract_protocol_usage(
+ "anthropic",
+ {
+ "usage": {
+ "input_tokens": USAGE_TOKEN_CEILING,
+ "cache_read_input_tokens": USAGE_TOKEN_CEILING,
+ "total_tokens": 3,
+ }
+ },
+ )
+
+ assert report is not None
+ assert report.input_tokens == USAGE_TOKEN_CEILING
+ assert report.cached_input_tokens == USAGE_TOKEN_CEILING
+
+
+ "payload",
+ [
+ pytest.param({"type": "ping"}, id="no-container"),
+ pytest.param({"usage": "many"}, id="container-not-an-object"),
+ pytest.param({"usage": {}}, id="empty-container"),
+ pytest.param({"usage": {"unknown_tokens": 5}}, id="unknown-members-only"),
+ ],
+)
+def test_a_document_with_no_readable_report_yields_none(payload: dict) -> None:
+ assert extract_protocol_usage("openai_chat", payload) is None
+
+
+# --- Persistence: bounded, credential-free, and safe to load -----------------
+
+
+def _ledger(tmp_path: Path, **kwargs) -> BoundedUsageLedger:
+ return BoundedUsageLedger(tmp_path / "state" / "usage.json", **kwargs)
+
+
+def test_records_fold_into_one_row_per_day_source_and_model(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+
+ ledger.record(
+ source_id="src_a",
+ model_id="model-x",
+ usage=ProtocolUsageReport(input_tokens=100, cached_input_tokens=40, output_tokens=7),
+ at=NOW,
+ )
+ ledger.record(
+ source_id="src_a",
+ model_id="model-x",
+ usage=ProtocolUsageReport(input_tokens=200, output_tokens=3),
+ at=NOW + timedelta(hours=1),
+ )
+
+ rows = ledger.window(days=1, now=NOW + timedelta(hours=1))
+ assert len(rows) == 1
+ assert rows[0]["requests"] == 2
+ assert rows[0]["token_reports"] == 2
+ assert rows[0]["input_tokens"] == 300
+ assert rows[0]["cached_input_tokens"] == 40
+ assert rows[0]["output_tokens"] == 7 + 3
+ assert rows[0]["last_served_at"] == (NOW + timedelta(hours=1)).isoformat()
+
+
+def test_a_turn_without_a_report_counts_the_request_only(tmp_path: Path) -> None:
+ """`requests` is self-measured; a missing report must not read as zero usage."""
+
+ ledger = _ledger(tmp_path)
+
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
+ ledger.record(
+ source_id="src_a",
+ model_id="model-x",
+ usage=ProtocolUsageReport(input_tokens=90),
+ at=NOW,
+ )
+
+ totals = ledger.summary(days=7, now=NOW)["totals"]
+ assert totals["requests"] == 2
+ assert totals["token_reports"] == 1
+ assert totals["input_tokens"] == 90
+
+
+def test_summary_groups_by_source_then_model_and_orders_by_traffic(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+ yesterday = NOW - timedelta(days=1)
+
+ for _ in range(3):
+ ledger.record(
+ source_id="src_busy",
+ model_id="model-x",
+ usage=ProtocolUsageReport(input_tokens=10),
+ at=yesterday,
+ )
+ ledger.record(
+ source_id="src_busy",
+ model_id="model-y",
+ usage=ProtocolUsageReport(input_tokens=5),
+ at=NOW,
+ )
+ ledger.record(source_id="src_quiet", model_id="model-x", usage=None, at=NOW)
+
+ summary = ledger.summary(days=7, now=NOW)
+
+ assert summary["window_days"] == 7
+ assert summary["to_day"] == local_usage_day(NOW).isoformat()
+ assert summary["from_day"] == (local_usage_day(NOW) - timedelta(days=6)).isoformat()
+ assert [source["source_id"] for source in summary["sources"]] == ["src_busy", "src_quiet"]
+ assert [model["model_id"] for model in summary["sources"][0]["models"]] == [
+ "model-x",
+ "model-y",
+ ]
+ assert summary["sources"][0]["requests"] == 4
+ assert summary["sources"][0]["input_tokens"] == 35
+ assert [day["day"] for day in summary["days"]] == sorted(day["day"] for day in summary["days"])
+ assert len(summary["days"]) == 2
+ assert summary["totals"]["requests"] == 5
+
+
+def test_summary_reports_a_day_range_even_when_it_carries_no_turn(tmp_path: Path) -> None:
+ """Days are the window's frame; only days with data become entries."""
+
+ summary = _ledger(tmp_path).summary(days=30, now=NOW)
+
+ assert summary["days"] == []
+ assert summary["sources"] == []
+ assert summary["totals"]["requests"] == 0
+ assert summary["from_day"] < summary["to_day"]
+
+
+def test_a_window_excludes_days_outside_it(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW - timedelta(days=5))
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
+
+ assert len(ledger.window(days=30, now=NOW)) == 2
+ assert len(ledger.window(days=2, now=NOW)) == 1
+
+
+ "requested,expected",
+ [
+ pytest.param(0, 1, id="zero-clamps-up"),
+ pytest.param(-7, 1, id="negative-clamps-up"),
+ pytest.param(10_000, USAGE_RETENTION_DAYS, id="clamps-to-retention"),
+ ],
+)
+def test_a_requested_window_is_clamped_to_what_is_retained(
+ tmp_path: Path,
+ requested: int,
+ expected: int,
+) -> None:
+ assert _ledger(tmp_path).summary(days=requested, now=NOW)["window_days"] == expected
+
+
+def test_retention_drops_rows_past_the_horizon(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path, retention_days=3)
+
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW - timedelta(days=10))
+ assert len(ledger.window(days=3, now=NOW - timedelta(days=10))) == 1
+
+ # Recording under a later day is what advances the horizon.
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
+ persisted = json.loads(ledger.path.read_text(encoding="utf-8"))
+ assert [row["day"] for row in persisted] == [local_usage_day(NOW).isoformat()]
+
+
+def test_the_row_cap_keeps_the_newest_rows(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path, max_rows=3)
+
+ for index in range(6):
+ ledger.record(
+ source_id="src_a",
+ model_id=f"model-{index}",
+ usage=None,
+ at=NOW,
+ )
+
+ persisted = json.loads(ledger.path.read_text(encoding="utf-8"))
+ assert [row["model_id"] for row in persisted] == ["model-3", "model-4", "model-5"]
+
+
+ "content",
+ [
+ pytest.param("", id="empty"),
+ pytest.param("not json", id="unparseable"),
+ pytest.param('{"rows": []}', id="object-instead-of-list"),
+ pytest.param("[1, 2, 3]", id="scalar-rows"),
+ pytest.param('[{"source_id": "src_a"}]', id="row-missing-day"),
+ pytest.param('[{"day": "not-a-day", "source_id": "s", "model_id": "m"}]', id="row-bad-day"),
+ ],
+)
+def test_an_unreadable_ledger_degrades_to_empty_and_keeps_recording(
+ tmp_path: Path,
+ content: str,
+) -> None:
+ """A broken optional-feature file disables the feature; it never fails."""
+
+ ledger = _ledger(tmp_path)
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ ledger.path.write_text(content, encoding="utf-8")
+
+ assert ledger.window(days=30, now=NOW) == []
+
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
+ assert ledger.summary(days=30, now=NOW)["totals"]["requests"] == 1
+
+
+def test_a_row_with_unusable_counters_loads_as_zero(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ ledger.path.write_text(
+ json.dumps(
+ [
+ {
+ "day": local_usage_day(NOW).isoformat(),
+ "source_id": "src_a",
+ "model_id": "model-x",
+ "requests": -4,
+ "token_reports": True,
+ "input_tokens": "many",
+ "output_tokens": USAGE_TOKEN_CEILING * 5,
+ }
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ row = ledger.window(days=30, now=NOW)[0]
+ assert row["requests"] == 0
+ assert row["token_reports"] == 0
+ assert row["input_tokens"] == 0
+ assert row["cached_input_tokens"] == 0
+ assert row["output_tokens"] == USAGE_TOKEN_CEILING
+
+
+def test_duplicate_persisted_rows_merge_instead_of_shadowing(tmp_path: Path) -> None:
+ """An older file could hold the same key twice; both counts must survive."""
+
+ ledger = _ledger(tmp_path)
+ row = {
+ "day": local_usage_day(NOW).isoformat(),
+ "source_id": "src_a",
+ "model_id": "model-x",
+ "requests": 2,
+ "token_reports": 2,
+ "input_tokens": 50,
+ "cached_input_tokens": 0,
+ "output_tokens": 5,
+ }
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ ledger.path.write_text(json.dumps([row, dict(row)]), encoding="utf-8")
+
+ rows = ledger.window(days=30, now=NOW)
+ assert len(rows) == 1
+ assert rows[0]["requests"] == 4
+ assert rows[0]["input_tokens"] == 100
+
+
+def test_accumulated_counters_stop_at_the_ceiling(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+ saturated = ProtocolUsageReport(input_tokens=USAGE_TOKEN_CEILING)
+
+ ledger.record(source_id="src_a", model_id="model-x", usage=saturated, at=NOW)
+ ledger.record(source_id="src_a", model_id="model-x", usage=saturated, at=NOW)
+
+ assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == USAGE_TOKEN_CEILING
+
+
+ "source_id,model_id",
+ [
+ pytest.param("", "model-x", id="empty-source"),
+ pytest.param(" ", "model-x", id="blank-source"),
+ pytest.param("src_a", "m" * 500, id="oversized-model"),
+ ],
+)
+def test_an_unusable_identifier_is_never_persisted(
+ tmp_path: Path,
+ source_id: str,
+ model_id: str,
+) -> None:
+ ledger = _ledger(tmp_path)
+
+ ledger.record(source_id=source_id, model_id=model_id, usage=None, at=NOW)
+
+ assert ledger.window(days=30, now=NOW) == []
+
+
+def test_the_ledger_file_is_owner_only(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
+
+ assert stat.S_IMODE(os.stat(ledger.path).st_mode) == 0o600
+
+
+def test_a_record_leaves_no_temporary_file_behind(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
+
+ assert [entry.name for entry in ledger.path.parent.iterdir()] == [ledger.path.name]
+
+
+def test_days_bucket_by_the_host_calendar_not_utc(tmp_path: Path) -> None:
+ """Avibe is local-first, so a day boundary is the user's midnight."""
+
+ moment = datetime(2026, 7, 23, 21, 30, tzinfo=timezone.utc)
+ expected = datetime.fromtimestamp(moment.timestamp()).date()
+
+ assert local_usage_day(moment) == expected
+
+ ledger = _ledger(tmp_path)
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=moment)
+ assert ledger.window(days=1, now=moment)[0]["day"] == expected.isoformat()
+
+
+def test_one_local_day_holds_moments_from_two_utc_days(tmp_path: Path) -> None:
+ """Bucketing must follow the host's calendar consistently, whatever it is."""
+
+ ledger = _ledger(tmp_path)
+ local_noon = datetime.combine(date(2026, 7, 23), datetime.min.time()).astimezone() + timedelta(hours=12)
+
+ for offset in (timedelta(hours=-11), timedelta(hours=11)):
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=local_noon + offset)
+
+ rows = ledger.window(days=1, now=local_noon)
+ assert len(rows) == 1
+ assert rows[0]["day"] == "2026-07-23"
+ assert rows[0]["requests"] == 2
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 1640faadf..23dd43995 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -7,6 +7,7 @@ from typing import Any, Optional
import httpx
from core.handlers.model_hub import ModelHubError
+from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS
from vibe.internal_client import default_socket_path
@@ -206,6 +207,9 @@ 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})
+
def agent_chain(self, backend: str, model_id: str) -> dict:
return _rpc_sync(
"get_agent_chain",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 6d2039c0f..1243160c1 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4465,6 +4465,22 @@ 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
+
+ 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)
+
+
@app.route("/api/models/agents/<backend>/chain", methods=["GET"])
def model_hub_agent_chain_get(backend):
from core.handlers.model_hub import ModelHubError