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): meter every billed upstream call, not just served turns

cyhac32d0981864
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index ed26a7ada..ced461a5a 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -14,6 +14,8 @@ from dataclasses import dataclass
from enum import Enum
from typing import Any, AsyncIterator, Final, Literal, Mapping, Protocol, Sequence
+from .stream_wire import ProtocolUsageReport
+
ENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0
SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")
OBSERVATION_OUTCOMES = (
@@ -97,6 +99,11 @@ class RawCallOutcome:
source_id: str
error_type: str | None = None # raw upstream error type, if present
error_candidates: tuple[str, ...] = () # unsorted raw type/code candidates
+ # Tokens the upstream reported for this call, when the response carried a
+ # readable report. A call that settles before it can hand its body onward
+ # would otherwise take its token report with it, and a vendor that reported
+ # tokens billed for them whether or not the call ended well.
+ usage: ProtocolUsageReport | None = None
class ObservationOutcome(str, Enum):
diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.py
index 1cbfd09d4..5dfccf3da 100644
--- a/core/handlers/model_hub/identifiers.py
+++ b/core/handlers/model_hub/identifiers.py
@@ -2,6 +2,12 @@
from __future__ import annotations
+# The longest model identifier the hub accepts. One constant so the boundaries
+# that admit an identifier (manual add and upstream discovery) and the usage
+# ledger that keys rows by it cannot disagree: a model config accepts is always
+# a model usage can meter, and a persisted row can never grow without limit.
+MODEL_ID_MAX_LENGTH = 200
+
# Vendors with native, stable OpenCode provider identifiers. Compatible relays
# and unrecognized vendors share the frozen contract's single custom/ prefix.
STANDARD_OPENCODE_VENDOR_IDS = frozenset(
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 6cca0d8be..5a4d24db0 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -73,7 +73,7 @@ from .events import (
contains_credential_material,
)
from .errors import ModelDiscoveryError
-from .identifiers import STANDARD_OPENCODE_VENDOR_IDS
+from .identifiers import MODEL_ID_MAX_LENGTH, STANDARD_OPENCODE_VENDOR_IDS
from .migration import (
MigrationConflictError,
apply_native_migration,
@@ -1409,6 +1409,7 @@ class ModelHubService:
if (not allow_empty and not discovered and not manual_models) or any(
not isinstance(model_id, str)
or not model_id
+ or len(model_id) > MODEL_ID_MAX_LENGTH
or contains_credential_material(model_id)
for model_id in discovered
) or len(set(discovered)) != len(discovered):
@@ -3480,6 +3481,7 @@ class ModelHubService:
if (
not isinstance(model_id, str)
or not model_id
+ or len(model_id) > MODEL_ID_MAX_LENGTH
or contains_credential_material(model_id)
):
raise ModelHubError("mapping_target_unavailable")
@@ -4901,8 +4903,51 @@ class ModelHubService:
self.adapter.invoke(source.id, model_id, request, stream, backend)
)
if handle.stream is not None:
+ # The body is the gateway's to forward, so the tokens in it are the
+ # gateway's to meter.
return handle, None
- return handle, await self._engine_call(handle.outcome())
+ outcome = await self._engine_call(handle.outcome())
+ await self._meter_call(source_id=source.id, model_id=model_id, outcome=outcome)
+ return handle, outcome
+
+ async def _meter_call(
+ self,
+ *,
+ source_id: str,
+ model_id: str,
+ outcome: RawCallOutcome,
+ ) -> None:
+ """Fold one bodyless upstream call into the usage ledger, best-effort.
+
+ This is the resolver's half of metering. A call that ends here has no body
+ to hand onward — a terminal error, or a buffered response the resolver
+ itself consumed — so the gateway will never see its token report, and for
+ an error the resolver may not even name this Source in what it raises. A
+ vendor that reported tokens billed for them whether or not the call ended
+ well, and every hop of a failover chain that reported tokens billed the
+ Source it was made against, not the one that finally served the turn.
+
+ The population split with the gateway is ``handle.stream is not None``
+ one frame above: a call either hands its body onward or it does not, so
+ each call is metered exactly once and none is missed.
+
+ The ledger read-modify-write is file I/O, so it runs off the event loop;
+ metering is a report, never a control input, and a ledger failure must not
+ change the outcome the caller sees.
+ """
+
+ if outcome.usage is None:
+ return
+ try:
+ await asyncio.to_thread(
+ self.usage.record,
+ source_id=source_id,
+ model_id=model_id,
+ usage=outcome.usage,
+ at=self.now(),
+ )
+ except (OSError, ValueError) as exc:
+ logger.debug("Model Hub usage metering skipped one call: %s", exc)
async def _classify_source_outcome(
self,
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index 154aaf61b..ea3f97292 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -161,10 +161,39 @@ class ProtocolUsageReport:
cached_input_tokens: int = 0
output_tokens: int = 0
+ @classmethod
+ def of(
+ cls,
+ *,
+ input_tokens: int,
+ cached_input_tokens: int,
+ output_tokens: int,
+ ) -> "ProtocolUsageReport":
+ """Build one report with the cached-input subset invariant enforced.
+
+ Cached input is a *part* of the input the turn was billed for, which is
+ what the read contract promises and what the settings page will divide
+ by. Both numbers come from the same upstream, so the only bound worth
+ trusting is the input count this module normalized itself — never a
+ total the response declares. Cached input reported without a readable
+ input count is a subset of nothing, so it clamps to zero.
+ """
+
+ return cls(
+ input_tokens=input_tokens,
+ cached_input_tokens=min(cached_input_tokens, input_tokens),
+ output_tokens=output_tokens,
+ )
+
def merge(self, other: "ProtocolUsageReport") -> "ProtocolUsageReport":
- """Combine two reports for the same turn by taking the larger of each."""
+ """Combine two reports for the same turn by taking the larger of each.
+
+ The per-field max is re-normalized because the winning input and cached
+ counts can come from different frames, which is a second way an upstream
+ could compose a cached count larger than the input it belongs to.
+ """
- return ProtocolUsageReport(
+ return ProtocolUsageReport.of(
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),
@@ -518,7 +547,7 @@ def extract_protocol_usage(
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(
+ candidate = ProtocolUsageReport.of(
input_tokens=input_tokens or 0,
cached_input_tokens=cached_input_tokens or 0,
output_tokens=output_tokens or 0,
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 0cc6e2f4d..11615eed4 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -94,6 +94,11 @@ class _TurnExecution:
settlement_recorded: bool = False
terminal_fact_committed: bool = False
rendered_turn_outcome: _RenderedTurnOutcome | None = None
+ # The live stream tracker, published here so a boundary that ends the turn
+ # without reaching the end of the chunk loop can still read the tokens the
+ # upstream had already reported.
+ wire_state: _SSEWireState | None = None
+ usage_recorded: bool = False
@dataclass(frozen=True)
@@ -561,6 +566,8 @@ class ModelHubTurnGateway:
if resolved.supply_channel != "hub":
return self._error_response(status=409, code="mode_switch_blocked")
if resolved.outcome is not None:
+ # A call that reached the resolver's own hands has already been
+ # metered there; its body never becomes this gateway's to forward.
return self._outcome_response(resolved.outcome)
handle = resolved.handle
if handle is None or handle.stream is None:
@@ -594,8 +601,8 @@ class ModelHubTurnGateway:
streamed=False,
data=bytes(payload),
).usage
- self._record_usage(
- resolved,
+ await self._record_usage(
+ execution,
usage=buffered_usage,
served=settlement.decision.action == "return",
)
@@ -624,6 +631,7 @@ class ModelHubTurnGateway:
)
await self._downstream_io(response.prepare(request))
wire_state = _SSEWireState(protocol)
+ execution.wire_state = wire_state
async for chunk in handle.stream:
output_started_before = wire_state.model_output_started
wire_state.observe(chunk)
@@ -640,8 +648,8 @@ class ModelHubTurnGateway:
terminalizer,
settlement,
)
- self._record_usage(
- resolved,
+ await self._record_usage(
+ execution,
usage=wire_state.usage,
served=wire_state.terminal_outcome == "served",
)
@@ -655,30 +663,47 @@ class ModelHubTurnGateway:
await self._downstream_io(response.write_eof())
return response
- def _record_usage(
+ async def _record_usage(
self,
- resolved: ResolvedInvocation,
+ execution: _TurnExecution,
*,
usage: ProtocolUsageReport | None,
served: bool,
) -> None:
- """Fold one proxied turn into the usage ledger, best-effort.
+ """Fold one forwarded upstream call into the usage ledger, best-effort.
- A turn counts when it reached the model: either the hub returned upstream
+ A call 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
+ reported tokens billed us even when the stream ended in an error. Calls
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
+ This is the gateway's half of metering, and it covers exactly the calls
+ whose body the gateway forwards. A call the resolver consumed itself was
+ already metered by ``ModelHubService._meter_call``, so no call is counted
+ twice and none is missed.
+
+ Sole metering owner for the boundary. Several endings can reach it for one
+ forwarded call — a stream that finished and then failed to flush, a
+ disconnect that raced the terminal chunk — so the first ending to describe
+ it wins and every later one is a no-op. One call is one request, whatever
+ killed it.
+
+ The ledger read-modify-write is file I/O, so it runs off the event loop;
+ metering is a report, never a control input, and a ledger failure must not
change the turn the caller sees.
"""
+ resolved = execution.resolved
+ if execution.usage_recorded or resolved is None:
+ return
if not served and usage is None:
return
+ execution.usage_recorded = True
try:
- self.usage.record(
+ await asyncio.to_thread(
+ self.usage.record,
source_id=resolved.source_id,
model_id=resolved.model_id,
usage=usage,
@@ -727,6 +752,17 @@ class ModelHubTurnGateway:
*,
termination_origin: HandleTerminationOrigin,
) -> None:
+ # Ahead of the settlement guard: a downstream disconnect can arrive after
+ # the upstream already reported its tokens, so the turn was billed even
+ # though the chunk loop never reached its own metering call. The recorder
+ # is idempotent, so an ending that already metered costs nothing here.
+ wire_state = execution.wire_state
+ if wire_state is not None:
+ await self._record_usage(
+ execution,
+ usage=wire_state.usage,
+ served=wire_state.terminal_outcome == "served",
+ )
if execution.settlement_recorded:
return
_outcome, settlement = await self._settle_turn_handle(
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index 4670a5cec..bd278a1ab 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -1,9 +1,13 @@
"""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.
+Only the code that sees a complete upstream model response can count tokens, and
+one turn can make several upstream calls. Two callers therefore report calls here,
+over populations that ``InvokeHandle.stream is not None`` keeps disjoint: the
+resolver reports every call it consumed itself, including a failover hop that
+billed us before the turn moved on, and the turn gateway reports every call whose
+body it forwarded. This module owns what happens to those counts afterwards: one
+bounded daily aggregate per 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
@@ -16,6 +20,7 @@ usage.
from __future__ import annotations
import json
+import logging
import os
import tempfile
import threading
@@ -23,16 +28,20 @@ from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Final, Optional
+from .identifiers import MODEL_ID_MAX_LENGTH
from .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReport
+logger = logging.getLogger(__name__)
+
# 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
+# Identifiers reaching this module are already bounded where they are admitted;
+# the same bound is re-checked here so a hand-edited or corrupt file cannot grow
+# one row without limit. Source ids are hub-generated and shorter still.
+_MAX_IDENTIFIER_LENGTH: Final = MODEL_ID_MAX_LENGTH
_COUNTER_KEYS: Final = (
"requests",
@@ -72,6 +81,48 @@ def _identifier(value: object) -> Optional[str]:
return trimmed
+def _calendar_day(value: str) -> Optional[date]:
+ """Read one ISO calendar day, or None when the text is not a bare date."""
+
+ try:
+ return date.fromisoformat(value)
+ except ValueError:
+ return None
+
+
+def _instant(value: object) -> Optional[datetime]:
+ """Parse one persisted instant, or None when it is not an ISO date-time.
+
+ A bare date is a day, not an instant, and the date-time parser would read one
+ as midnight — inventing a time of day this ledger never wrote. The same parser
+ that recognizes the ``day`` key decides that here, so the module holds one
+ notion of what a day is.
+
+ A naive value is read as local time, the same calendar the day buckets use.
+ """
+
+ if not isinstance(value, str) or _calendar_day(value) is not None:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo is not None else parsed.astimezone()
+
+
+def _timestamp(value: object) -> Optional[str]:
+ """Read one persisted instant as text, dropping anything unparseable.
+
+ The read surface promises a date-time, so a corrupt or hand-edited value
+ degrades the field to absent rather than travelling out through the API.
+ """
+
+ text = _identifier(value)
+ if text is None or _instant(text) is None:
+ return None
+ return text
+
+
def _normalize_row(row: object) -> Optional[dict]:
"""Project one persisted row onto the current shape, or drop it."""
@@ -82,9 +133,7 @@ def _normalize_row(row: object) -> Optional[dict]:
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:
+ if _calendar_day(day) is None:
return None
normalized = {
"day": day,
@@ -92,8 +141,14 @@ def _normalize_row(row: object) -> Optional[dict]:
"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
+ # Cached input is a subset of input everywhere it is reported, so a file that
+ # claims otherwise is repaired on read instead of leaking out through a read
+ # surface that promises the subset.
+ normalized["cached_input_tokens"] = min(
+ normalized["cached_input_tokens"],
+ normalized["input_tokens"],
+ )
+ normalized["last_metered_at"] = _timestamp(row.get("last_metered_at"))
return normalized
@@ -111,15 +166,27 @@ def _accumulate(target: dict, row: dict) -> None:
def _newer_timestamp(current: Optional[str], candidate: Optional[str]) -> Optional[str]:
+ """Keep the later of two instants, comparing points in time.
+
+ Text order is not time order once two rows carry different UTC offsets, which
+ a state file merged across machines or an older release can hold.
+ """
+
if candidate is None:
return current
if current is None:
return candidate
- return max(current, candidate)
+ current_instant = _instant(current)
+ candidate_instant = _instant(candidate)
+ if current_instant is None:
+ return candidate
+ if candidate_instant is None:
+ return current
+ return candidate if candidate_instant > current_instant else current
class BoundedUsageLedger:
- """Persist served-turn token counts as a bounded daily aggregate."""
+ """Persist metered upstream-call token counts as a bounded daily aggregate."""
def __init__(
self,
@@ -152,9 +219,9 @@ class BoundedUsageLedger:
rows[_row_key(row)] = row
continue
_accumulate(existing, row)
- existing["last_served_at"] = _newer_timestamp(
- existing["last_served_at"],
- row["last_served_at"],
+ existing["last_metered_at"] = _newer_timestamp(
+ existing["last_metered_at"],
+ row["last_metered_at"],
)
return sorted(rows.values(), key=_row_key)
@@ -186,11 +253,19 @@ class BoundedUsageLedger:
usage: Optional[ProtocolUsageReport],
at: datetime,
) -> None:
- """Fold one served turn into its day's row."""
+ """Fold one metered upstream call 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:
+ # Unreachable for anything the hub admits: both boundaries that
+ # accept a model id bound it by the same constant. Loud rather than
+ # silent so a future boundary that forgets shows up as lost metering
+ # instead of as a quietly incomplete tab.
+ logger.warning(
+ "Model Hub usage metering skipped a turn with an unusable identifier",
+ extra={"source_id_usable": safe_source_id is not None},
+ )
return
increment = {
"day": local_usage_day(at).isoformat(),
@@ -201,7 +276,7 @@ class BoundedUsageLedger:
"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(),
+ "last_metered_at": at.isoformat(),
}
with self._lock:
rows = {_row_key(row): row for row in self._read()}
@@ -210,9 +285,9 @@ class BoundedUsageLedger:
rows[_row_key(increment)] = increment
else:
_accumulate(existing, increment)
- existing["last_served_at"] = _newer_timestamp(
- existing["last_served_at"],
- increment["last_served_at"],
+ existing["last_metered_at"] = _newer_timestamp(
+ existing["last_metered_at"],
+ increment["last_metered_at"],
)
retained = self._retained(list(rows.values()), local_usage_day(at))
self._write(retained)
@@ -250,14 +325,14 @@ class BoundedUsageLedger:
{
"source_id": row["source_id"],
**_empty_totals(),
- "last_served_at": None,
+ "last_metered_at": None,
"models": {},
},
)
_accumulate(source, row)
- source["last_served_at"] = _newer_timestamp(
- source["last_served_at"],
- row["last_served_at"],
+ source["last_metered_at"] = _newer_timestamp(
+ source["last_metered_at"],
+ row["last_metered_at"],
)
model = source["models"].setdefault(
row["model_id"],
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 10e6ad6cb..32e625431 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -44,7 +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. |
+| 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 call 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. |
@@ -992,10 +992,18 @@ 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
+The metered unit is one upstream call that reached the model, not one turn: a turn
+that failed over billed every hop that reported tokens, and each hop is counted
+against the Source it was made against. A call counts when the hub forwarded its
+output downstream or when upstream reported tokens for it, so a stream that died
+after its terminal frame and a buffered error that still billed us are both
+metered. A call that never reached the model is not, because the resolution feed
+and Source health already own that.
+
+`requests` is self-measured by hub code and is always present. Token counts are
+vendor-reported and may be absent for a served call — 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
+calls 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.
@@ -1003,7 +1011,10 @@ 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.
+count is informational only. The subset holds even when an upstream reports a cached
+count above the input it belongs to, or reports one without a readable input count:
+the merged cached count is bounded by the merged input count, and a persisted row
+that claims otherwise is repaired on read.
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
diff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.json
index e50738206..9bdf9f73f 100644
--- a/docs/plans/model-hub-contracts/usage-summary.schema.json
+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json
@@ -69,11 +69,11 @@
"properties": {
"requests": {
"$ref": "#/definitions/Count",
- "description": "Self-measured served turns. Always available."
+ "description": "Self-measured upstream calls that reached the model. One turn contributes more than one when it failed over. 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."
+ "description": "Metered calls whose upstream response carried a token report. Never greater than requests; a shortfall means missing reports, not zero usage."
},
"input_tokens": {
"$ref": "#/definitions/Count",
@@ -98,7 +98,7 @@
"input_tokens",
"cached_input_tokens",
"output_tokens",
- "last_served_at",
+ "last_metered_at",
"models"
],
"additionalProperties": false,
@@ -126,7 +126,8 @@
"output_tokens": {
"$ref": "#/definitions/Count"
},
- "last_served_at": {
+ "last_metered_at": {
+ "description": "When this Source last had a call metered, served or billed-and-failed.",
"type": ["string", "null"],
"format": "date-time"
},
@@ -226,7 +227,7 @@
"input_tokens": 148230,
"cached_input_tokens": 96010,
"output_tokens": 4120,
- "last_served_at": "2026-08-18T03:14:00+00:00",
+ "last_metered_at": "2026-08-18T03:14:00+00:00",
"models": [
{
"model_id": "claude-opus-4-6",
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index 06c4196e5..a8f0f721a 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -75,6 +75,28 @@ 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.
+The same rule decides the cached-input subset. `cached_input_tokens` is a part of
+`input_tokens`, so after merging every container and frame the cached count is
+bounded by the input count *this code normalized itself* — a bound we measured,
+never a total the response declared. Cached input reported without a readable input
+count is a subset of nothing and clamps to zero. `ProtocolUsageReport.of` is the one
+constructor that holds the invariant, and a persisted row that violates it (older
+release, hand edit) is repaired on read rather than travelling out through a read
+surface that promises the subset.
+
+Persisted instants get the same treatment: the read surface promises `date-time`, so
+a value that is not one degrades the field to absent instead of being published, and
+`last_metered_at` comparisons order two rows as *points in time* — text order is not
+time order once two rows carry different UTC offsets.
+
+Identifiers are bounded once, by `MODEL_ID_MAX_LENGTH` in `identifiers.py`, at both
+boundaries that admit a model ID (discovery and custom-model mapping) and again in
+the ledger. The ledger's re-check is unreachable for anything the hub admits, so it
+logs a warning rather than dropping silently: a future boundary that forgets the
+bound should show up as lost metering, not as a quietly incomplete tab. The bound is
+deliberately *not* applied when loading persisted config — per the persisted-shape
+rule, a legacy value must not make startup fail.
+
## Persisted shape
New state file `~/.avibe/state/model_hub_usage.json`, written through the same
@@ -98,7 +120,7 @@ owner. It can be added when a reader needs it.
"input_tokens": 148230,
"cached_input_tokens": 96010,
"output_tokens": 4120,
- "last_served_at": "2026-08-18T03:14:00+00:00"
+ "last_metered_at": "2026-08-18T03:14:00+00:00"
}
```
@@ -114,14 +136,39 @@ 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.
+**The metered unit is one upstream call, not one turn.** A turn that failed over
+made several calls, and each hop that reported tokens billed the Source it was made
+against — attributing all of them to the Source that finally served would both
+undercount the failing Source and misprice the serving one.
+
+A call is recorded when it reached the model: the hub forwarded its output
+downstream, or upstream reported tokens for it. The second half matters because a
+vendor that reported tokens billed us whether or not the response ended well — a
+stream that died after its terminal frame, or a buffered error carrying a usage
+block. A call that never reached the model (rejected credential, engine down) is
+not recorded: resolution events and source health already own that surface, and
+counting it here would duplicate the concept.
+
+Metering has **two owners over disjoint populations**, split by the one line that
+decides who can read a call's body — `handle.stream is not None` in
+`ModelHubService._invoke`:
+
+- `ModelHubService._meter_call` records every call the resolver consumed itself.
+ These have no body to forward, so the gateway never sees them, and for an error
+ the resolver may not even name that Source in what it raises.
+- `ModelHubTurnGateway._record_usage` records every call whose body the gateway
+ forwards, reading tokens from the buffered body or the live SSE wire state.
+
+Each call therefore reaches exactly one owner. Within the gateway, several endings
+can describe one forwarded call — a stream that finished and then failed to flush,
+a downstream disconnect that raced the terminal chunk — so the first ending to
+report wins and later ones are no-ops. A structure guard pins both owners and the
+gateway's idempotence flag.
+
+Both owners write through `asyncio.to_thread`: the ledger's read-modify-write is
+file I/O, and per `CLAUDE.md` §6 blocking work must not run on the controller event
+loop. Metering is a report, never a control input, so a ledger failure is logged and
+the call the caller sees is unchanged.
## Read surface
@@ -129,7 +176,7 @@ counting them here would duplicate that concept.
`[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`
+- `sources[]` — per source, with a `models[]` breakdown and `last_metered_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
@@ -141,7 +188,7 @@ route against a real server response.
- [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] Resolver and gateway recording over the two disjoint call populations
- [x] `ModelHubService.usage_summary` + RPC + `GET /api/models/usage`
- [x] Contract row, response registry entry, and usage schema
- [x] Unit and contract coverage
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 2aa95ba8f..c44a31d80 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import ast
import asyncio
import json
+import threading
from collections import deque
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -68,6 +69,7 @@ from core.handlers.model_hub.turn_gateway import (
_SSEWireState,
render_protocol_terminal_event,
)
+from core.handlers.model_hub.stream_wire import ProtocolUsageReport
from core.handlers.model_hub.usage import BoundedUsageLedger
from core.run_settlement import (
SETTLED_BY_NO_TERMINAL_RESULT,
@@ -1131,6 +1133,7 @@ def _outcome(
message: str | None = None,
source_id: str = "src_primary01",
stream_started: bool = False,
+ usage: ProtocolUsageReport | None = None,
) -> RawCallOutcome:
return RawCallOutcome(
kind=kind,
@@ -1140,6 +1143,7 @@ def _outcome(
stream_started=stream_started,
model_id="shared-model",
source_id=source_id,
+ usage=usage,
)
@@ -6250,6 +6254,278 @@ def test_gateway_meters_nothing_for_a_turn_that_never_reached_the_model(
asyncio.run(exercise())
+def test_a_surfaced_buffered_error_still_meters_the_tokens_it_billed(
+ tmp_path: Path,
+) -> None:
+ """The call never hands a body onward, so only the resolver can meter it."""
+
+ async def exercise() -> None:
+ source = _source("src_meterbuferr", "Surfaced billing")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ outcomes=[
+ _outcome(
+ RawOutcomeKind.HTTP_ERROR,
+ status=400,
+ code="invalid_request_error",
+ source_id=source.id,
+ usage=ProtocolUsageReport.of(
+ input_tokens=310,
+ cached_input_tokens=64,
+ output_tokens=0,
+ ),
+ )
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+
+ with pytest.raises(ModelHubError) as raised:
+ await service.resolve(
+ backend="codex",
+ model_id=requested_model,
+ request=ModelHubRequest(
+ {"model": requested_model, "input": "ping"},
+ protocol="openai_responses",
+ ),
+ supply_channel="hub",
+ )
+
+ assert raised.value.code == "upstream_request_invalid"
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1
+ assert metered["token_reports"] == 1
+ assert metered["input_tokens"] == 310
+ assert metered["cached_input_tokens"] == 64
+ assert metered["last_metered_at"] == NOW.isoformat()
+
+ asyncio.run(exercise())
+
+
+def test_a_billed_failover_hop_is_metered_against_the_source_that_billed_it(
+ tmp_path: Path,
+) -> None:
+ """Every hop that reported tokens billed its own Source, not the last one."""
+
+ async def exercise() -> None:
+ first = _source("src_meterhop001", "Billed hop")
+ second = _source("src_meterhop002", "Serving hop")
+ service = _service(
+ tmp_path,
+ sources=[first, second],
+ outcomes=[
+ _outcome(
+ RawOutcomeKind.HTTP_ERROR,
+ status=429,
+ code="rate_limit_error",
+ source_id=first.id,
+ usage=ProtocolUsageReport.of(
+ input_tokens=88,
+ cached_input_tokens=0,
+ output_tokens=0,
+ ),
+ ),
+ _outcome(
+ RawOutcomeKind.SUCCESS,
+ status=200,
+ source_id=second.id,
+ usage=ProtocolUsageReport.of(
+ input_tokens=120,
+ cached_input_tokens=0,
+ output_tokens=17,
+ ),
+ ),
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ service.store.config.agents["codex"].routes[requested_model] = ModelHubRouteConfig(
+ hops=(
+ ModelHubRouteHopConfig(first.id, "shared-model"),
+ ModelHubRouteHopConfig(second.id, "shared-model"),
+ )
+ )
+
+ resolved = await service.resolve(
+ backend="codex",
+ model_id=requested_model,
+ request=ModelHubRequest(
+ {"model": requested_model, "input": "ping"},
+ protocol="openai_responses",
+ ),
+ supply_channel="hub",
+ )
+
+ assert resolved.source_id == second.id
+ assert _usage_of(service, first.id)["input_tokens"] == 88
+ assert _usage_of(service, second.id)["input_tokens"] == 120
+ # One turn, two upstream calls: the unit is the call, so the total says so.
+ assert service.usage_summary(days=30)["totals"]["requests"] == 2
+
+ asyncio.run(exercise())
+
+
+def test_a_call_that_reached_no_model_is_never_metered(tmp_path: Path) -> None:
+ """A rejected credential billed nothing; source health already reports it."""
+
+ async def exercise() -> None:
+ source = _source("src_meterauth01", "Rejected")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ outcomes=[
+ _outcome(
+ RawOutcomeKind.HTTP_ERROR,
+ status=401,
+ code="authentication_error",
+ source_id=source.id,
+ )
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+
+ with pytest.raises(ModelHubError):
+ await service.resolve(
+ backend="codex",
+ model_id=requested_model,
+ request=ModelHubRequest(
+ {"model": requested_model, "input": "ping"},
+ protocol="openai_responses",
+ ),
+ supply_channel="hub",
+ )
+
+ assert service.usage_summary(days=30)["totals"]["requests"] == 0
+
+ asyncio.run(exercise())
+
+
+def test_a_downstream_disconnect_meters_the_terminal_frame_exactly_once(
+ tmp_path: Path,
+) -> None:
+ """The wire read the tokens before the write failed, so the turn was billed."""
+
+ async def exercise() -> None:
+ source = _source("src_meterdrop01", "Dropped client")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(
+ RawOutcomeKind.SUCCESS,
+ status=200,
+ source_id=source.id,
+ stream_started=True,
+ ),
+ (
+ b'event: response.completed\ndata: {"type":"response.completed",'
+ b'"sequence_number":1,"response":{"usage":{"input_tokens":512,'
+ b'"output_tokens":33}}}\n\n',
+ ),
+ )
+ ],
+ )
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_disconnect",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=True,
+ )
+ response = FakeStreamResponse(
+ write_error=ConnectionResetError("downstream write failed")
+ )
+
+ with patch(
+ "core.handlers.model_hub.turn_gateway.web.StreamResponse",
+ return_value=response,
+ ):
+ with pytest.raises(ConnectionError, match="downstream"):
+ await asyncio.wait_for(gateway._handle_request(request), timeout=1)
+
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1
+ assert metered["token_reports"] == 1
+ assert metered["input_tokens"] == 512
+ assert metered["output_tokens"] == 33
+
+ asyncio.run(exercise())
+
+
+def test_neither_metering_owner_writes_the_ledger_on_the_event_loop(
+ tmp_path: Path,
+) -> None:
+ """A ledger read-modify-write is file I/O; the controller loop must not wait."""
+
+ async def exercise() -> None:
+ recording_threads: list[int] = []
+
+ def capture(**_kwargs: object) -> None:
+ recording_threads.append(threading.get_ident())
+
+ resolver_source = _source("src_meterloop01", "Resolver owner")
+ resolver_service = _service(
+ tmp_path / "resolver",
+ sources=[resolver_source],
+ outcomes=[
+ _outcome(
+ RawOutcomeKind.SUCCESS,
+ status=200,
+ source_id=resolver_source.id,
+ usage=ProtocolUsageReport.of(
+ input_tokens=5,
+ cached_input_tokens=0,
+ output_tokens=1,
+ ),
+ )
+ ],
+ )
+ resolver_service.usage.record = capture
+ requested_model = _canonicalize_fixed_test_routes(resolver_service)["codex"]
+ await resolver_service.resolve(
+ backend="codex",
+ model_id=requested_model,
+ request=ModelHubRequest(
+ {"model": requested_model, "input": "ping"},
+ protocol="openai_responses",
+ ),
+ supply_channel="hub",
+ )
+
+ gateway_source = _source("src_meterloop02", "Gateway owner")
+ gateway_service = _service(
+ tmp_path / "gateway",
+ sources=[gateway_source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(
+ RawOutcomeKind.SUCCESS, status=200, source_id=gateway_source.id
+ ),
+ (json.dumps({"id": "resp", "usage": {"input_tokens": 9}}).encode(),),
+ )
+ ],
+ )
+ gateway_service.usage.record = capture
+ gateway_model = _canonicalize_fixed_test_routes(gateway_service)["codex"]
+ gateway = ModelHubTurnGateway(gateway_service)
+ await gateway._handle_request(
+ _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_offloop",
+ requested_model=gateway_model,
+ source_id=gateway_source.id,
+ stream=False,
+ )
+ )
+
+ assert len(recording_threads) == 2
+ assert threading.get_ident() not in recording_threads
+
+ 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."""
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 8528ecc21..aad476385 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -303,6 +303,19 @@ def _raw_outcome_constructors(tree: ast.AST) -> tuple[ast.Call, ...]:
)
+def _ledger_writes(tree: ast.AST) -> tuple[ast.Attribute, ...]:
+ """Every reference to the usage ledger's write, called or handed to a thread."""
+
+ return tuple(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Attribute)
+ and node.attr == "record"
+ and isinstance(node.value, ast.Attribute)
+ and node.value.attr == "usage"
+ )
+
+
def _auth_status_branch(node: ast.AST) -> bool:
if not isinstance(node, ast.Compare):
return False
@@ -505,6 +518,40 @@ def test_protocol_outcome_owner_guard_rejects_each_bypassed_kind() -> None:
) == 1
+def test_usage_metering_has_one_owner_per_call_population() -> None:
+ # Review 4958923279 finding 3: a turn can make several upstream calls, and the
+ # gateway only ever sees the one whose body it forwards. Metering therefore has
+ # two owners over populations split by ``handle.stream is not None``, and a
+ # third write anywhere — or a second caller of either owner — would double
+ # count or silently drop a billed call.
+ service_tree = _tree(SERVICE)
+ gateway_tree = _tree(TURN_GATEWAY)
+ owners = (
+ _functions(service_tree)["_meter_call"],
+ _functions(gateway_tree)["_record_usage"],
+ )
+ writes = _ledger_writes(service_tree) + _ledger_writes(gateway_tree)
+ assert writes
+ assert all(any(write in set(ast.walk(owner)) for owner in owners) for write in writes)
+ invoke = _functions(service_tree)["_invoke"]
+ meter_calls = [
+ node for node in ast.walk(service_tree) if _call_name(node) == "_meter_call"
+ ]
+ assert len(meter_calls) == 1
+ assert meter_calls[0] in set(ast.walk(invoke))
+ # Any of the gateway's endings may report the forwarded call, so exactly-once
+ # rests on its idempotence flag; a caller that pre-checks or clears the flag
+ # would move that decision outside the owner.
+ recorder = _functions(gateway_tree)["_record_usage"]
+ flags = [
+ node
+ for node in ast.walk(gateway_tree)
+ if isinstance(node, ast.Attribute) and node.attr == "usage_recorded"
+ ]
+ assert flags
+ assert all(flag in set(ast.walk(recorder)) for flag in flags)
+
+
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 4bdddd4c8..50fd3ca3b 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -13,6 +13,7 @@ settlement scaffolding it depends on.
from __future__ import annotations
import json
+import logging
import os
import stat
from datetime import date, datetime, timedelta, timezone
@@ -20,6 +21,7 @@ from pathlib import Path
import pytest
+from core.handlers.model_hub.identifiers import MODEL_ID_MAX_LENGTH
from core.handlers.model_hub.stream_wire import (
PROTOCOL_STREAM_TAXONOMY,
USAGE_TOKEN_CEILING,
@@ -270,6 +272,73 @@ def test_a_composed_input_total_cannot_exceed_our_own_ceiling() -> None:
assert report.cached_input_tokens == USAGE_TOKEN_CEILING
+ "reported_input,reported_cached,expected_cached",
+ [
+ pytest.param(100, 4096, 100, id="cached-above-input"),
+ pytest.param(0, 4096, 0, id="cached-without-input"),
+ pytest.param(4096, 4096, 4096, id="fully-cached"),
+ ],
+)
+def test_cached_input_never_exceeds_the_input_it_is_a_part_of(
+ reported_input: int,
+ reported_cached: int,
+ expected_cached: int,
+) -> None:
+ """The subset the read contract promises is bounded by our own input count."""
+
+ report = extract_protocol_usage(
+ "openai_responses",
+ {
+ "usage": {
+ "input_tokens": reported_input,
+ "input_tokens_details": {"cached_tokens": reported_cached},
+ "output_tokens": 7,
+ }
+ },
+ )
+
+ assert report == ProtocolUsageReport(
+ input_tokens=reported_input,
+ cached_input_tokens=expected_cached,
+ output_tokens=7,
+ )
+
+
+def test_the_subset_holds_when_two_frames_each_win_one_field() -> None:
+ """Per-field max can compose a cached count larger than its own input."""
+
+ usage = _observed(
+ "openai_responses",
+ {
+ "type": "response.in_progress",
+ "response": {
+ "usage": {
+ "input_tokens": 10,
+ "input_tokens_details": {"cached_tokens": 8},
+ "output_tokens": 1,
+ }
+ },
+ },
+ {
+ "type": "response.completed",
+ "response": {
+ "usage": {
+ "input_tokens": 12,
+ "input_tokens_details": {"cached_tokens": 4096},
+ "output_tokens": 3,
+ }
+ },
+ },
+ )
+
+ assert usage == ProtocolUsageReport(
+ input_tokens=12,
+ cached_input_tokens=12,
+ output_tokens=3,
+ )
+
+
@pytest.mark.parametrize(
"payload",
[
@@ -313,7 +382,7 @@ def test_records_fold_into_one_row_per_day_source_and_model(tmp_path: Path) -> N
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()
+ assert rows[0]["last_metered_at"] == (NOW + timedelta(hours=1)).isoformat()
def test_a_turn_without_a_report_counts_the_request_only(tmp_path: Path) -> None:
@@ -490,6 +559,103 @@ def test_a_row_with_unusable_counters_loads_as_zero(tmp_path: Path) -> None:
assert row["output_tokens"] == USAGE_TOKEN_CEILING
+ "persisted",
+ [
+ pytest.param("yesterday", id="not-a-datetime"),
+ pytest.param("2026-07-23", id="date-only"),
+ pytest.param("", id="empty"),
+ pytest.param(1753272000, id="epoch-number"),
+ ],
+)
+def test_an_unparseable_instant_degrades_to_absent(tmp_path: Path, persisted: object) -> None:
+ """The read surface promises a date-time, so a corrupt value never travels."""
+
+ 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": 1,
+ "last_metered_at": persisted,
+ }
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ row = ledger.window(days=30, now=NOW)[0]
+ assert row["requests"] == 1
+ assert row["last_metered_at"] is None
+
+
+def test_the_later_instant_wins_even_when_its_text_sorts_first(tmp_path: Path) -> None:
+ """Text order is not time order once two rows carry different offsets."""
+
+ earlier = datetime(2026, 7, 23, 20, 0, tzinfo=timezone(timedelta(hours=8)))
+ later = datetime(2026, 7, 23, 13, 0, tzinfo=timezone.utc)
+ assert later.isoformat() < earlier.isoformat() and later > earlier
+
+ ledger = _ledger(tmp_path)
+ day = local_usage_day(NOW).isoformat()
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ ledger.path.write_text(
+ json.dumps(
+ [
+ {
+ "day": day,
+ "source_id": "src_a",
+ "model_id": "model-x",
+ "requests": 1,
+ "last_metered_at": earlier.isoformat(),
+ },
+ {
+ "day": day,
+ "source_id": "src_a",
+ "model_id": "model-x",
+ "requests": 1,
+ "last_metered_at": later.isoformat(),
+ },
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ assert ledger.window(days=30, now=NOW)[0]["last_metered_at"] == later.isoformat()
+
+
+def test_a_persisted_cached_count_above_its_input_is_repaired_on_read(tmp_path: Path) -> None:
+ """The subset invariant is a read-surface promise, not only a wire check."""
+
+ 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": 1,
+ "token_reports": 1,
+ "input_tokens": 120,
+ "cached_input_tokens": 900,
+ "output_tokens": 4,
+ }
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ row = ledger.window(days=30, now=NOW)[0]
+ assert row["input_tokens"] == 120
+ assert row["cached_input_tokens"] == 120
+
+
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."""
@@ -528,19 +694,35 @@ def test_accumulated_counters_stop_at_the_ceiling(tmp_path: Path) -> None:
[
pytest.param("", "model-x", id="empty-source"),
pytest.param(" ", "model-x", id="blank-source"),
- pytest.param("src_a", "m" * 500, id="oversized-model"),
+ pytest.param("src_a", "m" * (MODEL_ID_MAX_LENGTH + 1), id="oversized-model"),
],
)
def test_an_unusable_identifier_is_never_persisted(
tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
source_id: str,
model_id: str,
) -> None:
+ """Loud, not silent: a dropped turn is lost metering, not a tidy no-op."""
+
ledger = _ledger(tmp_path)
- ledger.record(source_id=source_id, model_id=model_id, usage=None, at=NOW)
+ with caplog.at_level(logging.WARNING, logger="core.handlers.model_hub.usage"):
+ ledger.record(source_id=source_id, model_id=model_id, usage=None, at=NOW)
assert ledger.window(days=30, now=NOW) == []
+ assert [record.levelno for record in caplog.records] == [logging.WARNING]
+
+
+def test_the_longest_admissible_model_id_is_still_metered(tmp_path: Path) -> None:
+ """One constant bounds admission and metering, so neither can drop the other's."""
+
+ ledger = _ledger(tmp_path)
+ longest = "m" * MODEL_ID_MAX_LENGTH
+
+ ledger.record(source_id="src_a", model_id=longest, usage=None, at=NOW)
+
+ assert [row["model_id"] for row in ledger.window(days=30, now=NOW)] == [longest]
def test_the_ledger_file_is_owner_only(tmp_path: Path) -> None:
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index 118737718..81708cee3 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -25,6 +25,7 @@ from core.handlers.model_hub.stream_wire import (
ErrorEnvelopePath,
ProtocolObservation,
ProtocolSSEState,
+ ProtocolUsageReport,
SSE_MAX_FRAME_BYTES,
SSE_MAX_PRELUDE_BYTES,
SSEFrameLimitError,
@@ -301,6 +302,7 @@ class EngineClient:
error_payload=payload,
error_envelope_paths=observed_payload.error_envelope_paths,
message=f"upstream returned HTTP {response.status}",
+ usage=observed_payload.usage,
),
source=source,
model_id=model_id,
@@ -784,7 +786,13 @@ def _reduce_protocol_observation(
http_status: int | None,
stream_started: bool,
) -> RawCallOutcome | None:
- """Sole conversion from protocol observations to runtime call outcomes."""
+ """Sole conversion from protocol observations to runtime call outcomes.
+
+ Every branch carries the observation's token report onward, including the
+ error ones: a vendor that reported tokens billed for them whether or not the
+ response ended well, and this is the only hop where a call that settles
+ without ever handing its body downstream can still report them.
+ """
if observation is None or observation.outcome is None:
return None
@@ -795,6 +803,7 @@ def _reduce_protocol_observation(
model_id=model_id,
http_status=http_status,
stream_started=stream_started,
+ usage=observation.usage,
)
if observation.outcome == "failed_terminal":
error_type, error_code, candidates = _raw_error_fields(
@@ -811,6 +820,7 @@ def _reduce_protocol_observation(
error_candidates=candidates,
message=observation.message or "upstream returned a protocol error event",
stream_started=stream_started,
+ usage=observation.usage,
)
return _outcome(
kind=RawOutcomeKind.PROTOCOL_ERROR,
@@ -819,6 +829,7 @@ def _reduce_protocol_observation(
http_status=http_status,
message=observation.message or "upstream emitted invalid protocol data",
stream_started=stream_started,
+ usage=observation.usage,
)
@@ -885,6 +896,7 @@ def _outcome(
error_candidates: tuple[str, ...] = (),
message: str | None = None,
stream_started: bool = False,
+ usage: ProtocolUsageReport | None = None,
) -> RawCallOutcome:
return RawCallOutcome(
kind=kind,
@@ -896,6 +908,7 @@ def _outcome(
source_id=source.source_id,
error_type=error_type,
error_candidates=error_candidates,
+ usage=usage,
)