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 model identity and ledger degradation one owner each
cyh1ddff18da6ae
diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.pyindex 5dfccf3da..4cc5206a9 100644--- a/core/handlers/model_hub/identifiers.py+++ b/core/handlers/model_hub/identifiers.py@@ -8,6 +8,30 @@ from __future__ import annotations# a model usage can meter, and a persisted row can never grow without limit.MODEL_ID_MAX_LENGTH = 200++def canonical_model_id(value: object) -> str | None:+ """Reduce one candidate identifier to its canonical form, or reject it.++ A model ID is an identity: it is compared, stored in config, sent upstream,+ and used as a usage-ledger key. Those uses only agree if every one of them+ means the same thing by "the same model", so the canonical form is decided+ once here and the boundaries that admit an identifier store what this+ returns. Surrounding whitespace is not part of the identity — accepting both+ ``"model-x"`` and ``" model-x"`` would put two rows in the tab for one model+ — and 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.+ """++ if not isinstance(value, str):+ return None+ canonical = value.strip()+ if not canonical or len(canonical) > MODEL_ID_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/service.py b/core/handlers/model_hub/service.pyindex 5a4d24db0..05e85ddeb 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 MODEL_ID_MAX_LENGTH, STANDARD_OPENCODE_VENDOR_IDS+from .identifiers import STANDARD_OPENCODE_VENDOR_IDS, canonical_model_idfrom .migration import (MigrationConflictError,apply_native_migration,@@ -1406,14 +1406,21 @@ class ModelHubService:*,allow_empty: bool = False,) -> None:- 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):+ # Admit the canonical form, not the text upstream happened to send: what+ # is stored here is what resolution compares and what usage meters, and a+ # listing that names one model twice under two spellings is a failed+ # discovery, not two models.+ canonical = [canonical_model_id(model_id) for model_id in discovered]+ if (+ (not allow_empty and not discovered and not manual_models)+ or any(+ model_id is None or contains_credential_material(model_id)+ for model_id in canonical+ )+ or len(set(canonical)) != len(canonical)+ ):raise ModelHubError("discovery_failed", status=502)+ discovered = [model_id for model_id in canonical if model_id is not None]discovered_at = self.now().isoformat()manual_model_ids = {model.id for model in manual_models}existing_by_id = {model.id: model for model in source.models}@@ -3475,15 +3482,10 @@ class ModelHubService:async def add_custom_model(self, source_id: object, payload: dict) -> dict:if not isinstance(payload, dict):raise ModelHubError("source_not_found", status=404)- model_id = payload.get("model_id")+ model_id = canonical_model_id(payload.get("model_id"))display_name = payload.get("display_name")reasoning_efforts = payload.get("reasoning_efforts")- if (- not isinstance(model_id, str)- or not model_id- or len(model_id) > MODEL_ID_MAX_LENGTH- or contains_credential_material(model_id)- ):+ if model_id is None or contains_credential_material(model_id):raise ModelHubError("mapping_target_unavailable")if display_name is not None and (not isinstance(display_name, str) or contains_credential_material(display_name)diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.pyindex ea3f97292..270503f1f 100644--- a/core/handlers/model_hub/stream_wire.py+++ b/core/handlers/model_hub/stream_wire.py@@ -699,11 +699,21 @@ class ProtocolSSEState:self.last_sequence_number = observation.sequence_numberdef terminal_observation(self) -> ProtocolObservation | None:+ """Report the settled facts, including everything accumulated to get here.++ Usage often arrives before the terminal — Anthropic reports input tokens on+ ``message_start`` — so a terminal that dropped the accumulated report would+ lose tokens the upstream already billed on exactly the streams that end+ badly.+ """+if self.terminal_outcome is not None:return ProtocolObservation(outcome=self.terminal_outcome,error_payload=self.error_payload,error_envelope_paths=self.error_envelope_paths,+ model_output_started=self.model_output_started,+ usage=self.usage,)return Nonediff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex 11615eed4..2686205c3 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -110,6 +110,21 @@ class _RenderedTurnOutcome:class _SSEWireState(ProtocolSSEState):"""Gateway-local name for the shared protocol stream tracker."""+ @property+ def reached_model(self) -> bool:+ """Whether this stream got far enough upstream to have been billed.++ Forwarded model output proves the call reached the model even when the+ stream then ended without a recognized terminal — a connection lost after+ a text delta is a request that happened, and `token_reports` staying at+ zero is exactly how the ledger records that nobody reported its tokens.++ One owner for the question, because every ending of a stream has to+ answer it the same way.+ """++ return self.terminal_outcome == "served" or self.model_output_started+class _DownstreamDisconnected(ConnectionError):pass@@ -651,7 +666,7 @@ class ModelHubTurnGateway:await self._record_usage(execution,usage=wire_state.usage,- served=wire_state.terminal_outcome == "served",+ served=wire_state.reached_model,)await self._write_stream_terminal_copy(response,@@ -761,7 +776,7 @@ class ModelHubTurnGateway:await self._record_usage(execution,usage=wire_state.usage,- served=wire_state.terminal_outcome == "served",+ served=wire_state.reached_model,)if execution.settlement_recorded:returndiff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex bd278a1ab..9e5a198c2 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -24,11 +24,11 @@ import loggingimport osimport tempfileimport threading-from datetime import date, datetime, timedelta+from datetime import date, datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Final, Optional-from .identifiers import MODEL_ID_MAX_LENGTH+from .identifiers import canonical_model_idfrom .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReportlogger = logging.getLogger(__name__)@@ -38,10 +38,9 @@ logger = logging.getLogger(__name__)USAGE_RETENTION_DAYS: Final = 62USAGE_MAX_ROWS: Final = 400USAGE_DEFAULT_WINDOW_DAYS: Final = 30-# 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+# Anything older than every instant this ledger can hold, so a row that never+# recorded one sorts as the least recently metered.+_OLDEST_INSTANT: Final = datetime.min.replace(tzinfo=timezone.utc)_COUNTER_KEYS: Final = ("requests",@@ -50,6 +49,14 @@ _COUNTER_KEYS: Final = ("cached_input_tokens","output_tokens",)+# The cross-field guarantees the read contract makes, as (subset, superset).+# Each one is repaired on read, so a corrupt or hand-edited file degrades into a+# smaller true statement instead of publishing an impossible one: a coverage+# figure above 100% is more misleading than a conservative one.+_COUNTER_SUBSETS: Final = (+ ("cached_input_tokens", "input_tokens"),+ ("token_reports", "requests"),+)def local_usage_day(moment: datetime) -> date:@@ -72,13 +79,18 @@ def _bounded_counter(value: object) -> int:return min(value, USAGE_TOKEN_CEILING)-def _identifier(value: object) -> Optional[str]:+def _text(value: object) -> Optional[str]:+ """Read one persisted text field, dropping anything that is not text.++ No length bound here: the only text fields this reads are a calendar day and+ an 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.+ """+if not isinstance(value, str):return None- trimmed = value.strip()- if not trimmed or len(trimmed) > _MAX_IDENTIFIER_LENGTH:- return None- return trimmed+ return value.strip() or Nonedef _calendar_day(value: str) -> Optional[date]:@@ -117,7 +129,7 @@ def _timestamp(value: object) -> Optional[str]:degrades the field to absent rather than travelling out through the API."""- text = _identifier(value)+ text = _text(value)if text is None or _instant(text) is None:return Nonereturn text@@ -128,9 +140,9 @@ def _normalize_row(row: object) -> Optional[dict]:if not isinstance(row, dict):return None- day = _identifier(row.get("day"))- source_id = _identifier(row.get("source_id"))- model_id = _identifier(row.get("model_id"))+ day = _text(row.get("day"))+ source_id = canonical_model_id(row.get("source_id"))+ model_id = canonical_model_id(row.get("model_id"))if day is None or source_id is None or model_id is None:return Noneif _calendar_day(day) is None:@@ -141,17 +153,24 @@ def _normalize_row(row: object) -> Optional[dict]:"model_id": model_id,**{key: _bounded_counter(row.get(key)) for key in _COUNTER_KEYS},}- # 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"],- )+ for subset, superset in _COUNTER_SUBSETS:+ normalized[subset] = min(normalized[subset], normalized[superset])normalized["last_metered_at"] = _timestamp(row.get("last_metered_at"))return normalized+def _recency(row: dict) -> 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 would+ be recreated and evicted again on every write while later-sorting stale rows+ survived, so its usage could never accumulate. Instants are compared as points+ in time — text order is not time order once two rows carry different offsets.+ """++ return (row["day"], _instant(row["last_metered_at"]) or _OLDEST_INSTANT)++def _row_key(row: dict) -> tuple[str, str, str]:return (row["day"], row["source_id"], row["model_id"])@@ -203,16 +222,24 @@ class BoundedUsageLedger:def _read(self) -> list[dict]:if not self.path.exists():return []+ # Degrading to empty keeps a broken optional-feature file from failing+ # startup, but the next write replaces that file — so this is the last+ # moment its history is recoverable, and saying nothing would erase it+ # silently.try:payload = json.loads(self.path.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):+ except (OSError, json.JSONDecodeError) as exc:+ logger.warning("Model Hub usage ledger %s is unreadable: %s", self.path, exc)return []if not isinstance(payload, list):+ logger.warning("Model Hub usage ledger %s is not a list of rows", self.path)return []rows: dict[tuple[str, str, str], dict] = {}+ dropped = 0for item in payload:row = _normalize_row(item)if row is None:+ dropped += 1continueexisting = rows.get(_row_key(row))if existing is None:@@ -223,12 +250,17 @@ class BoundedUsageLedger:existing["last_metered_at"],row["last_metered_at"],)+ if dropped:+ logger.warning(+ "Model Hub usage ledger %s dropped %d unusable row(s)", self.path, dropped+ )return sorted(rows.values(), key=_row_key)def _write(self, rows: list[dict]) -> None:self.path.parent.mkdir(parents=True, exist_ok=True)+ retained = sorted(rows, key=_recency)[-self.max_rows :]content = json.dumps(- sorted(rows, key=_row_key)[-self.max_rows :],+ sorted(retained, key=_row_key),ensure_ascii=False,separators=(",", ":"),)@@ -253,31 +285,36 @@ class BoundedUsageLedger:usage: Optional[ProtocolUsageReport],at: datetime,) -> None:- """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.+ """Fold one metered upstream call into its day's row.++ The new row goes through the same normalization as a persisted one, so+ what this module writes and what it reads can never disagree about a+ bound, a subset, or an identity.+ """++ increment = _normalize_row(+ {+ "day": local_usage_day(at).isoformat(),+ "source_id": source_id,+ "model_id": 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": at.isoformat(),+ }+ )+ 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.logger.warning(- "Model Hub usage metering skipped a turn with an unusable identifier",- extra={"source_id_usable": safe_source_id is not None},+ "Model Hub usage metering skipped a call with an unusable identifier",+ extra={"source_id_usable": canonical_model_id(source_id) is not None},)return- increment = {- "day": local_usage_day(at).isoformat(),- "source_id": safe_source_id,- "model_id": safe_model_id,- "requests": 1,- "token_reports": 1 if usage is not None else 0,- "input_tokens": usage.input_tokens if usage else 0,- "cached_input_tokens": usage.cached_input_tokens if usage else 0,- "output_tokens": usage.output_tokens if usage else 0,- "last_metered_at": at.isoformat(),- }with self._lock:rows = {_row_key(row): row for row in self._read()}existing = rows.get(_row_key(increment))diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex ed26a7ada..ced461a5a 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -14,6 +14,8 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import Any, AsyncIterator, Final, Literal, Mapping, Protocol, Sequence+from .stream_wire import ProtocolUsageReport+ENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")OBSERVATION_OUTCOMES = (@@ -97,6 +99,11 @@ class RawCallOutcome:source_id: strerror_type: str | None = None # raw upstream error type, if presenterror_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 = Noneclass ObservationOutcome(str, Enum):diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 32e625431..c2beb3b20 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1000,12 +1000,14 @@ after its terminal frame and a buffered error that still billed us are bothmetered. A call that never reached the model is not, because the resolution feedand 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-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.+`requests` is self-measured by hub code and is always present: a stream that+forwarded model output counts even when it then died without a terminal, because+that call demonstrably reached the model. 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 calls that carried a report, is+never greater than `requests`, and a missing report is never read as zero usage.+Every reported integer is bounded by a ceiling fixed in server code, never by a+total the response declares.Input composition follows each protocol rather than one invented total.`cached_input_tokens` is always the subset of `input_tokens` that was served from@@ -1013,8 +1015,13 @@ cache: Anthropic's own `input_tokens` excludes both cache members, so the reportinput total is their sum; OpenAI's already includes cached input, so the cachedcount is informational only. The subset holds even when an upstream reports a cachedcount 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.+the merged cached count is bounded by the merged input count. Both subset promises —+cached input inside input, token reports inside requests — are repaired on read, so a+corrupt or hand-edited ledger degrades into a smaller true statement instead of+publishing an impossible one.++`source_id` and `model_id` are reported in the canonical form configuration admitted,+so one model is one row rather than one row per spelling.Days are local-calendar days on the Avibe host. `from_day` and `to_day` bound therequested window even when no turn fell inside it; `days[]` contains only days thatdiff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex a8f0f721a..f22b090e4 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -89,13 +89,29 @@ a value that is not one degrades the field to absent instead of being published,`last_metered_at` comparisons order two rows as *points in time* — text order is nottime 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.+Identity is decided once, by `canonical_model_id` in `identifiers.py`: a model ID is+trimmed, non-empty, and within `MODEL_ID_MAX_LENGTH`. Both boundaries that admit one+(discovery and custom-model mapping) store what it returns, and the ledger keys rows+by it, so config, resolution, and metering cannot disagree about what "the same+model" means — two spellings of one ID would otherwise become two rows in the tab,+and a listing naming one model twice is a failed discovery rather than two models.+The ledger's re-check is therefore unreachable for anything the hub admits, so it+logs a warning rather than dropping silently: a future boundary that forgets should+show up as lost metering, not as a quietly incomplete tab. The rule is deliberately+*not* applied when loading persisted config — per the persisted-shape rule, a legacy+value must not make startup fail.++Every cross-field promise the read contract makes is a `_COUNTER_SUBSETS` entry+repaired in one place — cached input inside input, token reports inside requests —+and `record()` builds its row through the same normalization a persisted row gets, so+what this module writes it could also have read. Rejected state is never silent: a+ledger that fails to parse, is not a list, or holds unusable rows warns before the+next write replaces it, which is the last moment that history is recoverable.++Eviction under `USAGE_MAX_ROWS` orders rows by day and then by *when they were last+metered*, not by key. Ordering by key would evict by spelling: an early-sorting model+would be recreated and evicted again on every write while later-sorting stale rows+survived, so its usage could never accumulate.## Persisted shape@@ -145,10 +161,18 @@ A call is recorded when it reached the model: the hub forwarded its outputdownstream, or upstream reported tokens for it. The second half matters because avendor that reported tokens billed us whether or not the response ended well — astream 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+block. Usage a stream reported before it failed counts too: Anthropic bills input+tokens on `message_start`, so a terminal observation carries everything accumulated+to reach it. A call that never reached the model (rejected credential, engine down)+is not recorded: resolution events and source health already own that surface, andcounting it here would duplicate the concept.+For a stream, `_SSEWireState.reached_model` is the one place that answers "did this+call reach the model", because every ending of a stream has to answer it the same+way. Forwarded model output is sufficient on its own — a connection lost after a text+delta is a request that happened, and `token_reports` staying at zero is exactly how+the ledger records that nobody reported its tokens.+Metering has **two owners over disjoint populations**, split by the one line thatdecides who can read a call's body — `handle.stream is not None` in`ModelHubService._invoke`:@@ -184,6 +208,36 @@ Contract work: an `api.md` route-table row, an `x-model-hub-routes` entry plus a`usage-summary.schema.json`. The existing conformance guard then exercises theroute against a real server response.+## Review-loop diagnosis (2026-08-18, heads `847d681d` and `ac32d098`)++Two findings-bearing heads produced twelve P2 findings. Classified by root cause+rather than by comment, three classes recurred across both heads, which trips the+`ENGINEERING.md` circuit breaker. The full inventory and the ruling:++- **Class A — no owner for "the canonical form of a model identifier"** (findings 1,+ 11). Three notions coexisted: config accepted anything, the admission boundaries+ checked length only, and the ledger trimmed *and* bounded. Consolidated into+ `canonical_model_id`; both boundaries store its result and the ledger keys by it.+- **Class B — persisted-state degradation versus read-contract promises** (findings+ 2, 9, 12). Each cross-field guarantee needs one normalization site, and per the+ persisted-shape rule a rejection must warn. Consolidated into `_COUNTER_SUBSETS`,+ one shared `_normalize_row` on both the read and write paths, and warnings in+ `_read`.+- **Class C — metering population coverage** (findings 3, 4, 7, 10). Ownership was+ the fix on head 1 (`_invoke` splits the two populations); on head 2 the remaining+ two were a dropped field and code contradicting its own written policy, now owned+ by `reached_model`.+- **Class E — blocking I/O on the controller loop** (finding 6). Fixed, no recurrence.+- **Class F — bounded-retention eviction policy** (finding 8). No recurrence; evicting+ by key starved an early-sorting active model, so eviction is by recency.++Ruling: the breaker pauses blind patching, it does not automatically escalate to the+owner. Every action above is local, reversible, and makes the code match a contract+that was already written down, with no major trade-off and no irreversible risk — so+the work continued rather than stopping for a decision. The recurring signal was real+and was answered the way the property-ownership rule prescribes: consolidate the+owner, then resume.+## Todo- [x] Usage taxonomy and extraction in `stream_wire.py`diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 0e5fd6e86..a549d3e12 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -5674,6 +5674,77 @@ def test_source_patch_rejects_credential_bearing_discovered_model_id(tmp_path):assert "sk-model-never-persist-this" not in json.dumps(store.config.to_payload())+def test_admitted_model_ids_are_stored_in_their_canonical_form(tmp_path):+ """Review 4959575659 finding 11: one notion of "the same model", everywhere.++ A model ID is compared in config, sent upstream, and keys a usage row. If+ admission kept the surrounding whitespace the ledger's canonical key would+ split one model's usage in two, so admission stores what the ledger keys by.+ """++ service, store, adapter = _service(tmp_path)++ async def padded_models(vendor, protocol, base_url, credential_ref):+ return (" discovered-model ",)++ adapter.discover_models = padded_models+ source = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Padded source",+ "key": "sk-test-transient-only",+ },+ )+ )+ asyncio.run(+ service.add_custom_model(+ source["id"],+ {"model_id": " manual-model ", "reasoning_efforts": []},+ )+ )++ assert [model.id for model in store.config.sources[0].models] == [+ "discovered-model",+ "manual-model",+ ]+++def test_source_patch_rejects_one_discovered_model_under_two_spellings(tmp_path):+ """Two spellings of one identity are a failed listing, not two models."""++ service, store, adapter = _service(tmp_path)+ source = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "custom",+ "display_name": "Safe relay",+ "base_url": "https://relay.example/v1",+ "key": "sk-test-transient-only",+ },+ )+ )++ async def duplicate_spellings(vendor, protocol, base_url, credential_ref):+ return ("relay-model", " relay-model")++ adapter.discover_models = duplicate_spellings+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.patch_source(+ source["id"],+ {"base_url": "https://other-relay.example/v1"},+ )+ )++ assert exc_info.value.code == "discovery_failed"+ assert store.config.sources[0].base_url == "https://relay.example/v1"++def test_base_url_change_guards_and_prunes_invalid_exact_hops(monkeypatch,tmp_path,diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex c44a31d80..4090c00f8 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -6172,6 +6172,59 @@ def test_gateway_meters_a_streamed_served_turn_from_the_wire(tmp_path: Path) ->asyncio.run(exercise())+def test_a_stream_that_forwarded_output_is_metered_without_a_token_report(+ tmp_path: Path,+) -> None:+ """Review 4959575659 finding 10: `requests` is what our own code measured.++ Model output reached the client, so the call reached the model — a connection+ lost after a text delta is still a request that happened. Nobody reported its+ tokens, which is exactly what `token_reports` staying at zero records.+ """++ async def exercise() -> None:+ source = _source("src_meterpart01", "Interrupted stream")+ service = _service(+ tmp_path,+ sources=[source],+ live_handles=[+ LiveInvokeHandle(+ _outcome(+ RawOutcomeKind.NETWORK_ERROR,+ source_id=source.id,+ stream_started=True,+ ),+ (+ b'event: response.output_text.delta\ndata: {"type":'+ b'"response.output_text.delta","sequence_number":1}\n\n',+ ),+ )+ ],+ )+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]+ gateway = ModelHubTurnGateway(service)+ request = _prepared_gateway_request(+ gateway,+ turn_id="turn_meter_partial",+ requested_model=requested_model,+ source_id=source.id,+ stream=True,+ )+ with patch(+ "core.handlers.model_hub.turn_gateway.web.StreamResponse",+ return_value=FakeStreamResponse(),+ ):+ await gateway._handle_request(request)++ metered = _usage_of(service, source.id)+ assert metered["requests"] == 1+ assert metered["token_reports"] == 0+ assert metered["input_tokens"] == 0+ assert metered["output_tokens"] == 0++ asyncio.run(exercise())++def test_gateway_meters_a_failed_turn_that_upstream_already_billed(tmp_path: Path,) -> None:diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex aad476385..1303cf950 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -36,6 +36,7 @@ ROOT = Path(__file__).parents[1]DEEP_JSON_ARRAY = b"[" * 10_000 + b"0" + b"]" * 10_000TURN_GATEWAY = ROOT / "core/handlers/model_hub/turn_gateway.py"SERVICE = ROOT / "core/handlers/model_hub/service.py"+USAGE = ROOT / "core/handlers/model_hub/usage.py"PROVENANCE = ROOT / "core/handlers/model_hub/provenance.py"ROUTER = ROOT / "modules/agents/model_hub.py"ADAPTER = ROOT / "vibe/model_hub_runtime/adapter.py"@@ -552,6 +553,17 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:assert all(flag in set(ast.walk(recorder)) for flag in flags)+def test_model_identity_is_decided_only_by_its_owner() -> None:+ # Review 4959575659 finding 11: config, resolution, and metering only agree on+ # 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.+ for path in (SERVICE, USAGE):+ source = path.read_text(encoding="utf-8")+ assert "canonical_model_id" in source+ assert "MODEL_ID_MAX_LENGTH" not in source++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.pyindex 50fd3ca3b..c3995ebeb 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -170,6 +170,33 @@ def test_usage_on_the_terminal_frame_is_observed_before_settlement() -> None:assert state.usage == ProtocolUsageReport(input_tokens=30, output_tokens=4)+def test_a_terminal_error_carries_the_tokens_reported_before_it() -> None:+ """Review 4959575659 finding 7: Anthropic bills input on `message_start`.++ The terminal observation is what the runtime turns into a bodyless outcome for+ resolver metering, so dropping the accumulated report there would lose tokens+ on exactly the streams that end badly.+ """++ state = ProtocolSSEState("anthropic")+ for frame in _frames(+ {+ "type": "message_start",+ "message": {"usage": {"input_tokens": 900, "cache_read_input_tokens": 128}},+ },+ {"type": "error", "error": {"type": "overloaded_error"}},+ ):+ state.observe(frame)++ observation = state.terminal_observation()+ assert observation is not None+ assert observation.outcome != "served"+ assert observation.usage == ProtocolUsageReport(+ input_tokens=1028,+ cached_input_tokens=128,+ )++def test_openai_chat_reports_usage_only_on_its_final_chunk() -> None:"""Chat streaming carries usage on a dedicated chunk, then `[DONE]`."""@@ -504,6 +531,39 @@ 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_evicts_the_least_recently_metered_row(tmp_path: Path) -> None:+ """Review 4959575659 finding 8: evicting by spelling starves a live model.++ `model-a` sorts first by key and last by recency. Evicting by key would drop+ the row that was just written, so every later call for that model would be+ recreated and immediately evicted again while stale rows survived.+ """++ ledger = _ledger(tmp_path, max_rows=2)+ for index, model_id in enumerate(("model-y", "model-z", "model-a")):+ ledger.record(+ source_id="src_a",+ model_id=model_id,+ usage=None,+ at=NOW + timedelta(minutes=index),+ )++ assert [row["model_id"] for row in ledger.window(days=30, now=NOW)] == [+ "model-a",+ "model-z",+ ]++ ledger.record(+ source_id="src_a",+ model_id="model-a",+ usage=None,+ at=NOW + timedelta(minutes=3),+ )++ rows = {row["model_id"]: row for row in ledger.window(days=30, now=NOW)}+ assert rows["model-a"]["requests"] == 2++@pytest.mark.parametrize("content",[@@ -656,6 +716,91 @@ def test_a_persisted_cached_count_above_its_input_is_repaired_on_read(tmp_path:assert row["cached_input_tokens"] == 120+def test_a_persisted_report_count_above_its_requests_is_repaired_on_read(+ tmp_path: Path,+) -> None:+ """Review 4959575659 finding 9: coverage can be partial, never over 100%.++ `requests` is self-measured and `token_reports` counts a subset of it, so a+ corrupt file degrades into a smaller true statement rather than claiming more+ reports than there were calls.+ """++ 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": 3,+ "token_reports": 40,+ "input_tokens": 120,+ "cached_input_tokens": 8,+ "output_tokens": 4,+ }+ ]+ ),+ encoding="utf-8",+ )++ assert ledger.summary(days=30, now=NOW)["totals"] == {+ "requests": 3,+ "token_reports": 3,+ "input_tokens": 120,+ "cached_input_tokens": 8,+ "output_tokens": 4,+ }+++def test_a_written_row_is_validated_the_same_way_a_persisted_one_is(+ tmp_path: Path,+) -> None:+ """One validation path: what this module writes, it could also have read."""++ ledger = _ledger(tmp_path)+ ledger.record(+ source_id="src_a",+ model_id="model-x",+ usage=ProtocolUsageReport(input_tokens=40, cached_input_tokens=12, output_tokens=7),+ at=NOW,+ )++ persisted = json.loads(ledger.path.read_text(encoding="utf-8"))+ assert persisted == ledger.window(days=30, now=NOW)+++ "content",+ [+ pytest.param("not json", id="unparseable"),+ pytest.param('{"rows": []}', id="object-instead-of-list"),+ pytest.param('[{"day": "not-a-day", "source_id": "s", "model_id": "m"}]', id="bad-row"),+ ],+)+def test_rejecting_existing_ledger_state_is_warned_not_silent(+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+ content: str,+) -> None:+ """Review 4959575659 finding 12: the next write erases what was rejected.++ Degrading to empty is the persisted-shape rule; doing it quietly would spend+ the last moment the old history was recoverable.+ """++ ledger = _ledger(tmp_path)+ ledger.path.parent.mkdir(parents=True, exist_ok=True)+ ledger.path.write_text(content, encoding="utf-8")++ with caplog.at_level(logging.WARNING, logger="core.handlers.model_hub.usage"):+ assert ledger.window(days=30, now=NOW) == []++ assert [record.levelno for record in caplog.records] == [logging.WARNING]++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."""