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): keep a folded ledger key out of reach of any legal model ID
cyh5507c57083c3
diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.pyindex 52233d45f..a9f7b4ed4 100644--- a/core/handlers/model_hub/identifiers.py+++ b/core/handlers/model_hub/identifiers.py@@ -13,9 +13,11 @@ import hashlibMODEL_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.+# without limit. It is also the exact length of a folded key: a head bounded by the+# admission bound, one separator, one hex digest. Every key the ledger derives is+# therefore either at most `MODEL_ID_MAX_LENGTH` (stored verbatim) or exactly this+# long (folded), and those two populations cannot overlap — an identifier long+# enough to occupy the folded form is itself folded before anything compares it.USAGE_LEDGER_KEY_MAX_LENGTH = MODEL_ID_MAX_LENGTH + 1 + 2 * hashlib.sha256().digest_size@@ -52,7 +54,8 @@ def canonical_model_id(value: object) -> str | None:usage ledger: per the persisted-shape rule a legacy value must disable nothingand fail nothing, and a call already made under one cannot be un-billed byrefusing its identifier afterwards. `normalized_model_id` is the half that- applies on load; `usage_ledger_key` is the bound that applies to a row.+ applies on load; `usage_ledger_key` is how a metered call gets a bounded key+ without being refused one."""if not isinstance(value, str):@@ -75,13 +78,22 @@ def usage_ledger_key(value: object) -> str | None:would have every one of its calls dropped, and the tab would report anupgraded 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.+ The bound therefore folds instead of refusing. A value within the admission+ bound is its own key; anything longer 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.++ Where the fold starts is the whole of why two distinct models cannot share one+ row. It starts at the admission bound, not at the length of a folded key, so a+ verbatim key is at most `MODEL_ID_MAX_LENGTH` and a folded key is always exactly+ `USAGE_LEDGER_KEY_MAX_LENGTH`: two populations a length test tells apart. Fold+ later and they overlap, and the folded form stops being ours — a config may hold+ any string, including the literal `<head>~<digest>` of another model it also+ holds, and that second model would then be keyed verbatim onto the first+ model's row and billed for its calls. No marker can close that gap, because a+ legacy identifier can carry any marker too. Only a length no admissible+ identifier can reach can, and reaching it means being folded.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.@@ -90,11 +102,38 @@ def usage_ledger_key(value: object) -> str | None:if not isinstance(value, str) or not value:return Nonecanonical = normalized_model_id(value)- if len(canonical) <= USAGE_LEDGER_KEY_MAX_LENGTH:+ if len(canonical) <= MODEL_ID_MAX_LENGTH:return canonicaldigest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()return f"{canonical[:MODEL_ID_MAX_LENGTH]}~{digest}"++def persisted_ledger_key(value: object) -> str | None:+ """Accept one key a ledger row already carries, or refuse the row.++ The other direction, and the reason deriving a key is not idempotent: a folded+ key is past the admission bound by construction, so feeding it back through+ `usage_ledger_key` would fold it a second time and orphan the row it came from.+ The read path must therefore recognize a stored key rather than re-derive it.++ It may refuse where `usage_ledger_key` may not, and the asymmetry is the same+ one admission and metering have. A call that already happened cannot be+ un-billed, so deriving may only fold. A row is not a call — it is what a+ previous write claims about calls — so a row bigger than any key this ledger+ can produce is a corrupt row, and dropping it loses a claim rather than a call.++ Whitespace still normalizes, because a row written by a release that spelled an+ identity with padding names the same model as one that did not, and two rows for+ one model would double it in the tab.+ """++ if not isinstance(value, str) or not value:+ return None+ canonical = normalized_model_id(value)+ if len(canonical) > USAGE_LEDGER_KEY_MAX_LENGTH:+ return None+ return canonical+# 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/usage.py b/core/handlers/model_hub/usage.pyindex e3633cabc..d351bd8da 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 usage_ledger_key+from .identifiers import persisted_ledger_key, usage_ledger_keyfrom .state_file import write_state_documentfrom .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReport@@ -100,9 +100,11 @@ 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 `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.+ The key fields go through the two key functions instead, and which one depends+ on the direction: a live call is keyed by `usage_ledger_key`, which folds a long+ identity rather than refusing it because the hub already served that call, while+ a row read back from the file goes through `persisted_ledger_key`, which+ recognizes the key a previous write derived instead of deriving it again."""if not isinstance(value, str):@@ -161,13 +163,17 @@ def _timestamp(value: object) -> Optional[str]:def _normalize_row(row: object) -> Optional[dict]:- """Project one persisted row onto the current shape, or drop it."""+ """Project one persisted row onto the current shape, or drop it.++ Only ever handed keys, never live identities: a caller metering a call derives+ its key first, so this function asks the one question a row can be asked.+ """if not isinstance(row, dict):return Noneday = _text(row.get("day"))- source_id = usage_ledger_key(row.get("source_id"))- model_id = usage_ledger_key(row.get("model_id"))+ source_id = persisted_ledger_key(row.get("source_id"))+ model_id = persisted_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@@ -354,19 +360,27 @@ class BoundedUsageLedger:for call in calls:metered_at = min(_aware(call.at), persisted_at)usage = call.usage- increment = _normalize_row(- {- "day": local_usage_day(metered_at).isoformat(),- "source_id": call.source_id,- "model_id": call.model_id,- "requests": 1,- "token_reports": 1 if usage is not None else 0,- "input_tokens": usage.input_tokens if usage else 0,- "cached_input_tokens": usage.cached_input_tokens if usage else 0,- "output_tokens": usage.output_tokens if usage else 0,- "last_metered_at": metered_at.isoformat(),- }- )+ # A live call carries identities, not keys, and this is the one place+ # they become one: derive here and every row downstream — new,+ # accumulated, or read back next restart — is already a key, so no+ # later surface can re-derive one that was folded and orphan its row.+ source_key = usage_ledger_key(call.source_id)+ model_key = usage_ledger_key(call.model_id)+ increment = None+ if source_key is not None and model_key is not None:+ increment = _normalize_row(+ {+ "day": local_usage_day(metered_at).isoformat(),+ "source_id": source_key,+ "model_id": model_key,+ "requests": 1,+ "token_reports": 1 if usage is not None else 0,+ "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_metered_at": metered_at.isoformat(),+ }+ )if increment is None:# Reachable only for a value no config can hold — not text, or# empty — because a long identity is folded to a bounded key@@ -375,7 +389,7 @@ class BoundedUsageLedger:# a quietly incomplete tab.logger.warning("Model Hub usage metering skipped a call with an unusable identifier",- extra={"source_id_usable": usage_ledger_key(call.source_id) is not None},+ extra={"source_id_usable": source_key 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 9978b556e..2964b0a4b 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -764,6 +764,53 @@ failing. The structure guard keeps each module to its own question: the servicemay not borrow the ledger's, the ledger meters and may not borrow the service's, andneither may spell the bound.+### Round 14 (head `500fb55af`)++One finding, and it is a defect in round 13's own fix rather than a new instance of+class C: no call is dropped now, but two calls can be attributed to one identity. The+breaker still applies — same property, eleventh head — so the decision is recorded+before the edit.++**The claim that was false.** The sentence "a folded key is longer than any verbatim+one, so it is returned unchanged" appears twice in round 13's prose and once as the+reason one function could serve both directions. The code did not implement it: the+verbatim branch admitted anything up to `USAGE_LEDGER_KEY_MAX_LENGTH`, which is+*exactly* the length every folded key has. The two populations overlapped at that+length, and the overlap needs no preimage attack — whoever writes the config picks any+over-long ID `X`, computes `X[:200] + "~" + sha256(X)` themselves, and stores that+literal string as a second model's ID. Both models load, both route, and the ledger+merges them onto one row. The reviewer's phrasing names the real defect: a "string+namespace that legacy IDs can already occupy".++**Why the obvious fix is not enough on its own.** Folding everything past+`MODEL_ID_MAX_LENGTH` makes verbatim (≤ 200) and folded (= 265) disjoint by length, and+then no admissible identifier can occupy the folded form — reaching that length means+being folded. But it also breaks the idempotence round 13 relied on: a stored folded key+fed back through the same function folds a second time and orphans its own row, which is+a mutation the existing `MH-USAGE-006` assertion already catches. Recognizing the folded+*shape* instead would restore idempotence and reopen the hole, because a legacy+identifier can carry any shape marker too. No marker closes this; only a length no+admissible identifier can reach.++**Scope decision: split the direction, not the shape.** Deriving a key for a call that+already happened and accepting a key a row already carries are different questions, and+only the second may answer no — a row is not a call, it is what an earlier write claims+about calls, so a key no write could have produced is a corrupt row and refusing it+loses a claim rather than a served call. `usage_ledger_key` therefore folds past the+admission bound and never refuses an identity; `persisted_ledger_key` recognizes what a+write derived and bounds the row. `record_many` derives once, where a live call becomes+a row, so `_normalize_row` only ever sees keys — the double duty that function was doing+is what made a single self-idempotent function look necessary in the first place.++**Evidence.** `MH-USAGE-006` now asserts the disjointness (`len(key)` is within the+admission bound or exactly a folded key's length, never between) and the pairing between+the two directions in place of self-idempotence. `MH-USAGE-007` states the property the+finding violated as injectivity over a closure — every seed plus the key it folds to,+each one asserted loadable through `ModelHubModelConfig.from_payload` — so the crafted+pair fails it without being named, and a read-back test fixes which keys a row may+carry. Four mutations, four distinct failures: the late fold threshold, a re-deriving+read path, a truncation-only fold, and an unbounded read.+## 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 198f855cc..0f5e9c082 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -155,6 +155,12 @@ scenarios:kind: compatibilitylayer: unittest: tests/test_model_hub_usage.py::test_metering_can_key_exactly_the_identities_a_config_can_hold+ - id: MH-USAGE-007+ name: Two model identifiers a config holds are never metered onto one ledger row+ status: covered+ kind: persistence+ layer: unit+ test: tests/test_model_hub_usage.py::test_no_two_identities_a_config_holds_can_share_one_row- 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 53f602a2d..d6a2dac47 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -647,9 +647,16 @@ def test_model_identity_is_decided_only_by_its_owner() -> None:# 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.+ #+ # Review 4966041599: within the ledger the same split appears again by+ # direction. Deriving a key for a call cannot refuse it; accepting a key a row+ # already carries can, and must not re-derive it. One function serving both+ # forced the fold to start late enough to be idempotent, which is what let a+ # legacy identifier occupy a folded key and share another model's row.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 "persisted_ledger_key" in usage_sourceassert "canonical_model_id" not in usage_sourcefor path in (SERVICE, USAGE):source = path.read_text(encoding="utf-8")diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex d1c19eea5..198da05fd 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -26,6 +26,7 @@ from core.handlers.model_hub import state_filefrom core.handlers.model_hub.identifiers import (MODEL_ID_MAX_LENGTH,USAGE_LEDGER_KEY_MAX_LENGTH,+ persisted_ledger_key,usage_ledger_key,)from core.handlers.model_hub.stream_wire import (@@ -1124,10 +1125,13 @@ def test_metering_can_key_exactly_the_identities_a_config_can_hold(identifier: odecides which identities exist, and this asserts the ledger can key every oneof 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.+ Keying the loaded value and the raw payload alike stops one model from occupying+ two rows. The length assertion is the review-4966041599 property: a key is either+ within the admission bound or exactly a folded key's length, never in between, so+ no identifier a config can hold can occupy the folded form. And the read path+ returns a derived key unchanged, so a row read back after a restart is the row+ that was written — the guarantee that used to be spelled as self-idempotence,+ which is what forced the fold to start too late."""try:@@ -1142,9 +1146,9 @@ def test_metering_can_key_exactly_the_identities_a_config_can_hold(identifier: oassert (key is None) == (loadable is None)if key is None:return- assert len(key) <= USAGE_LEDGER_KEY_MAX_LENGTH+ assert len(key) <= MODEL_ID_MAX_LENGTH or len(key) == USAGE_LEDGER_KEY_MAX_LENGTHassert usage_ledger_key(loadable) == key- assert usage_ledger_key(key) == key+ assert persisted_ledger_key(key) == key@pytest.mark.parametrize(@@ -1198,6 +1202,87 @@ def test_two_identities_sharing_a_bounded_head_are_metered_apart(tmp_path: Path)assert [row["requests"] for row in rows] == [1, 1]+def test_no_two_identities_a_config_holds_can_share_one_row(tmp_path: Path) -> None:+ """MH-USAGE-007, review 4966041599: a key this ledger derives is itself a legal ID.++ Nothing stops a config from holding, as one model's literal ID, the exact string+ the ledger derives for another — `from_payload` accepts any non-empty text, and+ the assertion below checks that rather than assuming it. So the identities under+ test are closed under keying: every seed, plus the key that seed folds to. If+ keying is not injective over that closure, two models a user configured+ separately are one row and one is billed for the other's calls.++ Stated as the closure rather than as the pair that exposed it, because the pair+ is only reachable while some legal identifier can occupy a derived key's shape —+ and any rule that leaves such a shape reachable fails here without being named.+ """++ seeds = (+ "model-x",+ "m" * MODEL_ID_MAX_LENGTH,+ "m" * (MODEL_ID_MAX_LENGTH + 1),+ "z" * (USAGE_LEDGER_KEY_MAX_LENGTH * 3),+ )+ identities = sorted({*seeds, *(usage_ledger_key(seed) for seed in seeds)})++ ledger = _ledger(tmp_path)+ for identity in identities:+ assert (+ ModelHubModelConfig.from_payload(+ {"id": identity, "origin": "manual", "reasoning_efforts": []}+ ).id+ == identity+ )+ ledger.record(source_id="src_a", model_id=identity, usage=None, at=NOW)++ rows = ledger.window(days=30, now=NOW)++ assert len({usage_ledger_key(identity) for identity in identities}) == len(identities)+ assert [row["requests"] for row in rows] == [1] * len(identities)+++ "key",+ [+ pytest.param("m" * MODEL_ID_MAX_LENGTH, id="a-verbatim-key"),+ pytest.param(usage_ledger_key("m" * (MODEL_ID_MAX_LENGTH + 1)), id="a-folded-key"),+ pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH + 1), id="one-past-every-derivable-key"),+ pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH * 8), id="far-past-them"),+ ],+)+def test_a_row_is_read_back_exactly_when_its_key_is_one_a_write_could_derive(+ tmp_path: Path, key: str+) -> None:+ """MH-USAGE-007: reading a row is the direction that may refuse.++ A row is not a call — it is what an earlier write claims about calls — so a key+ no write of this ledger could have produced is a corrupt row, and refusing it+ loses a claim rather than a served call. That refusal is also what keeps a+ persisted row bounded, since the read path is where a hand-edited file arrives.+ """++ derivable = len(key) <= USAGE_LEDGER_KEY_MAX_LENGTH+ 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": key,+ "requests": 1,+ }+ ]+ ),+ encoding="utf-8",+ )++ kept = [row["model_id"] for row in ledger.window(days=30, now=NOW)]++ assert kept == ([key] if derivable else [])++def test_the_ledger_file_is_owner_only(tmp_path: Path) -> None:ledger = _ledger(tmp_path)