Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): give model-ID spelling and ledger shape single owners

cyh8e2af4a4baa5
diff --git a/config/v2_config.py b/config/v2_config.py
index c4f901367..33900d99b 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -2589,8 +2589,15 @@ class ModelHubModelConfig:
raise ValueError(
"Config 'model_hub.sources.models.retired' must be false for manual models"
)
+ # Spelling is settled here, at the one place a payload becomes a model
+ # config, so no admission path can invent a second spelling for one
+ # model and split its usage across two ledger rows. The length bound
+ # stays with the admission surfaces: this constructor also reads files
+ # older releases wrote, and rejecting one of those would fail config load.
+ from core.handlers.model_hub.identifiers import normalized_model_id
+
return cls(
- id=model_id,
+ id=normalized_model_id(model_id),
provenance=origin,
reasoning_efforts=list(reasoning_efforts),
display_name=display_name,
diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.py
index 4cc5206a9..4a96e1285 100644
--- a/core/handlers/model_hub/identifiers.py
+++ b/core/handlers/model_hub/identifiers.py
@@ -9,26 +9,44 @@ from __future__ import annotations
MODEL_ID_MAX_LENGTH = 200
+def normalized_model_id(value: str) -> str:
+ """Spell one identifier the one way this product spells it.
+
+ The identity half of the canonical form, split out because it is the half
+ that is always safe. Surrounding whitespace is not part of a model's
+ identity — accepting both ``"model-x"`` and ``" model-x"`` would put two rows
+ in the tab for one model — so every identifier that enters a config object
+ goes through here, including one read from a file an older release wrote.
+ The bound below cannot follow it there: rejecting a persisted value would
+ fail config load, and per the persisted-shape rule a legacy file must load.
+
+ A value that is nothing but padding therefore comes back unchanged rather
+ than emptied. A normalization that turns a loadable file into an unloadable
+ one is a migration, and this is not one.
+ """
+
+ return value.strip() or value
+
+
def canonical_model_id(value: object) -> str | None:
- """Reduce one candidate identifier to its canonical form, or reject it.
+ """Admit one candidate identifier in 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.
+ means the same thing by "the same model", so admission is decided once here
+ and 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.
"""
if not isinstance(value, str):
return None
- canonical = value.strip()
- if not canonical or len(canonical) > MODEL_ID_MAX_LENGTH:
+ canonical = normalized_model_id(value)
+ if not canonical.strip() or len(canonical) > MODEL_ID_MAX_LENGTH:
return None
return canonical
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 96d619424..a002b859f 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -97,7 +97,13 @@ async def dispatch_model_hub_rpc(
if operation == "list_events":
return service.list_events(limit=payload.get("limit", 20), before=payload.get("before"))
if operation == "usage_summary":
- return service.usage_summary(days=payload.get("days", USAGE_DEFAULT_WINDOW_DAYS))
+ # Reads the ledger file and the config store, and takes the same lock a
+ # concurrent `record()` holds across `fsync()`. On the controller loop
+ # that is every turn on this machine waiting on one settings page.
+ return await asyncio.to_thread(
+ service.usage_summary,
+ days=payload.get("days", USAGE_DEFAULT_WINDOW_DAYS),
+ )
if operation == "get_agent_chain":
return service.agent_chain(payload.get("backend"), payload.get("model_id"))
if operation == "probe_agent":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 05e85ddeb..f63d35b3a 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -2350,6 +2350,11 @@ class ModelHubService:
manual_models = [ModelHubModelConfig.from_payload(model) for model in models_payload]
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.
+ or canonical_model_id(model.id) is None
or contains_credential_material(model.id)
or contains_credential_material(model.display_name or "")
for model in manual_models
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index ad0500823..c51dd10ed 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -123,20 +123,24 @@ def _instant(value: object) -> Optional[datetime]:
def _timestamp(value: object) -> Optional[str]:
- """Read one persisted instant as the canonical text for that instant.
-
- The read surface promises a date-time with an offset, and `_instant` accepts
- every spelling `datetime.fromisoformat` does — naive, space-separated, second-
- less. Publishing the original text would let a hand-edited `2026-08-18T03:14`
- travel out through the API as something the schema does not describe, so the
- field carries what the parser understood rather than what the file said. An
- unparseable value degrades the field to absent.
+ """Publish one persisted instant in the one spelling this module writes.
+
+ The read surface promises an RFC 3339 date-time, and `datetime.fromisoformat`
+ accepts far more than RFC 3339 describes — naive, space-separated, and, after
+ an offset, even seconds. Publishing the file's text, or re-publishing the
+ parsed value in the file's own offset, both leave the output shape decided by
+ the input: fix one spelling and the next one is still reachable.
+
+ So the file supplies only the instant, and this module supplies the spelling.
+ Normalizing to UTC means the offset is `+00:00` by construction, whatever the
+ file said, and there is no remaining spelling for a hand-edited value to
+ reach. An unparseable value degrades the field to absent.
"""
parsed = _instant(_text(value))
if parsed is None:
return None
- return parsed.isoformat()
+ return parsed.astimezone(timezone.utc).isoformat()
def _normalize_row(row: object) -> Optional[dict]:
@@ -149,10 +153,16 @@ def _normalize_row(row: object) -> Optional[dict]:
model_id = canonical_model_id(row.get("model_id"))
if day is None or source_id is None or model_id is None:
return None
- if _calendar_day(day) is None:
+ # Same rule as the instant above: the file supplies the day, this module
+ # supplies its spelling. `date.fromisoformat` also reads `20260818` and
+ # `2026-W34-2`, and the window bounds are compared as `YYYY-MM-DD` text — so
+ # a row kept in another valid spelling would be silently outside every
+ # window it belongs to, without even counting as dropped.
+ calendar_day = _calendar_day(day)
+ if calendar_day is None:
return None
normalized = {
- "day": day,
+ "day": calendar_day.isoformat(),
"source_id": source_id,
"model_id": model_id,
**{key: _bounded_counter(row.get(key)) for key in _COUNTER_KEYS},
@@ -230,9 +240,15 @@ class BoundedUsageLedger:
# 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.
+ # Every way decoding can fail, by category rather than by the shapes a
+ # particular file happens to hold: invalid UTF-8 and an integer past the
+ # digit limit both raise plain `ValueError`, deep nesting raises
+ # `RecursionError`, and either one escaping here would take down the read
+ # route and then stop metering entirely — the loud-failure outcome this
+ # degradation exists to prevent.
try:
payload = json.loads(self.path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
+ except (OSError, ValueError, RecursionError) as exc:
logger.warning("Model Hub usage ledger %s is unreadable: %s", self.path, exc)
return []
if not isinstance(payload, list):
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index e7b420358..d1261d5a2 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -266,6 +266,47 @@ by another route answered the question with nothing.
`2026-08-18T03:14` leave through the API as something the schema does not describe.
The field now carries what the parser understood, not what the file said.
+### Round 4 (head `617aefb80`)
+
+Five P2 findings, and the two recurring classes both turned out to have been fixed one
+level too shallow. Round 3's rulings were correct about the sites they named and wrong
+about where the property lived.
+
+- **Class A, a third admission path** (`identifiers.py`, `config/v2_config.py`,
+ `service.py`). Rounds 1–2 put model-ID canonicalization at "the admission boundaries",
+ which made it a duty each boundary had to remember — so `create_source` with inline
+ `models`, a boundary added for a different reason, obeyed neither half. The rule is now
+ split by what each half can safely do. *Spelling* (`normalized_model_id`) moves into
+ `ModelHubModelConfig.from_payload`, the one validator every path goes through,
+ including the one that loads files older releases wrote; it only strips padding, so it
+ cannot reject anything that used to load. The *length bound* stays at the admission
+ surfaces, because that same validator sits under `ModelHubConfig.from_payload`, where
+ raising fails config load outright — rejecting a persisted value there would break the
+ persisted-shape rule. Two owners because there are two properties, not two call sites.
+- **Class B, three findings** (`usage.py`: `_timestamp`, `_normalize_row`, `_read`).
+ Applying the repo lesson about anchoring adversarial-input rulings to self-measured
+ bounds: round 3's `_timestamp` fix still let the *file* decide the output shape, which
+ is the endless narrowing series that lesson names — fix `2026-08-18T03:14` and
+ `+00:00:30` is still reachable. Terminal rule: **the file supplies the instant, this
+ module supplies the spelling.** `_timestamp` normalizes to UTC so the offset is
+ `+00:00` by construction; `_normalize_row` re-emits the day via `date.isoformat()` so a
+ row written as `20260818` still lands in the windows that compare `YYYY-MM-DD` text;
+ `_read` degrades by failure *category* (`OSError, ValueError, RecursionError`) rather
+ than by the shapes one file happens to hold.
+- **Class E, the other half of round 2** (`rpc.py`). Round 2 moved the ledger *write* off
+ the controller loop and left the *read* on it, where it takes the same lock a writer
+ holds across `fsync()` — every turn on the machine waiting on one settings page. The
+ read now goes through `asyncio.to_thread`, and a structure guard asserts every RPC
+ entry into the ledger is enclosed by one, so the next entry cannot quietly be the
+ exception.
+
+Known limitation observed while narrowing
+`test_opencode_identity_computation_stays_in_validator_and_resolver`: its import check
+inspects absolute imports only, so a module inside `core/handlers/model_hub/` can reach
+OpenCode identity helpers by relative import without tripping it. Pre-existing and left
+alone here — closing it requires ruling on `service.py`'s existing relative import of
+`STANDARD_OPENCODE_VENDOR_IDS`, which is a separate question from this stage.
+
## 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.py
index a549d3e12..22c3ceaa5 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -7,6 +7,7 @@ import inspect
import json
import re
import textwrap
+import threading
from datetime import datetime, timezone
from pathlib import Path
@@ -38,6 +39,7 @@ from core.handlers.model_hub.adapter import (
SourceObservation,
)
from core.handlers.model_hub.errors import ModelDiscoveryError
+from core.handlers.model_hub.identifiers import MODEL_ID_MAX_LENGTH
from core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent
from core.handlers.model_hub.oauth import (
NativeOAuthSourceStatus,
@@ -1818,6 +1820,37 @@ def test_agent_supply_rpc_refreshes_cli_presence_before_first_response(tmp_path)
assert calls == ["refresh"]
+def test_usage_summary_rpc_reads_the_ledger_off_the_controller_loop(tmp_path):
+ """Review 4960570946: the read blocks as hard as the write it mirrors.
+
+ Summarising reads the ledger file and the config store, and takes the same
+ lock a concurrent `record()` holds across `fsync()`. Awaited on the
+ controller loop that is every turn on this machine waiting on one settings
+ page, so it belongs in a worker thread exactly as the two writers already do.
+ """
+
+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+
+ service, _store, _adapter = _service(tmp_path)
+ summarised_on: list[threading.Thread] = []
+ real_summary = service.usage_summary
+
+ def observed(**kwargs):
+ summarised_on.append(threading.current_thread())
+ return real_summary(**kwargs)
+
+ service.usage_summary = observed
+
+ async def exercise() -> tuple[dict, threading.Thread]:
+ payload = await dispatch_model_hub_rpc(service, "usage_summary", {"days": 7})
+ return payload, threading.current_thread()
+
+ payload, loop_thread = asyncio.run(exercise())
+
+ assert payload["totals"]["requests"] == 0
+ assert summarised_on and loop_thread not in summarised_on
+
+
def test_agents_endpoint_projects_each_enabled_named_agent_live(tmp_path):
service, store, _adapter = _service(tmp_path)
store.requested_model = lambda backend: {
@@ -5712,6 +5745,78 @@ def test_admitted_model_ids_are_stored_in_their_canonical_form(tmp_path):
]
+def test_models_declared_inline_at_source_creation_are_admitted_the_same_way(tmp_path):
+ """Review 4960570946: the third admission path obeyed neither half.
+
+ A source may be created with its models inline, so this is the other way a
+ client-declared identifier enters config. Spelling is now settled by the
+ config validator, which every path goes through; the length bound stays with
+ the admission surfaces, because that same validator also loads files older
+ releases wrote and rejecting one of those would fail config load.
+ """
+
+ service, store, _ = _service(tmp_path)
+
+ def creation(models: list[dict]) -> dict:
+ return {
+ "kind": "api_key",
+ "vendor": "custom",
+ "display_name": "Inline models",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-test-transient-only",
+ "models": models,
+ }
+
+ asyncio.run(
+ _create_source(
+ service,
+ creation([{"id": " inline-model ", "origin": "manual", "reasoning_efforts": []}]),
+ )
+ )
+
+ stored = [model.id for model in store.config.sources[0].models]
+
+ assert "inline-model" in stored
+ assert " inline-model " not in stored
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ creation(
+ [
+ {
+ "id": "m" * (MODEL_ID_MAX_LENGTH + 1),
+ "origin": "manual",
+ "reasoning_efforts": [],
+ }
+ ]
+ )
+ )
+ )
+
+ assert exc_info.value.code == "discovery_failed"
+ assert len(store.config.sources) == 1
+
+
+def test_a_persisted_model_id_past_the_bound_still_loads(tmp_path):
+ """The bound is an admission rule, not a load rule.
+
+ Nothing stops a file written before the bound existed from holding a longer
+ identifier, and per the persisted-shape rule that file must still load. It
+ keeps its length and gains only the canonical spelling.
+ """
+
+ model = ModelHubModelConfig.from_payload(
+ {
+ "id": " " + "m" * (MODEL_ID_MAX_LENGTH + 1) + " ",
+ "origin": "manual",
+ "reasoning_efforts": [],
+ }
+ )
+
+ assert model.id == "m" * (MODEL_ID_MAX_LENGTH + 1)
+
+
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."""
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 1d6bfa176..b42a701c5 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -1131,6 +1131,13 @@ def test_opencode_identity_computation_stays_in_validator_and_resolver():
)
from pathlib import Path
+ OPENCODE_IDENTITY_NAMES = {
+ "STANDARD_OPENCODE_VENDOR_IDS",
+ "opencode_provider_id",
+ "opencode_model_id",
+ "parse_opencode_model_id",
+ }
+
class RawIdentityCalls(NodeVisitor):
def __init__(self):
self.calls = []
@@ -1161,7 +1168,15 @@ def test_opencode_identity_computation_stays_in_validator_and_resolver():
def visit_ImportFrom(self, node):
if node.module == "core.handlers.model_hub.identifiers":
- self.calls.extend(alias.name for alias in node.names)
+ # The OpenCode identity names only. That module also owns model-ID
+ # spelling, which the config validator is now the single owner of
+ # — a different property, guarded by its own owner test, and one
+ # this partition has nothing to say about.
+ self.calls.extend(
+ alias.name
+ for alias in node.names
+ if alias.name in OPENCODE_IDENTITY_NAMES
+ )
if node.module == "core.handlers.model_hub.resolver":
self.calls.extend(
alias.name
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 1303cf950..0df02adc8 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -37,6 +37,8 @@ DEEP_JSON_ARRAY = b"[" * 10_000 + b"0" + b"]" * 10_000
TURN_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"
+RPC = ROOT / "core/handlers/model_hub/rpc.py"
+V2_CONFIG = ROOT / "config/v2_config.py"
PROVENANCE = ROOT / "core/handlers/model_hub/provenance.py"
ROUTER = ROOT / "modules/agents/model_hub.py"
ADAPTER = ROOT / "vibe/model_hub_runtime/adapter.py"
@@ -562,6 +564,37 @@ def test_model_identity_is_decided_only_by_its_owner() -> None:
source = path.read_text(encoding="utf-8")
assert "canonical_model_id" in source
assert "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 goes
+ # through. The bound cannot follow it there — that validator also loads files
+ # older releases wrote — so it stays where a request can be refused.
+ config_source = V2_CONFIG.read_text(encoding="utf-8")
+ assert "normalized_model_id" in config_source
+ assert "MODEL_ID_MAX_LENGTH" not in config_source
+
+
+def test_the_usage_ledger_is_never_touched_from_the_controller_loop() -> None:
+ # Review 4960570946: the read blocks on the same lock the writers hold across
+ # fsync, so "off the loop" is a property of the ledger, not of whichever
+ # caller happened to remember it. Every RPC entry into it is checked here so
+ # the next one cannot quietly be the exception.
+ tree = _tree(RPC)
+ parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
+ touches = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Attribute) and node.attr in {"usage_summary", "usage"}
+ ]
+ assert touches
+ for touch in touches:
+ enclosing = touch
+ off_loop = False
+ while enclosing in parents:
+ enclosing = parents[enclosing]
+ if _call_name(enclosing) == "to_thread":
+ off_loop = True
+ break
+ assert off_loop, f"{touch.attr} is reached on the controller loop"
def test_g4_terminal_projection_has_no_execution_channel() -> None:
diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.py
index 6fc8e38d4..70899e863 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -755,24 +755,25 @@ def test_a_persisted_report_count_above_its_requests_is_repaired_on_read(
}
-def test_a_persisted_instant_is_published_in_the_shape_the_schema_promises(
+def test_a_day_in_another_valid_iso_spelling_still_lands_in_its_window(
tmp_path: Path,
) -> None:
- """Review 4960016618: the read surface publishes an offset-bearing date-time.
+ """Review 4960570946: the window compares days this module spelled.
- `datetime.fromisoformat` accepts spellings the API schema does not describe —
- naive, space-separated, minute-less — so the field carries what the parser
- understood rather than the text the file happened to hold. A naive value is
- read in the same local calendar the day buckets use.
+ `date.fromisoformat` also reads `20260723` and `2026-W30-4`, and the window
+ bounds are `YYYY-MM-DD` text. A row kept in the file's own spelling would
+ therefore sort outside every window it belongs to and vanish from the tab —
+ without even being counted as dropped, since it parsed perfectly well.
"""
ledger = _ledger(tmp_path)
ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ day = local_usage_day(NOW)
ledger.path.write_text(
json.dumps(
[
{
- "day": local_usage_day(NOW).isoformat(),
+ "day": day.strftime("%Y%m%d"),
"source_id": "src_a",
"model_id": "model-x",
"requests": 1,
@@ -780,17 +781,110 @@ def test_a_persisted_instant_is_published_in_the_shape_the_schema_promises(
"input_tokens": 4,
"cached_input_tokens": 0,
"output_tokens": 2,
- "last_metered_at": "2026-07-23 12:00",
+ "last_metered_at": NOW.isoformat(),
}
]
),
encoding="utf-8",
)
- published = ledger.window(days=30, now=NOW)[0]["last_metered_at"]
+ rows = ledger.window(days=30, now=NOW)
+
+ assert [row["day"] for row in rows] == [day.isoformat()]
+ assert ledger.summary(days=30, now=NOW)["totals"]["input_tokens"] == 4
+
+
+def test_every_decode_failure_degrades_the_ledger_instead_of_raising(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Review 4960570946: degradation is by failure category, not by shape.
+
+ `JSONDecodeError` is only one way a file fails to decode. Invalid UTF-8 and
+ an integer past the digit limit both raise a plain `ValueError`, deep nesting
+ raises `RecursionError`, and any of them escaping the ledger would fail the
+ read route and then stop metering for good — the loud failure this
+ degradation exists to prevent.
+ """
+
+ payloads = (
+ b"\xff\xfe not utf-8",
+ ("[" + "9" * 8000 + "]").encode("utf-8"),
+ b"[" * 10_000 + b"0" + b"]" * 10_000,
+ )
+ for payload in payloads:
+ ledger = _ledger(tmp_path)
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ ledger.path.write_bytes(payload)
- assert published == datetime(2026, 7, 23, 12, 0).astimezone().isoformat()
- assert datetime.fromisoformat(published).tzinfo is not None
+ with caplog.at_level(logging.WARNING):
+ assert ledger.window(days=30, now=NOW) == []
+
+ assert any("unreadable" in record.message for record in caplog.records)
+ caplog.clear()
+ # Metering keeps working, and the next write replaces the broken file.
+ ledger.record(
+ source_id="src_a",
+ model_id="model-x",
+ usage=ProtocolUsageReport.of(
+ input_tokens=4,
+ cached_input_tokens=0,
+ output_tokens=2,
+ ),
+ at=NOW,
+ )
+ assert ledger.summary(days=30, now=NOW)["totals"]["requests"] == 1
+
+
+def test_a_persisted_instant_is_published_in_the_shape_the_schema_promises(
+ tmp_path: Path,
+) -> None:
+ """Reviews 4960016618 and 4960570946: this module decides the spelling.
+
+ `datetime.fromisoformat` accepts far more than RFC 3339 does — naive,
+ space-separated, and, after an offset, seconds. Republishing the parsed value
+ in the file's own offset only moved the problem, so the file now supplies the
+ instant and the module supplies the spelling: UTC, hence `+00:00`, whatever
+ was written. A naive value is still read in the local calendar the day
+ buckets use.
+ """
+
+ ledger = _ledger(tmp_path)
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ written = {
+ "naive": "2026-07-23 12:00",
+ # A valid `fromisoformat` spelling with an offset RFC 3339 cannot express.
+ "second_bearing_offset": "2026-07-23T12:00:00+00:00:30",
+ }
+ ledger.path.write_text(
+ json.dumps(
+ [
+ {
+ "day": local_usage_day(NOW).isoformat(),
+ "source_id": f"src_{key}",
+ "model_id": "model-x",
+ "requests": 1,
+ "token_reports": 1,
+ "input_tokens": 4,
+ "cached_input_tokens": 0,
+ "output_tokens": 2,
+ "last_metered_at": value,
+ }
+ for key, value in written.items()
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ published = {
+ row["source_id"]: row["last_metered_at"] for row in ledger.window(days=30, now=NOW)
+ }
+
+ assert published["src_naive"] == (
+ datetime(2026, 7, 23, 12, 0).astimezone(timezone.utc).isoformat()
+ )
+ assert published["src_second_bearing_offset"] == "2026-07-23T11:59:30+00:00"
+ assert all(value.endswith("+00:00") for value in published.values())
def test_a_written_row_is_validated_the_same_way_a_persisted_one_is(