Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): stop clamping metered usage aggregates (#2093)
Call White46290120f516
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.pyindex b25e25774..f072a76d7 100644--- a/core/handlers/model_hub/stream_wire.py+++ b/core/handlers/model_hub/stream_wire.py@@ -374,7 +374,17 @@ 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+#+# It bounds ONE report, which is what the name has to say, because the scope is+# the whole argument for the number. No request composes a billion input tokens,+# so a single response past this is broken or hostile and dropping it costs+# nothing true. An aggregate of many accepted reports is a different quantity+# with no upper bound worth inventing — a user may spend whatever they spend —+# and this ceiling was once reused there, where it silently truncated real usage+# into a plausible-looking total. What an aggregate needs is+# `usage.USAGE_COUNTER_CEILING`: a statement about what the read contract can+# carry, not about what a count is allowed to be.+USAGE_REPORT_TOKEN_CEILING: Final = 1_000_000_000@dataclass(frozen=True)@@ -781,12 +791,12 @@ def _usage_sum(container: Mapping[str, object], paths: tuple[tuple[str, ...], ..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:+ if value < 0 or value > USAGE_REPORT_TOKEN_CEILING:continuetotal = value if total is None else total + valueif total is None:return None- return min(total, USAGE_TOKEN_CEILING)+ return min(total, USAGE_REPORT_TOKEN_CEILING)def extract_protocol_usage(@@ -830,10 +840,10 @@ def _usage_from_scalar_paths(value = scalars.get((*container_path, *path))if not isinstance(value, int) or isinstance(value, bool):continue- if value < 0 or value > USAGE_TOKEN_CEILING:+ if value < 0 or value > USAGE_REPORT_TOKEN_CEILING:continuetotal = value if total is None else total + value- return None if total is None else min(total, USAGE_TOKEN_CEILING)+ return None if total is None else min(total, USAGE_REPORT_TOKEN_CEILING)input_tokens = usage_sum(taxonomy.input_paths)cached_input_tokens = usage_sum(taxonomy.cached_input_paths)diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex 672739503..4732bdb54 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -15,6 +15,14 @@ why `token_reports` is tracked separately instead of treating a missing report azero usage. And nothing here ever feeds admission, routing, or cooldown — ahostile upstream must not be able to change resolution behavior by lying aboutusage.++What "bounded" bounds is the file: a fixed number of daily rows over a fixed+retention window, each carrying counters the settings page can still read back+exactly. It was never a bound on the counts themselves — how much a user spends+is not ours to cap — so every aggregate here is an exact sum, and+`USAGE_COUNTER_CEILING` constrains only what crosses into the file and back out+of it. A row carrying a counter past it is dropped at whichever door it reaches,+loudly, rather than rewritten into a number nobody spent."""from __future__ import annotations@@ -33,7 +41,7 @@ from typing import Callable, Final, Mapping, Optional, Sequencefrom .identifiers import persisted_ledger_key, usage_ledger_keyfrom .state_file import write_state_document-from .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReport+from .stream_wire import ProtocolUsageReportlogger = logging.getLogger(__name__)@@ -42,8 +50,54 @@ logger = logging.getLogger(__name__)USAGE_RETENTION_DAYS: Final = 62USAGE_MAX_ROWS: Final = 400USAGE_DEFAULT_WINDOW_DAYS: Final = 30-# Anything older than every instant this ledger can hold, so a row that never-# recorded one sorts as the least recently metered.+# The largest integer the settings page holds exactly. Nothing on this side of the+# wire needs it: `json.loads` reads a counter of any size into an exact `int`, and+# so do the rpc and client hops. The doubles appear one boundary later, in the+# browser parsing the published summary, and this is the only number in the module+# that comes from there — which is worth saying plainly, because calling it a+# property of the file is what made it look reusable as a bound on a sum.+#+# It is applied at the file's doors because that is where a value can still be+# refused. A published aggregate is a sum, and refusing a sum is the defect this+# module was fixed for; admitting a row only up to this instead bounds every+# published count at `USAGE_MAX_ROWS` times it, a range the consumer holds as a+# finite double and the contract can therefore declare and satisfy — with no+# ceiling anywhere on how much a user may spend.+#+# Deliberately not the per-report ceiling, and nothing between the two doors+# clamps to it. Nothing this module writes can approach it either: a window spans+# at most `USAGE_RETENTION_DAYS` days of calls each bounded by+# `stream_wire.USAGE_REPORT_TOKEN_CEILING`, so what it actually guards is a corrupt+# or hand-edited file. There it drops the row rather than saturating it: a+# saturated counter is a number nobody spent, and saturating a subset with its+# superset forces a cached-input share to exactly 100% — the artifact this module+# exists to not produce.+USAGE_COUNTER_CEILING: Final = 2**53 - 1+# The largest count `summary` can publish, and the maximum+# `usage-summary.schema.json` declares. Derived rather than imposed: a published+# count is a sum over one window, `window` reports at most `USAGE_MAX_ROWS` rows,+# and no row reaches it carrying a counter past `USAGE_COUNTER_CEILING` — not from+# the file, where `_counter` clears each one, and not from a merge, which `_read`+# re-checks because a sum of cleared addends is not itself cleared.+#+# Both capacities binding the reported set is what makes the product a bound on+# what this module can publish, rather than a description of the files it happens+# to write. Deriving it from the write path alone was true of every file this+# ledger produces and false of every other one — a reader handed a larger file+# published a total above its own contract.+#+# Saying it out loud is what lets the contract carry a maximum that is both true+# and satisfiable; the two things tried before were a maximum the producer could+# violate, and none at all, which left a consumer nothing to size against and said+# nothing about where exactness ends. Never a clamp: it states the range, and+# nothing compares a sum against it. Every value in the range is a finite double,+# only the part above `USAGE_COUNTER_CEILING` rounds, and reaching that at all+# takes a corrupt file — a window spans at most `USAGE_RETENTION_DAYS` days of+# real calls.+USAGE_PUBLISHED_COUNT_BOUND: Final = USAGE_MAX_ROWS * USAGE_COUNTER_CEILING+# Anything older than every instant this ledger can hold, so a row whose recency+# cannot be read — it recorded no instant, or recorded one that has not happened —+# sorts as the least recently metered._OLDEST_INSTANT: Final = datetime.min.replace(tzinfo=timezone.utc)_COUNTER_KEYS: Final = (@@ -115,14 +169,36 @@ def local_usage_day(moment: datetime) -> date:return _aware(moment).astimezone().date()-def _bounded_counter(value: object) -> int:- """Read one persisted counter, degrading anything unusable to zero."""+def _counter(value: object) -> Optional[int]:+ """Read one persisted counter, or None when its whole row is unreadable.++ Two unusable shapes, two answers, because they cost different things. A value+ that is not a count — not an integer, a bool, negative — carries no magnitude,+ and zero is the one substitute that claims none either: it is the identity of+ every sum this module performs, so the rest of the row still reports what it+ does know.++ A value above `USAGE_COUNTER_CEILING` is the opposite problem. It carries a+ magnitude no published document could carry to its reader, so every substitute+ invents one in its place, and an+ invented counter that large dominates whatever aggregate it enters; saturating+ it would additionally hand a subset and its superset the same number and force+ a cached-input share to exactly 100%. So that row is not read at all. It is+ dropped and counted with every other unusable row, and the next write is what+ takes it out of the file.++ No reading of a real count is refused here: the ceiling is a property of the+ consumer, and `_write` is what keeps this module from ever persisting a counter+ past it.+ """if not isinstance(value, int) or isinstance(value, bool):return 0if value < 0:return 0- return min(value, USAGE_TOKEN_CEILING)+ if value > USAGE_COUNTER_CEILING:+ return None+ return valuedef _text(value: object) -> Optional[str]:@@ -218,11 +294,17 @@ def _normalize_row(row: object) -> Optional[dict]:calendar_day = _calendar_day(day)if calendar_day is None:return None+ counters: dict[str, int] = {}+ for key in _COUNTER_KEYS:+ counter = _counter(row.get(key))+ if counter is None:+ return None+ counters[key] = counternormalized = {"day": calendar_day.isoformat(),"source_id": source_id,"model_id": model_id,- **{key: _bounded_counter(row.get(key)) for key in _COUNTER_KEYS},+ **counters,}for subset, superset in _COUNTER_SUBSETS:normalized[subset] = min(normalized[subset], normalized[superset])@@ -281,16 +363,42 @@ def _keyed_identities(return sources, models-def _recency(row: dict) -> tuple[str, datetime]:+def _recency(row: dict, ceiling: datetime) -> tuple[str, datetime]:"""Order rows oldest-metered first, so the bound evicts what costs least.Ordering by key instead would evict by spelling: an early-sorting model wouldbe recreated and evicted again on every write while later-sorting stale rowssurvived, so its usage could never accumulate. Instants are compared as pointsin time — text order is not time order once two rows carry different offsets.++ An instant later than `ceiling` is not a recency at all. Nothing was metered+ after the reading the caller just took, so such a row is not the set's most+ recently used one — it is one whose recency cannot be read, which is the case+ `_OLDEST_INSTANT` already answers for a row that recorded no instant. It gets+ the same answer, and not because a corrupt row deserves to lose: a row this+ ordering cannot place is the only row it can evict without discarding usage it+ can account for.++ Bounding it to `ceiling` instead is not enough, which is worth stating because+ it is the obvious remedy. That makes the row as recent as the reading, so it+ still outranks every row metered before it and still evicts real usage; it+ narrows the lie without changing who pays for it. Placing the bound here at all+ — rather than leaving it to whoever assembled the rows — is what stops this from+ recurring: `_retained` keeps a future instant out of the file, and each time+ that was the only place it happened, the report path ordered by the raw value.++ The day is a different question and is deliberately not answered here. A row+ dated after today reports nothing to anybody, so it does not belong in the set+ at all; ranking it as though it were today's would still let it evict a real+ row. Membership is each caller's own filter — a retention window on the way in,+ the requested window on the way out — and the one caller that had neither is the+ defect this ordering keeps being handed."""- return (row["day"], _instant(row["last_metered_at"]) or _OLDEST_INSTANT)+ metered = _instant(row["last_metered_at"])+ if metered is None or metered > ceiling:+ return (row["day"], _OLDEST_INSTANT)+ return (row["day"], metered)def _row_key(row: dict) -> tuple[str, str, str]:@@ -302,8 +410,27 @@ def _empty_totals() -> dict:def _accumulate(target: dict, row: dict) -> None:+ """Add one row's counters into an aggregate, exactly.++ Nothing is clamped here, and that absence is the point. Every addend already+ passed the door that bounds it — a live report at+ `stream_wire.USAGE_REPORT_TOKEN_CEILING`, a persisted one at+ `USAGE_COUNTER_CEILING` — so a ceiling on the sum would no longer protect the+ aggregate from a hostile upstream. It would cap how much usage the user is+ allowed to have had, and it read as exactly that: a truncated total is+ indistinguishable from a real one, and clamping a subset and its superset+ independently drove every cached-input share to exactly 100% once either+ saturated, which presents a broken number as perfect caching.++ Two callers persist what they accumulate — the duplicate-key merge in `_read`+ and the fold in `record_many` — and neither makes a bound belong here. A sum+ that outgrows the file is a fact about the file, so `_write` answers it, for+ every writer at once and without a published aggregate ever being quietly+ reduced to keep a row writable.+ """+for key in _COUNTER_KEYS:- target[key] = min(target[key] + row[key], USAGE_TOKEN_CEILING)+ target[key] += row[key]def _newer_timestamp(current: Optional[str], candidate: Optional[str]) -> Optional[str]:@@ -346,6 +473,33 @@ class BoundedUsageLedger:self._now = nowself._lock = threading.RLock()+ def _within_capacity(self, rows: list[dict], *, measured: datetime) -> list[dict]:+ """Return at most `max_rows` of these rows, evicting the least recently metered.++ `_recency` orders by day first, so this may only be handed rows that are+ already reportable. Given a future-dated row it does the opposite of its+ job: that row outranks every real one, survives, and then reads refuse it+ — which is the defect `_retained` exists to close, and which reappeared+ the one time this was called on rows straight out of the file.++ So the two callers are the two places a reportable set is formed, and+ neither is the parse. `_write` calls it on rows `_retained` has already+ placed inside the ledger's own day window; `window` calls it on rows it+ has already filtered to the requested one. Both keep the same survivors+ in the same order.++ `measured` is what those two filters cannot supply: the day they bound is+ only the first half of the order, and an instant inside today can still be+ one no clock has reached. It is the reading each caller already took for its+ own window, so the eviction and the placement answer to one clock — and on+ the write path it changes nothing, because `_retained` has already brought+ every instant back under it.+ """++ if len(rows) <= self.max_rows:+ return rows+ return sorted(rows, key=lambda row: _recency(row, measured))[-self.max_rows :]+def _read(self) -> list[dict]:if not self.path.exists():return []@@ -387,10 +541,56 @@ class BoundedUsageLedger:logger.warning("Model Hub usage ledger %s dropped %d unusable row(s)", self.path, dropped)- return sorted(rows.values(), key=_row_key)+ # A merge builds a counter no row in the file carried. `_counter` cleared+ # each addend, and their sum can still land past the ceiling — only a+ # file holding duplicate keys reaches this, which is one this ledger never+ # wrote. Same answer as every other door, for the same reason: a row whose+ # magnitude no published document could carry is dropped, not saturated.+ held = []+ for row in rows.values():+ if all(row[key] <= USAGE_COUNTER_CEILING for key in _COUNTER_KEYS):+ held.append(row)+ continue+ logger.warning(+ "Model Hub usage ledger %s dropped row %s: merged counters outgrew "+ "what the file can carry",+ self.path,+ _row_key(row),+ )+ return sorted(held, key=_row_key)++ def _write(self, rows: list[dict], *, measured: datetime) -> None:+ """Persist the rows the file can hold, at both of the capacities it has.++ `max_rows` is one, and `_within_capacity` is where it is applied for this+ door and for `window` together — holding it here alone is what let a larger+ file be read back and published whole. The other capacity is what a stored+ counter may be without putting the published document out of the+ range its reader holds exactly, and it needs the same door for a reason+ the exact merges upstream make unavoidable: folding an increment onto a row+ near the ceiling, or merging two duplicate-keyed rows a corrupt file holds,+ can produce a counter past it. Persisting that would put the loss somewhere+ worse than here — the next read would find a row it cannot use, and the+ usage would go missing with nothing having said so.++ So the row stops where it stops fitting, once, with its identity in the+ log. That is also what heals the file: a bucket whose stored counters were+ never real disappears instead of saturating, and the next call recorded+ against it starts a row that means what it says.+ """- def _write(self, rows: list[dict]) -> None:- retained = sorted(rows, key=_recency)[-self.max_rows :]+ holdable: list[dict] = []+ for row in rows:+ if all(row[key] <= USAGE_COUNTER_CEILING for key in _COUNTER_KEYS):+ holdable.append(row)+ continue+ logger.warning(+ "Model Hub usage ledger %s dropped row %s: counters outgrew what the "+ "file can carry",+ self.path,+ _row_key(row),+ )+ retained = self._within_capacity(holdable, measured=measured)write_state_document(self.path, sorted(retained, key=_row_key))def record(@@ -492,7 +692,7 @@ class BoundedUsageLedger:if not folded:returnretained = self._retained(list(rows.values()), persisted_at)- self._write(retained)+ self._write(retained, measured=persisted_at)def _retained(self, rows: list[dict], measured: datetime) -> list[dict]:"""Keep the rows this ledger's own clock can place, bounded at both edges.@@ -538,7 +738,26 @@ class BoundedUsageLedger:last_day = today.isoformat()with self._lock:rows = self._read()- return [row for row in rows if first_day <= row["day"] <= last_day]+ placed = [row for row in rows if first_day <= row["day"] <= last_day]+ # The reportable set is formed here, so this is where the file's row+ # capacity bounds what `summary` can publish — after the date filter, never+ # before it. Every row left is one a reader can see, which is the condition+ # `_within_capacity` needs to evict the right one.+ #+ # `_write` never emits more rows than the file holds, so reaching this at+ # all means reading a file this ledger did not write. That is worth saying+ # once, unlike eviction on the write path, which is retention working as+ # designed and happens constantly.+ held = self._within_capacity(placed, measured=_aware(now))+ if len(held) < len(placed):+ logger.warning(+ "Model Hub usage ledger %s held %d reportable row(s) over its "+ "capacity of %d; dropped the least recently metered",+ self.path,+ len(placed) - len(held),+ self.max_rows,+ )+ return sorted(held, key=_row_key)def summary(self,diff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.jsonindex 58a5841a2..7e4c8b2ec 100644--- a/docs/plans/model-hub-contracts/usage-summary.schema.json+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json@@ -52,9 +52,10 @@"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"},"Count": {+ "description": "One metered count: the exact sum of the per-call reports inside the window, each already bounded where it entered the wire. Never clamped to keep it small — a truncated total is indistinguishable from a real one, and clamping a subset and its superset together forces a ratio such as a cached-input share to exactly 100%. The maximum is derived from the producer rather than imposed on the user, and caps nobody's spending: a count is a sum over at most 400 rows (USAGE_MAX_ROWS), each carrying counters of at most 2^53 - 1 (USAGE_COUNTER_CEILING). Both limits are applied when the store is read as well as when it is written, so the bound holds for a corrupt or hand-edited store too and not only for one this producer wrote. A consumer reading this document into IEEE-754 doubles holds every value up to 2^53 - 1 exactly and every larger one as a finite double, rounded in its last places; a window spans at most 62 days of real calls, so only a corrupt or hand-edited store can publish a count in that rounding range.","type": "integer","minimum": 0,- "maximum": 1000000000+ "maximum": 3602879701896396400},"Counters": {"type": "object",diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex b18211f7e..742e4dfc0 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -595,6 +595,33 @@ def test_source_client_nonce_round_trips_and_is_unique():ModelHubConfig.from_payload(duplicate.to_payload())+def test_the_usage_count_maximum_is_the_bound_the_producer_can_prove():+ """The contract's ceiling on a count has to be one the producer cannot exceed.++ It is a product of two limits that already exist — how many rows the file+ keeps, and how large a counter it admits — so a change to either silently+ moves what the producer can publish. Asserting the derivation here is what+ keeps the declared maximum from drifting into one of the two shapes this+ contract has already been through: a bound the producer could violate, and no+ bound at all.++ Nothing clamps to it. It states the range, it does not enforce one.+ """++ from core.handlers.model_hub.usage import (+ USAGE_COUNTER_CEILING,+ USAGE_MAX_ROWS,+ USAGE_PUBLISHED_COUNT_BOUND,+ )++ count = _schema("usage-summary.schema.json")["definitions"]["Count"]+ assert USAGE_PUBLISHED_COUNT_BOUND == USAGE_MAX_ROWS * USAGE_COUNTER_CEILING+ assert count["maximum"] == USAGE_PUBLISHED_COUNT_BOUND+ assert count["minimum"] == 0+ # A finite double, so no consumer of this document can be handed an Infinity.+ assert float(USAGE_PUBLISHED_COUNT_BOUND) < float("inf")++def test_every_frozen_schema_example_is_valid_and_json_round_trips():for path in sorted(CONTRACTS.glob("*.schema.json")):schema = json.loads(path.read_text(encoding="utf-8"))diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex 0f7aadaf8..7890408ca 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -37,7 +37,7 @@ from core.handlers.model_hub.identifiers import ()from core.handlers.model_hub.stream_wire import (PROTOCOL_STREAM_TAXONOMY,- USAGE_TOKEN_CEILING,+ USAGE_REPORT_TOKEN_CEILING,ProtocolSSEState,ProtocolUsageReport,extract_protocol_usage,@@ -45,6 +45,10 @@ from core.handlers.model_hub.stream_wire import (observe_protocol_response,)from core.handlers.model_hub.usage import (+ USAGE_COUNTER_CEILING,+ USAGE_DEFAULT_WINDOW_DAYS,+ USAGE_MAX_ROWS,+ USAGE_PUBLISHED_COUNT_BOUND,USAGE_RETENTION_DAYS,BoundedUsageLedger,SourceIdentity,@@ -331,7 +335,7 @@ def test_a_buffered_error_still_carries_the_tokens_it_billed() -> None: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"),+ pytest.param(USAGE_REPORT_TOKEN_CEILING + 1, id="above-ceiling"),],)def test_an_unusable_token_value_is_dropped_not_coerced(reported: object) -> None:@@ -352,16 +356,16 @@ def test_a_composed_input_total_cannot_exceed_our_own_ceiling() -> None:"anthropic",{"usage": {- "input_tokens": USAGE_TOKEN_CEILING,- "cache_read_input_tokens": USAGE_TOKEN_CEILING,+ "input_tokens": USAGE_REPORT_TOKEN_CEILING,+ "cache_read_input_tokens": USAGE_REPORT_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+ assert report.input_tokens == USAGE_REPORT_TOKEN_CEILING+ assert report.cached_input_tokens == USAGE_REPORT_TOKEN_CEILING@pytest.mark.parametrize(@@ -614,6 +618,374 @@ def test_the_row_cap_keeps_the_newest_rows(tmp_path: Path) -> None:assert [row["model_id"] for row in persisted] == ["model-3", "model-4", "model-5"]+def test_the_row_cap_holds_when_reporting_a_file_that_overflows_it(+ tmp_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ """Review 5266689271: a file may hold more rows than the writer would emit.++ `max_rows` used to be applied in `_write` only, which bounds every file this+ ledger produces and no other one. A store that was corrupted, hand-edited, or+ written by a different version was read back whole, so the window it published+ was not bounded by anything the contract could name.++ The bound belongs on the reportable set rather than on the parse — see+ `test_the_row_cap_never_evicts_a_reportable_row_for_a_future_dated_one` for+ what applying it to raw rows costs.++ The stamps here are all in the past, which is what distinguishes this from+ `test_the_row_cap_ranks_an_unmeasurable_instant_as_the_least_recent`: the+ ordering can read every one of them, so it evicts by age.+ """++ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ overflow = [+ {+ "day": local_usage_day(NOW).isoformat(),+ "source_id": "src_a",+ "model_id": f"model-{index:03d}",+ "requests": 1,+ "input_tokens": 1,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": (NOW - timedelta(seconds=5 - index)).isoformat(),+ }+ for index in range(5)+ ]+ path.write_text(json.dumps(overflow), encoding="utf-8")++ ledger = BoundedUsageLedger(path, max_rows=3)+ with caplog.at_level(logging.WARNING):+ held = ledger.window(days=30, now=NOW)++ # The survivors are the ones `_write` would have kept, in the same order.+ assert [row["model_id"] for row in held] == ["model-002", "model-003", "model-004"]+ assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == 3+ assert "over its capacity of 3" in caplog.text+++def test_the_row_cap_never_evicts_a_reportable_row_for_a_future_dated_one(+ tmp_path: Path,+) -> None:+ """Review 5267029898: capacity applied before the date filter evicts backwards.++ `_recency` orders by day first, so a future-dated row outranks every real one.+ `_retained` was written for exactly this — a clock that jumps forward, is+ corrected, and leaves rows no read will ever report while they hold slots and+ evict live ones. Applying the capacity to rows straight out of the file put+ that defect back on the read path, ahead of the code that closes it: the+ future rows survived, `window` then filtered them, and a window holding real+ usage reported none of it.++ Filtering to the requested window first is what makes the eviction meaningful,+ because then every candidate is a row a reader can actually see.+ """++ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ today = local_usage_day(NOW)+ rows = [+ {+ "day": (today + timedelta(days=ahead)).isoformat(),+ "source_id": "src_future",+ "model_id": f"model-{ahead}",+ "requests": 1,+ "input_tokens": 5,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": (NOW + timedelta(days=ahead)).isoformat(),+ }+ for ahead in (1, 2, 3)+ ] + [+ {+ "day": today.isoformat(),+ "source_id": "src_real",+ "model_id": f"model-{index}",+ "requests": 1,+ "input_tokens": 100,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": NOW.isoformat(),+ }+ for index in range(3)+ ]+ path.write_text(json.dumps(rows), encoding="utf-8")++ ledger = BoundedUsageLedger(path, max_rows=3)++ # The real rows are the only reportable ones, so they are the ones kept.+ assert [row["source_id"] for row in ledger.window(days=30, now=NOW)] == ["src_real"] * 3+ assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == 300+++def test_the_row_cap_ranks_an_unmeasurable_instant_as_the_least_recent(+ tmp_path: Path,+) -> None:+ """Review 5267204231: a future instant inside today survives the date filter.++ The date filter closed the future-*day* case; the second half of `_recency` is+ the instant, and a stamp later than the reading passes that filter untouched.+ A clock corrected backwards leaves exactly this behind, and the rows it leaves+ then outranked every real one and evicted live usage.++ Bounding the instant to the reading is the obvious remedy and is not enough:+ it makes those rows as recent as the reading, so they still outrank a row+ metered a minute earlier. Both halves are asserted here — the survivors, and+ the fact that a clamp would have kept the wrong ones.+ """++ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ today = local_usage_day(NOW).isoformat()+ rows = [+ {+ "day": today,+ "source_id": "src_future",+ "model_id": f"model-{ahead}",+ "requests": 1,+ "input_tokens": 5,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": (NOW + timedelta(hours=ahead)).isoformat(),+ }+ for ahead in (1, 2, 3)+ ] + [+ {+ "day": today,+ "source_id": "src_real",+ "model_id": f"model-{index}",+ "requests": 1,+ "input_tokens": 100,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ # An hour old: still the most recent usage anyone metered, and still+ # older than what a clamp to `now` would hand the future rows.+ "last_metered_at": (NOW - timedelta(hours=1)).isoformat(),+ }+ for index in range(3)+ ]+ path.write_text(json.dumps(rows), encoding="utf-8")++ ledger = BoundedUsageLedger(path, max_rows=3)++ assert [row["source_id"] for row in ledger.window(days=30, now=NOW)] == ["src_real"] * 3+ assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == 300+++def test_an_unmeasurable_instant_costs_a_row_nothing_while_there_is_room(+ tmp_path: Path,+) -> None:+ """Ranking last is an eviction order, not a verdict on the row.++ Nothing about a stamp decides whether a row is reported: the day does that.+ So a future-stamped row inside the window is published like any other until+ the file is over capacity, and the counters it carries are its own.+ """++ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ path.write_text(+ json.dumps(+ [+ {+ "day": local_usage_day(NOW).isoformat(),+ "source_id": "src_a",+ "model_id": "model-a",+ "requests": 1,+ "input_tokens": 42,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": (NOW + timedelta(days=9)).isoformat(),+ }+ ]+ ),+ encoding="utf-8",+ )++ ledger = BoundedUsageLedger(path, max_rows=3)++ assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == 42+++def test_a_merge_cannot_lift_a_published_count_over_the_declared_maximum(+ tmp_path: Path,+) -> None:+ """Review 5267029898: duplicates coalesce into one row, under one cap.++ `_counter` clears each stored counter against the ceiling, but their sum is+ not thereby cleared, and merging happens after. Enough duplicate-keyed rows+ therefore build a single row carrying more than any row may — and one row is+ one row, so the capacity that bounds the reportable set never sees it.++ How many duplicates a file holds is bounded by nothing, so this has to be+ answered on the merged value itself.+ """++ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ duplicate = {+ "day": local_usage_day(NOW).isoformat(),+ "source_id": "src_a",+ "model_id": "model-x",+ "requests": 1,+ "input_tokens": USAGE_COUNTER_CEILING,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": NOW.isoformat(),+ }+ path.write_text(+ json.dumps([dict(duplicate) for _ in range(USAGE_MAX_ROWS + 1)]), encoding="utf-8"+ )++ totals = BoundedUsageLedger(path).summary(days=30, now=NOW)["totals"]++ assert totals["input_tokens"] <= USAGE_PUBLISHED_COUNT_BOUND+ # Refused rather than reduced: the bucket is garbage, and the next call+ # recorded against it starts a row that means what it says.+ assert totals["input_tokens"] == 0+++def test_no_file_can_make_a_published_count_exceed_the_declared_maximum(+ tmp_path: Path,+) -> None:+ """The contract's maximum has to bound the reader, not just the writer.++ `USAGE_PUBLISHED_COUNT_BOUND` is the product of the two capacities this file+ has. It is a real bound on what `summary` publishes only while both of them+ are enforced on the way *in*; each was once enforced at one door only, and+ each time the gap let a hand-edited store publish a count its own schema+ rejects. This drives the worst case directly — every row at the counter+ ceiling, more rows than the file may hold — so the product stays a promise the+ producer keeps rather than a description of its happy path.+ """++ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ rows = USAGE_MAX_ROWS + 25+ path.write_text(+ json.dumps(+ [+ {+ "day": (local_usage_day(NOW) - timedelta(days=index % 30)).isoformat(),+ "source_id": "src_a",+ "model_id": f"model-{index:04d}",+ "requests": USAGE_COUNTER_CEILING,+ "input_tokens": USAGE_COUNTER_CEILING,+ "cached_input_tokens": USAGE_COUNTER_CEILING,+ "output_tokens": USAGE_COUNTER_CEILING,+ "last_metered_at": (NOW + timedelta(seconds=index)).isoformat(),+ }+ for index in range(rows)+ ]+ ),+ encoding="utf-8",+ )++ totals = BoundedUsageLedger(path).summary(days=30, now=NOW)["totals"]++ for key in ("requests", "input_tokens", "cached_input_tokens", "output_tokens"):+ assert totals[key] == USAGE_PUBLISHED_COUNT_BOUND, key+ # Tight, not merely safe: the worst admissible file reaches the bound exactly,+ # so the contract declares no range the producer cannot occupy.+ assert USAGE_PUBLISHED_COUNT_BOUND == USAGE_MAX_ROWS * USAGE_COUNTER_CEILING+++def test_no_file_can_put_a_published_summary_outside_its_own_contract(+ tmp_path: Path,+) -> None:+ """Every published guarantee, asserted against one deliberately hostile file.++ Five rounds of review found the same shape five times: an invariant the write+ path enforces that the report path does not mirror. Each fix closed the door it+ was found at, and the next one was found at a door nobody had listed. Listing+ the doors is the part that kept failing, so this asserts the guarantees instead+ — the properties `usage-summary.schema.json` and the UI depend on — over a file+ carrying every corruption at once, and over more reportable rows than the+ capacity can hold, so the eviction runs rather than being skipped.+ """++ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ today = local_usage_day(NOW)+ hostile: list[object] = []+ for index in range(USAGE_MAX_ROWS * 2):+ # Days on both sides of both edges: three ahead of today, thirty inside the+ # window, three behind it. Readable stamps on the first half, stamps no+ # clock has reached on the second.+ readable = index < USAGE_MAX_ROWS // 2+ hostile.append(+ {+ "day": (today - timedelta(days=(index % 36) - 3)).isoformat(),+ "source_id": f"src_{'past' if readable else 'ahead'}_{index % 7}",+ "model_id": f"model_{index % 11}",+ "requests": index,+ "token_reports": index * 3, # breaks its subset+ "input_tokens": USAGE_COUNTER_CEILING - index,+ "cached_input_tokens": USAGE_COUNTER_CEILING, # breaks its subset+ "output_tokens": -index, # not a count+ "last_metered_at": (+ NOW - timedelta(hours=index + 1)+ if readable+ else NOW + timedelta(hours=index)+ ).isoformat(),+ }+ )+ # Duplicate keys, so the merge builds counters no row in the file carried.+ # Taken from the unreadable half, because a merged row past the ceiling is+ # dropped on read and the readable family is what the eviction is asserted on.+ hostile.extend(hostile[USAGE_MAX_ROWS : USAGE_MAX_ROWS + 60])+ hostile.extend(["not a row", None, {"day": "2026-W34-2", "source_id": "s", "model_id": "m"}])+ path.write_text(json.dumps(hostile), encoding="utf-8")++ ledger = BoundedUsageLedger(path)+ rows = ledger.window(days=USAGE_DEFAULT_WINDOW_DAYS, now=NOW)+ report = ledger.summary(days=USAGE_DEFAULT_WINDOW_DAYS, now=NOW)++ assert len(rows) == USAGE_MAX_ROWS # the capacity binds, so eviction ran+ assert all(report["from_day"] <= row["day"] <= report["to_day"] for row in rows)++ # Nothing whose recency the report can read loses its slot to something it+ # cannot read — the property the last two rounds of review both came back to.+ # Within a day, because the day is the first half of the order and evicting the+ # oldest one first is what retention is: a recent row outranks an older one+ # whatever either claims about the hour.+ survivors = {(row["day"], row["source_id"], row["model_id"]) for row in rows}+ readable = {+ (row["day"], row["source_id"], row["model_id"])+ for row in hostile[: USAGE_MAX_ROWS // 2]+ if report["from_day"] <= row["day"] <= report["to_day"]+ }+ assert readable+ outbid = {day for day, _, _ in readable - survivors}+ assert not [row for row in rows if row["day"] in outbid and "ahead" in row["source_id"]]++ counters = (+ "requests",+ "token_reports",+ "input_tokens",+ "cached_input_tokens",+ "output_tokens",+ )+ buckets = [report["totals"], *report["days"]]+ for source in report["sources"]:+ buckets.append(source)+ buckets.extend(source["models"])+ for bucket in buckets:+ for key in counters:+ assert 0 <= bucket[key] <= USAGE_PUBLISHED_COUNT_BOUND+ assert bucket["cached_input_tokens"] <= bucket["input_tokens"]+ assert bucket["token_reports"] <= bucket["requests"]++ # The three groupings are three views of one set, so they must agree.+ for key in counters:+ assert sum(day[key] for day in report["days"]) == report["totals"][key]+ assert sum(source[key] for source in report["sources"]) == report["totals"][key]+ assert (+ sum(model[key] for source in report["sources"] for model in source["models"])+ == report["totals"][key]+ )++def test_the_row_cap_evicts_the_least_recently_metered_row(tmp_path: Path) -> None:"""Review 4959575659 finding 8: evicting by spelling starves a live model.@@ -768,7 +1140,7 @@ def test_a_row_with_unusable_counters_loads_as_zero(tmp_path: Path) -> None:"requests": -4,"token_reports": True,"input_tokens": "many",- "output_tokens": USAGE_TOKEN_CEILING * 5,+ "output_tokens": 1.5,}]),@@ -780,7 +1152,7 @@ def test_a_row_with_unusable_counters_loads_as_zero(tmp_path: Path) -> None:assert row["token_reports"] == 0assert row["input_tokens"] == 0assert row["cached_input_tokens"] == 0- assert row["output_tokens"] == USAGE_TOKEN_CEILING+ assert row["output_tokens"] == 0@pytest.mark.parametrize(@@ -1120,14 +1492,168 @@ def test_duplicate_persisted_rows_merge_instead_of_shadowing(tmp_path: Path) ->assert rows[0]["input_tokens"] == 100-def test_accumulated_counters_stop_at_the_ceiling(tmp_path: Path) -> None:+def test_accumulated_counters_are_exact_past_the_per_report_ceiling(tmp_path: Path) -> None:+ """An aggregate is a sum, not a capped one.++ The per-report ceiling exists so one hostile response cannot poison the+ ledger; it says nothing about how much a user may spend across many honest+ ones. Reusing it on the sum truncated real usage: the totals card showed a+ figure that was the ceiling rather than the usage, and nothing on the page+ could tell the difference. Every level the summary publishes is checked,+ because each one accumulates separately and a clamp left on any of them+ reappears as the same silent lie.+ """++ ledger = _ledger(tmp_path)+ maximal = ProtocolUsageReport(input_tokens=USAGE_REPORT_TOKEN_CEILING)++ ledger.record(source_id="src_a", model_id="model-x", usage=maximal, at=NOW)+ ledger.record(source_id="src_a", model_id="model-x", usage=maximal, at=NOW)++ expected = 2 * USAGE_REPORT_TOKEN_CEILING+ summary = ledger.summary(days=30, now=NOW)+ assert summary["totals"]["input_tokens"] == expected+ assert summary["sources"][0]["input_tokens"] == expected+ assert summary["sources"][0]["models"][0]["input_tokens"] == expected+ assert summary["days"][0]["input_tokens"] == expected+++def test_a_cached_input_share_survives_a_window_past_the_per_report_ceiling(+ tmp_path: Path,+) -> None:+ """The share is the reason a clamped aggregate could not stay hidden.++ Clamping input and its cached subset independently pinned both to the same+ ceiling, so the ratio converged on exactly 100% — a broken number wearing the+ appearance of perfect caching. The proportions here are a real week's:+ billions of input tokens at a cached share in the nineties.+ """+ledger = _ledger(tmp_path)- saturated = ProtocolUsageReport(input_tokens=USAGE_TOKEN_CEILING)+ report = ProtocolUsageReport.of(+ input_tokens=500_000_000,+ cached_input_tokens=475_000_000,+ output_tokens=2_000_000,+ )+ for day in range(7):+ at = NOW - timedelta(days=day)+ for _ in range(2):+ ledger.record(source_id="src_a", model_id="model-x", usage=report, at=at)++ totals = ledger.summary(days=7, now=NOW)["totals"]+ assert totals["input_tokens"] == 14 * 500_000_000+ assert totals["cached_input_tokens"] == 14 * 475_000_000+ assert totals["cached_input_tokens"] < totals["input_tokens"]+ assert totals["cached_input_tokens"] / totals["input_tokens"] == pytest.approx(0.95)+++def test_a_persisted_counter_past_the_representation_drops_its_row(+ tmp_path: Path,+) -> None:+ """The one bound this module keeps, and why it drops rather than saturates.- 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)+ A counter past 2**53 - 1 is not a count the file can hold, and no sum this+ module writes can reach it, so the probe has to come from a file nothing here+ would have produced. Saturating it would publish a number nobody spent — and+ saturating this row's input and cached-input together would publish it as a+ 100% cached share, the exact artifact this ledger exists to not produce.+ """- assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == USAGE_TOKEN_CEILING+ 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": USAGE_COUNTER_CEILING * 4,+ "cached_input_tokens": USAGE_COUNTER_CEILING * 4,+ "output_tokens": 0,+ "last_metered_at": NOW.isoformat(),+ }+ ]+ ),+ encoding="utf-8",+ )++ assert ledger.window(days=30, now=NOW) == []+ assert ledger.summary(days=30, now=NOW)["totals"] == {+ "requests": 0,+ "token_reports": 0,+ "input_tokens": 0,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ }+++def test_a_merge_the_file_cannot_hold_is_refused_by_every_surface(+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """Where an exact merge outgrows the file, and what every surface does with it.++ Two duplicate-keyed rows are something only a corrupt or hand-merged file+ holds, and `_read` folds them exactly — so their sum can exceed what a counter+ is written and read back as, on a value that was admitted one row at a time.++ This once asserted that the summary published that sum anyway, which was+ coherent while the contract declared no maximum: an exact aggregate was the+ honest answer and nothing downstream claimed a range. Restoring a derived+ maximum changed what the producer owes. A merged counter is bounded by how+ many duplicates the file holds, which is bounded by nothing, so publishing one+ unreduced means publishing counts the contract rejects — `USAGE_MAX_ROWS`+ rows can only bound a total while each of them is itself bounded.++ So the row is refused, not reduced, and now every surface says the same thing.+ A sum of cleared addends is not itself cleared, and the one rule every door+ already applied — a magnitude no published document could carry is dropped,+ never saturated — is what makes the bound hold. It is also what heals the+ file: the bucket disappears rather than pinning at the ceiling, and the next+ call starts a row that means what it says.+ """++ half = USAGE_COUNTER_CEILING // 2 + 1+ ledger = _ledger(tmp_path)+ ledger.path.parent.mkdir(parents=True, exist_ok=True)+ duplicate = {+ "day": local_usage_day(NOW).isoformat(),+ "source_id": "src_a",+ "model_id": "model-x",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": half,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": NOW.isoformat(),+ }+ ledger.path.write_text(json.dumps([duplicate, dict(duplicate)]), encoding="utf-8")++ with caplog.at_level(logging.WARNING, logger="core.handlers.model_hub.usage"):+ assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == 0++ assert any(+ "merged counters outgrew what the file can carry" in record.message+ for record in caplog.records+ )+ assert 2 * half > USAGE_COUNTER_CEILING++ # Refusing the row on the way in is also what stops the batch that follows+ # from being swallowed. The fold used to land on the unusable bucket and go+ # down with it when `_write` refused the result; now the bucket is already+ # gone, so this call is recorded rather than lost.+ 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["requests"], row["input_tokens"]) for row in persisted] == [(1, 0)]++ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)+ totals = ledger.summary(days=30, now=NOW)["totals"]+ assert totals["requests"] == 2+ assert totals["input_tokens"] == 0@pytest.mark.parametrize(