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 normalized identity and ledger recency one owner each
cyhac907286b2f4
diff --git a/config/v2_config.py b/config/v2_config.pyindex 8546a87a7..c2f3a8879 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -13,7 +13,18 @@ from copy import deepcopyfrom dataclasses import dataclass, field, fieldsfrom datetime import datetimefrom pathlib import Path-from typing import Callable, ClassVar, Iterator, List, Literal, Mapping, Optional, Union, get_args+from typing import (+ Callable,+ ClassVar,+ Iterator,+ List,+ Literal,+ Mapping,+ Optional,+ TypeVar,+ Union,+ get_args,+)from urllib.parse import parse_qsl, urlsplit, urlunsplitfrom config import paths@@ -2533,6 +2544,46 @@ class AgentsConfig:avault: AVaultConfig = field(default_factory=AVaultConfig)+_SettledItem = TypeVar("_SettledItem")+++def _collapse_settled_duplicates(+ parsed: list[_SettledItem],+ identity: Callable[[_SettledItem], object],+ as_written: list,+ message: str,+) -> list[_SettledItem]:+ """Keep a collection of model identifiers unique after spelling is settled.++ `normalized_model_id` is a many-to-one map applied inside the leaf validator,+ while the uniqueness check belongs to the parent holding the collection. So+ every such parent is checking pre-images while the object it builds carries+ post-images, and the difference is not cosmetic: the loaded config keeps both+ entries, `to_payload` writes one spelling for both, and the next load of what+ this one wrote raises. Loading a file must produce something loadable, and+ that round trip is what this restores.++ Duplicates **as written** stay a malformed payload and raise. Duplicates that+ appear only once spelling is settled are a legacy file naming one model in two+ spellings, so the later entry collapses into the earlier: it was already+ unreachable — an inventory lookup and an exact hop comparison both find the+ first — and raising would fail exactly the load the persisted-shape rule+ requires to succeed.+ """++ if len(set(as_written)) != len(as_written):+ raise ValueError(message)+ collapsed: list[_SettledItem] = []+ seen: set[object] = set()+ for item in parsed:+ settled = identity(item)+ if settled in seen:+ continue+ seen.add(settled)+ collapsed.append(item)+ return collapsed++@dataclassclass ModelHubModelConfig:id: str@@ -2808,8 +2859,12 @@ class ModelHubSourceConfig:raise ValueError("Config 'model_hub.sources.models' entries must be objects")if any(not isinstance(model_id, str) for model_id in model_ids):raise ValueError("Config 'model_hub.sources.models.id' must be a non-empty string")- if len(set(model_ids)) != len(model_ids):- raise ValueError("Config 'model_hub.sources.models' contains duplicate ids")+ models = _collapse_settled_duplicates(+ [ModelHubModelConfig.from_payload(model) for model in models_payload],+ lambda model: model.id,+ model_ids,+ "Config 'model_hub.sources.models' contains duplicate ids",+ )usage_payload = payload.get("usage")base_url = payload.get("base_url")credential_ref = payload.get("credential_ref")@@ -2850,7 +2905,7 @@ class ModelHubSourceConfig:supply_channel=supply_channel,billing=billing,state=ModelHubSourceStateConfig.from_payload(payload.get("state")),- models=[ModelHubModelConfig.from_payload(model) for model in models_payload],+ models=models,created_at=(_validate_optional_datetime(created_at,@@ -2937,24 +2992,16 @@ class ModelHubRouteConfig:hops = payload.get("hops")if not isinstance(hops, list):raise ValueError("Config 'model_hub.agents.routes.hops' must be an array")- parsed = tuple(ModelHubRouteHopConfig.from_payload(hop) for hop in hops)- # Duplicates as written stay a malformed payload. Duplicates that appear- # only once spelling is settled are a legacy file naming one upstream model- # in two spellings — the second hop could never have been reached past the- # first, so dropping it preserves the chain, where raising would fail the- # config load the persisted-shape rule requires to succeed.- as_written = [(hop["source_id"], hop["model_id"]) for hop in hops]- if len(set(as_written)) != len(as_written):- raise ValueError("Config 'model_hub.agents.routes.hops' must contain unique pairs")- deduplicated: list[ModelHubRouteHopConfig] = []- seen: set[tuple[str, str]] = set()- for hop in parsed:- pair = (hop.source_id, hop.model_id)- if pair in seen:- continue- seen.add(pair)- deduplicated.append(hop)- return cls(hops=tuple(deduplicated))+ return cls(+ hops=tuple(+ _collapse_settled_duplicates(+ [ModelHubRouteHopConfig.from_payload(hop) for hop in hops],+ lambda hop: (hop.source_id, hop.model_id),+ [(hop["source_id"], hop["model_id"]) for hop in hops],+ "Config 'model_hub.agents.routes.hops' must contain unique pairs",+ )+ )+ )def to_payload(self) -> dict:return {"hops": [hop.to_payload() for hop in self.hops]}diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex c51dd10ed..806d4765b 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -346,12 +346,42 @@ class BoundedUsageLedger:existing["last_metered_at"],increment["last_metered_at"],)- retained = self._retained(list(rows.values()), local_usage_day(at))+ retained = self._retained(list(rows.values()), at)self._write(retained)- def _retained(self, rows: list[dict], today: date) -> list[dict]:+ def _retained(self, rows: list[dict], now: datetime) -> list[dict]:+ """Keep the rows this ledger's own clock can place, bounded at both edges.++ `window` already refuses to report a row dated after today, so a future row+ contributes to nothing a reader can see — while still holding one of the+ `max_rows` slots and outranking every real row in `_recency`, which evicts+ the least recently metered. A clock that jumps forward while many pairs are+ metered and is then corrected would therefore fill the ledger with rows that+ report nothing and evict every new one, and metering would stop until those+ dates arrive. Retention keeping what reads refuse is the defect; one window+ with both edges, measured by this module rather than declared by the file,+ is what closes it.++ A row inside the window may still claim an instant that has not happened.+ That is not evidence of a misplaced row, only of an unmeasurable recency, so+ it is bounded rather than dropped: the file supplies the instant, this module+ supplies its spelling and its ceiling.+ """++ measured = now if now.tzinfo is not None else now.astimezone()+ today = local_usage_day(measured)oldest = (today - timedelta(days=self.retention_days - 1)).isoformat()- return [row for row in rows if row["day"] >= oldest]+ newest = today.isoformat()+ ceiling = measured.astimezone(timezone.utc).isoformat()+ placed = []+ for row in rows:+ if not oldest <= row["day"] <= newest:+ continue+ metered = _instant(row["last_metered_at"])+ if metered is not None and metered > measured:+ row = {**row, "last_metered_at": ceiling}+ placed.append(row)+ return placeddef window(self, *, days: int, now: datetime) -> list[dict]:"""Return the rows inside the trailing local-day window, oldest first."""diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex 56347d529..dd9dbe2e8 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -348,6 +348,51 @@ since this one — a file that ships but is invisible to anyone reading the inde`test_contracts_readme_indexes_every_file_beside_it` now compares the table with thedirectory, so the next file added is caught here instead of by whoever needed it.+### Round 6 (head `44bd53b48`)++Two P2 findings, and the first of them tripped the circuit breaker: "deduplicate model+IDs after normalization" in `ModelHubSourceConfig.from_payload` is the *same class* as+round 5's hop finding on the previous head. Stopping before a third site patch and+diagnosing the inventory instead, per the ruling recorded above.++- **Class G — normalized identity versus the collections that hold it**+ (`config/v2_config.py`). Round 4 made `normalized_model_id` a many-to-one map applied+ inside a leaf validator, while every uniqueness check lives in the parent that holds+ the collection. So each parent compares pre-images while the object it builds carries+ post-images. The consequence is not cosmetic: the loaded config keeps both entries,+ `to_payload` writes one spelling for both, and the next load of what this one wrote+ raises — a released build could write a file this product refuses. The class has+ exactly two members, confirmed by reading every application of the normalizer:+ `ModelHubModelConfig`/`ModelHubSourceConfig` and+ `ModelHubRouteHopConfig`/`ModelHubRouteConfig`. Route dict keys, `menu.checked`, and+ `sources.order` are a different identifier space and are not normalized. Both members+ now go through one owner, `_collapse_settled_duplicates`, which keeps round 5's+ ruling: duplicates *as written* raise, duplicates that appear only once spelling is+ settled collapse into the first — the later one was already unreachable.+- **Recency is only meaningful against a clock this module measures**+ (`core/handlers/model_hub/usage.py`). `_retained` named a window and implemented a+ half-line: a lower edge only. `window` already refuses to report a row dated after+ today, so a future-dated row contributes to nothing a reader can see — while holding+ one of the `max_rows` slots and outranking every real row in `_recency`, which evicts+ the least recently metered. A host clock that jumps forward while many pairs are+ metered and is then corrected therefore stops metering entirely until those dates+ arrive. Retention keeping what reads refuse was the defect; `_retained` now applies+ the same window at both edges, and bounds a within-window row whose `last_metered_at`+ has not happened yet to the measured instant. Same terminal rule as round 4's: the+ file supplies the instant, this module supplies its spelling *and* its ceiling.++Three invariant tests, each proven to fail without its fix.+`test_loading_a_persisted_config_yields_one_this_product_can_load_again` states the+property behind two rounds of findings once instead of per collection: whatever `load`+returns for a file a released build wrote, serializing it produces a file `load`+accepts. `test_every_normalized_identifier_collection_collapses_through_one_owner`+names the class rather than its members — an AST walk asserting the exact set of+classes that normalize and the exact set that collapse, so a third site fails a test+instead of costing a review round.+`test_a_new_call_is_metered_whatever_recency_the_ledger_already_claims` seeds every+shape a persisted row can use to outrank the present (future day, future instant, both)+rather than listing the ones that are handled.+## Todo- [x] Usage taxonomy and extraction in `stream_wire.py`diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 2d129a543..b981c3915 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -1,5 +1,6 @@from __future__ import annotations+import astimport copyimport jsonimport re@@ -1721,6 +1722,79 @@ def test_config_reload_spells_route_hops_like_the_inventory_they_name(monkeypatcassert {hop.model_id for hop in hops} == {model.id for model in hub.sources[0].models}+def test_loading_a_persisted_config_yields_one_this_product_can_load_again(monkeypatch, tmp_path):+ # The terminal property behind two rounds of findings, stated once instead of+ # per collection: whatever `load` returns for a file a released build wrote,+ # serializing it has to produce a file `load` accepts. Normalization is what+ # threatened it — a many-to-one map applied in the leaf validator while the+ # uniqueness check sits in the parent, so both spellings survive the load,+ # `to_payload` writes one spelling twice, and the *next* load raises. That+ # second load is the assertion, and it does not care which collections exist.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ padded = " claude-opus-4-6 "+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])+ source["supply_channel"] = "native_cli"+ source["models"] = [+ {+ "id": spelling,+ "display_name": None,+ "origin": "discovered",+ "reasoning_efforts": [],+ "discovered_at": "2026-07-23T03:00:00Z",+ }+ for spelling in (padded.strip(), padded)+ ]+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)+ current["model_hub"]["sources"] = [source]+ menu_model, route = next(iter(current["model_hub"]["agents"]["claude"]["routes"].items()))+ route["hops"] = [+ {"source_id": source["id"], "model_id": spelling} for spelling in (padded.strip(), padded)+ ]+ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps(current, ensure_ascii=False), encoding="utf-8")++ loaded = V2Config.load(config_path=config_path)+ assert loaded.load_warnings == ()++ rewritten = tmp_path / "rewritten.json"+ rewritten.write_text(+ json.dumps(+ api.config_to_payload(loaded, include_secrets=True, include_internal=True),+ ensure_ascii=False,+ ),+ encoding="utf-8",+ )+ reloaded = V2Config.load(config_path=rewritten)++ assert reloaded.load_warnings == ()+ assert reloaded.model_hub.to_payload() == loaded.model_hub.to_payload()+++def test_every_normalized_identifier_collection_collapses_through_one_owner():+ # Naming the class rather than its third member. Each collection whose leaf+ # validator settles a spelling needs its parent to collapse on the settled+ # value, and the two that exist cost one review round each because nothing+ # tied the two halves together. Counting them does: a normalization added+ # without its collapse fails here instead of arriving as a finding.+ source = Path("config/v2_config.py").read_text(encoding="utf-8")+ tree = ast.parse(source)+ normalizing = set()+ collapsing = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.ClassDef):+ continue+ for call in ast.walk(node):+ if not isinstance(call, ast.Call) or not isinstance(call.func, ast.Name):+ continue+ if call.func.id == "normalized_model_id":+ normalizing.add(node.name)+ elif call.func.id == "_collapse_settled_duplicates":+ collapsing.add(node.name)+ assert normalizing == {"ModelHubModelConfig", "ModelHubRouteHopConfig"}+ assert collapsing == {"ModelHubSourceConfig", "ModelHubRouteConfig"}+ assert len(collapsing) == len(normalizing)++def test_config_reload_recovers_dangling_legacy_custom_source_order(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex 70899e863..56c447821 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -564,6 +564,52 @@ def test_the_row_cap_evicts_the_least_recently_metered_row(tmp_path: Path) -> Noassert rows["model-a"]["requests"] == 2+def test_a_new_call_is_metered_whatever_recency_the_ledger_already_claims(+ tmp_path: Path,+) -> None:+ """Review 4964314764: a clock that ran ahead must not stop metering.++ Every shape a persisted row can use to outrank the present fills a ledger that+ is already at its cap: a day after today, an instant that has not happened, and+ both together. `_recency` evicts the least recently metered, so each of them+ ranks above the call being recorded right now, and none of them reports+ anything — `window` refuses a day it cannot place. Stating the property rather+ than the three shapes means a fourth spelling of "later than now" is covered+ without editing this test.+ """++ ledger = _ledger(tmp_path, max_rows=3)+ ahead = NOW + timedelta(days=400)+ ledger.path.parent.mkdir(parents=True, exist_ok=True)+ ledger.path.write_text(+ json.dumps(+ [+ {+ "day": local_usage_day(day).isoformat(),+ "source_id": "src_a",+ "model_id": f"model-{index}",+ "requests": 1,+ "token_reports": 0,+ "input_tokens": 0,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": instant.isoformat(),+ }+ for index, (day, instant) in enumerate(+ ((ahead, ahead), (NOW, ahead), (ahead, NOW))+ )+ ]+ ),+ encoding="utf-8",+ )++ ledger.record(source_id="src_a", model_id="model-new", usage=None, at=NOW)++ rows = {row["model_id"]: row for row in ledger.window(days=30, now=NOW)}+ assert rows["model-new"]["requests"] == 1+ assert all(datetime.fromisoformat(row["last_metered_at"]) <= NOW for row in rows.values())++@pytest.mark.parametrize("content",[