Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): give the usage ledger one owner for the row key it may use
cyh500fb55af903
diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.pyindex 4a96e1285..52233d45f 100644--- a/core/handlers/model_hub/identifiers.py+++ b/core/handlers/model_hub/identifiers.py@@ -2,12 +2,22 @@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.+import hashlib++# The longest model identifier the hub admits at a boundary that can still refuse+# one: manual add, upstream discovery, and a client-declared model on source+# creation. It is deliberately not a load rule — per the persisted-shape rule a+# file an older release wrote must keep loading — so a live, routable identifier+# is not always within it, and no surface downstream of config may treat this+# bound as the set of identifiers that exist.MODEL_ID_MAX_LENGTH = 200+# The longest key a usage ledger row can carry, so a persisted row cannot grow+# without limit. Longer than any identifier stored verbatim by construction: the+# fold below appends a full digest, so a folded key can never collide with a+# verbatim one and folding a key twice returns it unchanged.+USAGE_LEDGER_KEY_MAX_LENGTH = MODEL_ID_MAX_LENGTH + 1 + 2 * hashlib.sha256().digest_size+def normalized_model_id(value: str) -> str:"""Spell one identifier the one way this product spells it.@@ -35,12 +45,14 @@ def canonical_model_id(value: object) -> str | None:and used as a usage-ledger key. Those uses only agree if every one of themmeans the same thing by "the same model", so admission is decided once hereand the surfaces that accept a client-declared identifier store what this- returns. An identifier past the bound is rejected outright rather than- admitted somewhere it cannot be metered.-- Deliberately not applied when loading persisted config: per the- persisted-shape rule a legacy value must disable nothing and fail nothing.- `normalized_model_id` is the half that does apply there.+ returns. An identifier past the bound is refused here, at the one moment a+ request can still be answered with an error instead of carried forever.++ Deliberately not applied when loading persisted config, and not applied by the+ usage ledger: per the persisted-shape rule a legacy value must disable nothing+ and fail nothing, and a call already made under one cannot be un-billed by+ refusing its identifier afterwards. `normalized_model_id` is the half that+ applies on load; `usage_ledger_key` is the bound that applies to a row."""if not isinstance(value, str):@@ -50,6 +62,39 @@ def canonical_model_id(value: object) -> str | None:return Nonereturn canonical++def usage_ledger_key(value: object) -> str | None:+ """Key one metered call by the identity it ran under, whatever its length.++ Admission and metering ask different questions about the same identifier, and+ only admission may answer no. A request naming a 4KB model is refused and+ nothing is lost; a call that already reached an upstream was already billed,+ and the only identity it can be attributed to is the one config holds. So+ `canonical_model_id` is the wrong question here — a legacy model that+ `ModelHubModelConfig.from_payload` deliberately keeps loadable and routable+ would have every one of its calls dropped, and the tab would report an+ upgraded install as quieter than it actually is.++ The bound therefore folds instead of refusing. A value that fits is its own+ key; a longer one is keyed by its readable head plus a digest of the whole+ value, which is bounded, identical across restarts, and separated from other+ identities by that digest rather than by a prefix an adversary can pad. The+ result is longer than any verbatim key, so it cannot collide with one and+ cannot fold again — which is why the read path and the write path can share+ this one function.++ Only a value carrying no identity at all — not text, or empty — has no key,+ and that is exactly the set no config can hold.+ """++ if not isinstance(value, str) or not value:+ return None+ canonical = normalized_model_id(value)+ if len(canonical) <= USAGE_LEDGER_KEY_MAX_LENGTH:+ return canonical+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()+ return f"{canonical[:MODEL_ID_MAX_LENGTH]}~{digest}"+# 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.pyindex 09960dd8c..cf6759ecd 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -2355,9 +2355,10 @@ class ModelHubService:if any(model.provenance != "manual"# The same admission rule the manual-add surface applies. A source- # may be created with its models inline, so this is the other way- # a client-declared identifier enters config, and one the ledger- # cannot key by is one whose usage would never be counted.+ # may be created with its models inline, so this is the other way a+ # client-declared identifier enters config — and a client can still+ # be told no, which is the one moment an unbounded identifier is+ # refusable rather than something every later surface must carry.or canonical_model_id(model.id) is Noneor contains_credential_material(model.id)or contains_credential_material(model.display_name or "")diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex 72f2c6718..e3633cabc 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -29,7 +29,7 @@ from datetime import date, datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Callable, Final, Optional, Sequence-from .identifiers import canonical_model_id+from .identifiers import usage_ledger_keyfrom .state_file import write_state_documentfrom .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReport@@ -100,8 +100,9 @@ def _text(value: object) -> Optional[str]:No length bound here: the only text fields this reads are a calendar day andan instant, and the parsers below already reject anything that is not one.- The key fields go through `canonical_model_id` instead, so a ledger row is- keyed by exactly the identity configuration admitted.+ The key fields go through `usage_ledger_key` instead, which bounds a row by+ folding a long identity rather than by refusing it — a call the hub served+ must still be counted, and a row this ledger wrote must still read back."""if not isinstance(value, str):@@ -165,8 +166,8 @@ def _normalize_row(row: object) -> Optional[dict]:if not isinstance(row, dict):return Noneday = _text(row.get("day"))- source_id = canonical_model_id(row.get("source_id"))- model_id = canonical_model_id(row.get("model_id"))+ source_id = usage_ledger_key(row.get("source_id"))+ model_id = usage_ledger_key(row.get("model_id"))if day is None or source_id is None or model_id is None:return None# Same rule as the instant above: the file supplies the day, this module@@ -367,13 +368,14 @@ class BoundedUsageLedger:})if increment is None:- # Unreachable for anything the hub admits: both boundaries that- # accept a model id store the canonical form this row is keyed by.- # Loud rather than silent so a future boundary that forgets shows- # up as lost metering instead of as a quietly incomplete tab.+ # Reachable only for a value no config can hold — not text, or+ # empty — because a long identity is folded to a bounded key+ # rather than refused. Loud rather than silent so a caller that+ # invents an identifier shows up as lost metering instead of as+ # a quietly incomplete tab.logger.warning("Model Hub usage metering skipped a call with an unusable identifier",- extra={"source_id_usable": canonical_model_id(call.source_id) is not None},+ extra={"source_id_usable": usage_ledger_key(call.source_id) is not None},)continueexisting = rows.get(_row_key(increment))diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex abe716221..9978b556e 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -718,6 +718,52 @@ read-modify-write staying off the event loop, and a report surviving a full prel`tests/test_model_hub_l3.py` and `tests/test_model_hub_usage.py` join `canonical_tests` andthe project index, and each scenario ID is greppable from its test's docstring.+### Round 13 (head `915c3a73b`)++One finding, and it is class C a tenth time — so the circuit breaker applies and the+scope decision is recorded here before the edit rather than after it.++**Why this one is not another instance of the same fix.** Rounds 7 through 12 were all+about *when* a fact could be read: an observation existed and some ending, hand-off, or+buffer stood between it and the ledger. This one is not about reachability at all. The+call arrives with every fact intact and the ledger throws it away, because it asks+`canonical_model_id` — the *admission* question — about an identifier admission never+governed. Two policies, no owner of the question "what may key a usage row".++**The contradiction was written down, not merely implied.** Two tests were shipped side+by side and both passed: `test_a_persisted_model_id_past_the_bound_still_loads` asserts a+model ID longer than `MODEL_ID_MAX_LENGTH` stays loadable and keeps its length, because+per the persisted-shape rule a file an older release wrote must load; and+`test_an_unusable_identifier_is_never_persisted[oversized-model]` asserted that the same+shape's usage is dropped. Three comments stated the invariant the pair violates — the+`MODEL_ID_MAX_LENGTH` header ("a model config accepts is always a model usage can+meter"), `_text`'s docstring, and `record_many`'s "unreachable for anything the hub+admits". A false invariant asserted in prose next to a test that proves it false is how+this survived nine reviews.++**Scope decision: one owner, and it folds instead of refusing.** `usage_ledger_key` joins+the two existing spellings in `identifiers.py`. Admission may answer no — a request+naming a 4KB model is refused and nothing is lost — but metering cannot, because the call+already happened and was already billed. So the ledger's bound became a fold: a value+that fits is its own key, a longer one is keyed by its readable head plus a digest of the+whole identity. Both key fields go through it on both the read and the write path, which+is safe because the fold is idempotent by construction (a folded key is longer than any+verbatim one, so it is returned unchanged) and injective by digest rather than by a prefix+padding could collide with. `source_id` gets the same treatment for the same reason: its+config pattern is `src_[a-z0-9]{8,}`, unbounded above, so it belongs to the same+population.++**One deliberate behaviour change beyond the finding.** The old rule also dropped an+identifier that is nothing but padding. That is the same class one probe further on — a+padding-only ID is loadable too — so the refusal set is now exactly what no config can+hold: not text, or empty. `usage_ledger_key` returning `None` and+`ModelHubModelConfig.from_payload` raising are now the same predicate, and+`MH-USAGE-006` asserts that equivalence against the config constructor itself rather than+against a list of rejected shapes, so the two halves cannot drift apart again without+failing. The structure guard keeps each module to its own question: the service admits and+may not borrow the ledger's, the ledger meters and may not borrow the service's, and+neither may spell the bound.+## Todo- [x] Usage taxonomy and extraction in `stream_wire.py`diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex de851339f..198f855cc 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -149,6 +149,12 @@ scenarios:kind: recoverylayer: unittest: tests/test_model_hub_runtime.py::test_tokens_reported_by_the_chunk_that_overflows_the_prelude_are_still_metered+ - id: MH-USAGE-006+ name: Every model identifier a persisted config still loads is one the ledger can key+ status: covered+ kind: compatibility+ layer: unit+ test: tests/test_model_hub_usage.py::test_metering_can_key_exactly_the_identities_a_config_can_hold- id: MH-RES-LIVE-001name: Live turn retries an eligible backup before streaming startsstatus: covereddiff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex 932ce943b..53f602a2d 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -641,9 +641,18 @@ def test_model_identity_is_decided_only_by_its_owner() -> None:# what "the same model" is while one function decides it. A module that reaches# for the raw bound instead is re-deriving the rule, and the notions drift apart# again — that is exactly how one model became two ledger rows.+ #+ # Review 4965885614: which function is the right one depends on whether the+ # module may answer no. The service admits, so it asks the admission question;+ # the ledger meters a call that already happened, so asking it there dropped+ # every call made under an identifier a legacy file kept loadable. Neither may+ # spell the bound, and neither may borrow the other's question.+ assert "canonical_model_id" in SERVICE.read_text(encoding="utf-8")+ usage_source = USAGE.read_text(encoding="utf-8")+ assert "usage_ledger_key" in usage_source+ assert "canonical_model_id" not in usage_sourcefor path in (SERVICE, USAGE):source = path.read_text(encoding="utf-8")- assert "canonical_model_id" in sourceassert "MODEL_ID_MAX_LENGTH" not in source# Review 4960570946: a third admission path had picked up neither half, so# the half that is always safe moved to the one validator every path goesdiff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex bdc46daac..d1c19eea5 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -21,8 +21,13 @@ from pathlib import Pathimport pytest+from config.v2_config import ModelHubModelConfigfrom core.handlers.model_hub import state_file-from core.handlers.model_hub.identifiers import MODEL_ID_MAX_LENGTH+from core.handlers.model_hub.identifiers import (+ MODEL_ID_MAX_LENGTH,+ USAGE_LEDGER_KEY_MAX_LENGTH,+ usage_ledger_key,+)from core.handlers.model_hub.stream_wire import (PROTOCOL_STREAM_TAXONOMY,USAGE_TOKEN_CEILING,@@ -1070,8 +1075,7 @@ def test_accumulated_counters_stop_at_the_ceiling(tmp_path: Path) -> None:"source_id,model_id",[pytest.param("", "model-x", id="empty-source"),- pytest.param(" ", "model-x", id="blank-source"),- pytest.param("src_a", "m" * (MODEL_ID_MAX_LENGTH + 1), id="oversized-model"),+ pytest.param("src_a", "", id="empty-model"),],)def test_an_unusable_identifier_is_never_persisted(@@ -1080,7 +1084,13 @@ def test_an_unusable_identifier_is_never_persisted(source_id: str,model_id: str,) -> None:- """Loud, not silent: a dropped turn is lost metering, not a tidy no-op."""+ """Loud, not silent: a dropped turn is lost metering, not a tidy no-op.++ What reaches here is a caller that invented an identifier, not a config that+ holds an awkward one — the test below pins that boundary. A length is not a+ reason to drop a call, so the only refusals left are values carrying no+ identity at all.+ """ledger = _ledger(tmp_path)@@ -1091,15 +1101,101 @@ def test_an_unusable_identifier_is_never_persisted(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."""+ "identifier",+ [+ pytest.param("model-x", id="ordinary"),+ pytest.param(" model-x ", id="padded"),+ pytest.param(" ", id="padding-only"),+ pytest.param("m" * MODEL_ID_MAX_LENGTH, id="at-the-admission-bound"),+ pytest.param("m" * (MODEL_ID_MAX_LENGTH + 1), id="one-past-it"),+ pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH * 4), id="far-past-it"),+ pytest.param("", id="empty"),+ pytest.param(None, id="not-text"),+ ],+)+def test_metering_can_key_exactly_the_identities_a_config_can_hold(identifier: object) -> None:+ """MH-USAGE-006, review 4965885614: two bounds, and only one of them may refuse.++ The admission bound is not a load rule, so `from_payload` keeps a longer+ persisted identifier loadable and routable on purpose. Asking the admission+ question again at the ledger made that population unmeterable — a turn served+ without a trace in the tab. So the config constructor, not a list written here,+ decides which identities exist, and this asserts the ledger can key every one+ of them: the two halves cannot drift apart without failing.++ The last two assertions are the reason one function serves both directions.+ Keying the loaded value and the raw payload alike stops one model from+ occupying two rows, and keying a key returns it, so a row read back after a+ restart is the row that was written.+ """++ try:+ loadable = ModelHubModelConfig.from_payload(+ {"id": identifier, "origin": "manual", "reasoning_efforts": []}+ ).id+ except ValueError:+ loadable = None++ key = usage_ledger_key(identifier)++ assert (key is None) == (loadable is None)+ if key is None:+ return+ assert len(key) <= USAGE_LEDGER_KEY_MAX_LENGTH+ assert usage_ledger_key(loadable) == key+ assert usage_ledger_key(key) == key+++ "model_id",+ [+ pytest.param("m" * MODEL_ID_MAX_LENGTH, id="at-the-admission-bound"),+ pytest.param("m" * (MODEL_ID_MAX_LENGTH + 1), id="one-past-it"),+ pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH * 4), id="far-past-it"),+ ],+)+def test_a_model_a_legacy_file_still_routes_accumulates_one_row_across_restarts(+ tmp_path: Path, model_id: str+) -> None:+ """MH-USAGE-006: an upgraded install must not look quieter than it is.++ Three separate ledgers over one file, because a key derived per process would+ give this model a fresh row on every restart — bounded away again by retention+ before it could ever add up. Two calls, one row, whatever the identifier's+ length.+ """++ _ledger(tmp_path).record(source_id="src_a", model_id=model_id, usage=None, at=NOW)+ _ledger(tmp_path).record(source_id="src_a", model_id=model_id, usage=None, at=NOW)++ rows = _ledger(tmp_path).window(days=30, now=NOW)++ assert [(row["model_id"], row["requests"]) for row in rows] == [+ (usage_ledger_key(model_id), 2)+ ]+ assert len(rows[0]["model_id"]) <= USAGE_LEDGER_KEY_MAX_LENGTH+++def test_two_identities_sharing_a_bounded_head_are_metered_apart(tmp_path: Path) -> None:+ """MH-USAGE-006: the bound is a fold, and a fold that loses the tail merges rows.++ Truncation alone is the obvious way to bound a key and the wrong one: these two+ models differ only past the head a truncated key would keep, so one of them+ would be billed for the other's calls. What separates them is a digest of the+ whole identity, which no padding can collide with.+ """ledger = _ledger(tmp_path)- longest = "m" * MODEL_ID_MAX_LENGTH+ head = "m" * (USAGE_LEDGER_KEY_MAX_LENGTH * 2)++ ledger.record(source_id="src_a", model_id=f"{head}-one", usage=None, at=NOW)+ ledger.record(source_id="src_a", model_id=f"{head}-two", usage=None, at=NOW)- ledger.record(source_id="src_a", model_id=longest, usage=None, at=NOW)+ rows = ledger.window(days=30, now=NOW)- assert [row["model_id"] for row in ledger.window(days=30, now=NOW)] == [longest]+ assert len({row["model_id"] for row in rows}) == 2+ assert [row["requests"] for row in rows] == [1, 1]def test_the_ledger_file_is_owner_only(tmp_path: Path) -> None: