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 the metering facts and the write clock one owner each

cyha481bc864fc9
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 7f9b9f545..2d31e8d1b 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -592,7 +592,8 @@ class ModelHubService:
paths.get_state_dir() / "model_hub_turn_provenance.json"
)
self.usage = usage or BoundedUsageLedger(
- paths.get_state_dir() / "model_hub_usage.json"
+ paths.get_state_dir() / "model_hub_usage.json",
+ now=now,
)
self.native_oauth_adapter = native_oauth_adapter or UnavailableNativeOAuthAdapter()
self.oauth_flows = oauth_flows or OAuthFlowRegistry(
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 2acdc5a61..daafb9c59 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -98,9 +98,10 @@ class _TurnExecution:
# without reaching the end of the chunk loop can still read the tokens the
# upstream had already reported.
wire_state: _SSEWireState | None = None
- # The same fact for a response the gateway buffered whole, which has no wire
- # tracker to read it from.
+ # The same two facts for a response the gateway buffered whole, which has no
+ # wire tracker to read them from.
buffered_usage: ProtocolUsageReport | None = None
+ buffered_outcome: StreamTerminalOutcome | None = None
usage_recorded: bool = False
@property
@@ -116,6 +117,27 @@ class _TurnExecution:
return self.wire_state.usage
return self.buffered_usage
+ @property
+ def reached_model(self) -> bool:
+ """Whether this turn's upstream call was billed, whichever shape it took.
+
+ Sibling of `reported_usage`, for the same reason and with the same owner:
+ a boundary that ends the turn early cannot know which shape the response
+ took. Leaving it to the endings meant each one answered in the vocabulary
+ of the shape it happened to see — the boundary read a wire tracker a
+ buffered turn never has, so a complete upstream body that reported no
+ tokens counted as never having reached the model.
+
+ The buffered half is the observation the gateway already made of the whole
+ body: a complete model answer was served upstream exactly as a stream that
+ reached its terminal was, and an error envelope reached no model exactly as
+ a stream that forwarded no output did.
+ """
+
+ if self.wire_state is not None:
+ return self.wire_state.reached_model
+ return self.buffered_outcome == "served"
+
@dataclass(frozen=True)
class _RenderedTurnOutcome:
@@ -176,7 +198,10 @@ class ModelHubTurnGateway:
self.usage = (
usage
or getattr(service, "usage", None)
- or BoundedUsageLedger(paths.get_state_dir() / "model_hub_usage.json")
+ or BoundedUsageLedger(
+ paths.get_state_dir() / "model_hub_usage.json",
+ now=self._now,
+ )
)
self._start_lock = asyncio.Lock()
self._runner: web.AppRunner | None = None
@@ -616,13 +641,15 @@ class ModelHubTurnGateway:
async for chunk in handle.stream:
payload.extend(chunk)
# Published before settling, not after: settling can be cancelled by a
- # downstream disconnect, and a report only this frame's local knew about
+ # downstream disconnect, and facts only this frame's local knew about
# would leave the boundary with nothing to meter.
- execution.buffered_usage = observe_protocol_response(
+ observation = observe_protocol_response(
protocol,
streamed=False,
data=bytes(payload),
- ).usage
+ )
+ execution.buffered_usage = observation.usage
+ execution.buffered_outcome = observation.outcome
outcome, settlement = await self._settle_turn_handle(
execution,
terminalizer,
@@ -635,11 +662,7 @@ class ModelHubTurnGateway:
)
assert outcome is not None
assert settlement.decision is not None
- await self._record_usage(
- execution,
- usage=execution.reported_usage,
- served=settlement.decision.action == "return",
- )
+ await self._record_usage(execution)
if settlement.decision.action != "return":
return self._outcome_response(
outcome,
@@ -682,11 +705,7 @@ class ModelHubTurnGateway:
terminalizer,
settlement,
)
- await self._record_usage(
- execution,
- usage=wire_state.usage,
- served=wire_state.reached_model,
- )
+ await self._record_usage(execution)
await self._write_stream_terminal_copy(
response,
protocol,
@@ -697,13 +716,7 @@ class ModelHubTurnGateway:
await self._downstream_io(response.write_eof())
return response
- async def _record_usage(
- self,
- execution: _TurnExecution,
- *,
- usage: ProtocolUsageReport | None,
- served: bool,
- ) -> None:
+ async def _record_usage(self, execution: _TurnExecution) -> None:
"""Fold one forwarded upstream call into the usage ledger, best-effort.
A call counts when it reached the model: either the hub returned upstream
@@ -718,11 +731,18 @@ class ModelHubTurnGateway:
already metered by ``ModelHubService._meter_call``, so no call is counted
twice and none is missed.
- Sole metering owner for the boundary. Several endings can reach it for one
- forwarded call — a stream that finished and then failed to flush, a
- disconnect that raced the terminal chunk — so the first ending to describe
- it wins and every later one is a no-op. One call is one request, whatever
- killed it.
+ Sole metering owner for the boundary, and it takes only the turn. Several
+ endings can reach it for one forwarded call — a stream that finished and
+ then failed to flush, a disconnect that raced the terminal chunk — so the
+ first ending to describe it wins and every later one is a no-op. One call
+ is one request, whatever killed it.
+
+ Which is why no ending is asked what the call did. Both facts are read from
+ the turn itself, so an ending is only ever a *when*, never a *what*: a
+ boundary that ends the turn early sees one shape's evidence and cannot
+ answer for the other, and every ending that answered locally answered
+ differently. A future ending cannot get it wrong, because it has nothing to
+ get wrong.
The ledger read-modify-write is file I/O, so it runs off the event loop;
metering is a report, never a control input, and a ledger failure must not
@@ -732,7 +752,8 @@ class ModelHubTurnGateway:
resolved = execution.resolved
if execution.usage_recorded or resolved is None:
return
- if not served and usage is None:
+ usage = execution.reported_usage
+ if not execution.reached_model and usage is None:
return
execution.usage_recorded = True
try:
@@ -787,17 +808,10 @@ class ModelHubTurnGateway:
termination_origin: HandleTerminationOrigin,
) -> None:
# Ahead of the settlement guard: a downstream disconnect can arrive after
- # the upstream already reported its tokens, so the turn was billed even
- # though the request path never reached its own metering call. The recorder
- # is idempotent, so an ending that already metered costs nothing here, and
- # it reads the turn's own report rather than one shape's tracker — a
- # buffered response cancelled mid-settlement was billed the same way.
- wire_state = execution.wire_state
- await self._record_usage(
- execution,
- usage=execution.reported_usage,
- served=wire_state is not None and wire_state.reached_model,
- )
+ # the upstream already answered, so the turn was billed even though the
+ # request path never reached its own metering call. The recorder is
+ # idempotent, so an ending that already metered costs nothing here.
+ await self._record_usage(execution)
if execution.settlement_recorded:
return
_outcome, settlement = await self._settle_turn_handle(
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index 806d4765b..a79f10082 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -26,7 +26,7 @@ import tempfile
import threading
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
-from typing import Final, Optional
+from typing import Callable, Final, Optional
from .identifiers import canonical_model_id
from .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReport
@@ -59,6 +59,20 @@ _COUNTER_SUBSETS: Final = (
)
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _aware(moment: datetime) -> datetime:
+ """Read one caller-supplied moment, taking a naive one as local time.
+
+ The same rule `_instant` applies to persisted text, so a naive value means the
+ same thing however it reached this module.
+ """
+
+ return moment if moment.tzinfo is not None else moment.astimezone()
+
+
def local_usage_day(moment: datetime) -> date:
"""Bucket one moment into a local-calendar day.
@@ -227,10 +241,15 @@ class BoundedUsageLedger:
*,
max_rows: int = USAGE_MAX_ROWS,
retention_days: int = USAGE_RETENTION_DAYS,
+ now: Callable[[], datetime] = _utc_now,
):
self.path = path
self.max_rows = max_rows
self.retention_days = retention_days
+ # Not a second clock: hub callers pass their own so a fixed service clock
+ # still decides every day this ledger writes. What matters is that this one
+ # is *read* where the write happens rather than handed in from a call.
+ self._now = now
self._lock = threading.RLock()
def _read(self) -> list[dict]:
@@ -310,32 +329,44 @@ class BoundedUsageLedger:
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.
+
+ `at` is a value the caller captured when its call ended; the horizon and
+ the ceiling below are a reading taken where the write happens. The two are
+ not interchangeable, because metering runs off the event loop and reaches
+ this lock in whatever order the executor ran it: a call stamped just before
+ local midnight can persist after one stamped just after it. Handing the
+ captured value to a ledger-wide bound would then date the newer row into
+ the future and drop it. So `at` decides this call's own bucket and stamp
+ and nothing else — up to the moment it is persisted, since nothing is
+ metered later than the write that records it.
"""
- 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 call with an unusable identifier",
- extra={"source_id_usable": canonical_model_id(source_id) is not None},
- )
- return
with self._lock:
+ persisted_at = _aware(self._now())
+ metered_at = min(_aware(at), persisted_at)
+ increment = _normalize_row(
+ {
+ "day": local_usage_day(metered_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": metered_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 call with an unusable identifier",
+ extra={"source_id_usable": canonical_model_id(source_id) is not None},
+ )
+ return
rows = {_row_key(row): row for row in self._read()}
existing = rows.get(_row_key(increment))
if existing is None:
@@ -346,10 +377,10 @@ class BoundedUsageLedger:
existing["last_metered_at"],
increment["last_metered_at"],
)
- retained = self._retained(list(rows.values()), at)
+ retained = self._retained(list(rows.values()), persisted_at)
self._write(retained)
- def _retained(self, rows: list[dict], now: datetime) -> list[dict]:
+ def _retained(self, rows: list[dict], measured: 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
@@ -366,9 +397,10 @@ class BoundedUsageLedger:
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` is read at the write, never handed in from a call — see `record`.
"""
- 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()
newest = today.isoformat()
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index dd9dbe2e8..1aff07b7e 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -393,6 +393,66 @@ instead of costing a review round.
shape a persisted row can use to outrank the present (future day, future instant, both)
rather than listing the ones that are handled.
+### Round 7 (head `ac907286b`)
+
+Two P2 findings. One of them is class C again — a fourth findings-bearing head for
+that class — and the other is a regression introduced by round 6's own fix.
+
+- **Class C — metering population coverage, closed by removing the question**
+ (`core/handlers/model_hub/turn_gateway.py`). Round 3 gave "what tokens did upstream
+ report" one owner, `_TurnExecution.reported_usage`, because a boundary that ends the
+ turn early cannot know which shape the response took. Its sibling question — "did
+ this call reach the model" — was left to the endings, and each answered in the
+ vocabulary of the shape it happened to see: the buffered ending read the settlement
+ decision, the streaming ending read the wire tracker, and the boundary read the wire
+ tracker *and a buffered turn never has one*, so `served` there was structurally
+ `False`. A complete upstream body carrying no usage block, cancelled downstream
+ mid-settlement, was therefore never counted. That is why the class kept recurring at
+ a new site each round: the finding is not any one ending, it is that endings answer
+ at all.
+
+ So the closure is not a third owner but one fewer question. `reached_model` joins
+ `reported_usage` on `_TurnExecution` — reading `wire_state.reached_model` for a
+ stream and the buffered observation's own `outcome == "served"` otherwise, which the
+ gateway already computed and discarded — and `_record_usage` now takes only the turn.
+ An ending is a *when*, never a *what*; an ending added later cannot get this wrong
+ because it has nothing to pass in.
+
+- **A ledger-wide bound cannot come from one call's stamp**
+ (`core/handlers/model_hub/usage.py`). Round 6 fixed retention by measuring the window
+ against a clock instead of the file — and then handed it `at`, the *captured* moment
+ the call ended. Metering runs off the event loop, so concurrent calls reach the lock
+ in whatever order the executor ran them: a call stamped just before local midnight
+ persisting after one stamped just after it dated the newer row into the future and
+ dropped it, and a same-day inversion clamped a newer `last_metered_at` backward.
+
+ `at` and the horizon are the same clock read at two different times, and the gap is
+ the whole point — so the ledger now takes the clock, not a moment, and reads it under
+ the lock where the write happens. `at` decides this call's bucket and stamp and
+ nothing else, bounded by that reading because nothing is metered later than the write
+ that records it. The hub's callers pass their own clock in, so a fixed service clock
+ still decides every day the ledger writes; this is one clock read at the right place,
+ not a second clock. Round 6's ceiling property is unchanged and now holds under
+ concurrency.
+
+Three invariant tests, each proven to fail without its fix.
+`test_a_cancelled_buffered_turn_is_counted_even_when_it_reported_no_tokens` is the
+existing cancellation test with the one thing removed that was carrying it, the usage
+block; without the fix it fails with `KeyError: 'requests'`, nothing metered at all.
+`test_no_ending_of_a_turn_decides_for_itself_what_the_call_did` asserts the closure
+rather than today's three endings: every `_record_usage` call passes the turn and
+nothing else. `test_a_write_never_rewrites_what_a_later_stamped_write_already_persisted`
+seeds one row of every shape a later-stamped concurrent write can leave behind — an
+instant this write has not reached, and a day it has not reached — and asserts the
+earlier-stamped write contributes its own row and changes nothing else; without the fix
+it reproduces both harms at once, one row dropped and one clamped backward.
+
+The ledger's clock also removes a latent test defect: retention was previously measured
+against whatever moment a test happened to pass as `at`, so the fixed 2026-07-29 clock
+in `test_model_hub_l3.py` would have started failing once the wall clock drifted past
+the retention horizon from it. Ledger construction now carries the same fake clock as
+its service.
+
## 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 ad8589c31..920272156 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -330,7 +330,10 @@ def _service(tmp_path, adapter=None):
adapter=adapter,
events=BoundedEventLog(tmp_path / "events.json"),
provenance=BoundedProvenanceStore(tmp_path / "provenance.json"),
- usage=BoundedUsageLedger(tmp_path / "usage.json"),
+ usage=BoundedUsageLedger(
+ tmp_path / "usage.json",
+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
+ ),
native_oauth_adapter=adapter,
oauth_flows=OAuthFlowRegistry(
tmp_path / "oauth_flows.json",
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 95d8cb6ba..8708df3e7 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -1160,7 +1160,7 @@ def _service(
adapter=ProbeAdapter(outcomes or [], live_handles),
events=BoundedEventLog(tmp_path / "events.json"),
provenance=BoundedProvenanceStore(tmp_path / "provenance.json"),
- usage=BoundedUsageLedger(tmp_path / "usage.json"),
+ usage=BoundedUsageLedger(tmp_path / "usage.json", now=lambda: NOW),
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
now=lambda: NOW,
requested_model_override=store.requested_model,
@@ -6289,6 +6289,90 @@ def test_a_buffered_response_cancelled_while_settling_is_still_metered(
asyncio.run(exercise())
+def test_a_cancelled_buffered_turn_is_counted_even_when_it_reported_no_tokens(
+ tmp_path: Path,
+) -> None:
+ """Review 4964520496: a request is self-measured, so a silent vendor still owes one.
+
+ Same cancellation as above with the one thing removed that was carrying it —
+ the usage block. `requests` is measured by our own code and must not depend on
+ what upstream chose to report, which is exactly what `token_reports` staying
+ at zero records.
+ """
+
+ async def exercise() -> None:
+ source = _source("src_meterbuf02", "Cancelled silent turn")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(
+ RawOutcomeKind.SUCCESS,
+ status=200,
+ source_id=source.id,
+ stream_started=True,
+ ),
+ (b'{"output":[{"type":"message","content":[]}]}',),
+ )
+ ],
+ )
+ settling = asyncio.Event()
+ release = asyncio.Event()
+ settle_handle_outcome = service.settle_handle_outcome
+
+ async def blocked_settlement(*args: object, **kwargs: object):
+ settling.set()
+ await release.wait()
+ return await settle_handle_outcome(*args, **kwargs)
+
+ service.settle_handle_outcome = blocked_settlement
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_buffered_silent_cancel",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=False,
+ )
+
+ turn = asyncio.create_task(gateway._handle_request(request))
+ await asyncio.wait_for(settling.wait(), timeout=1)
+ turn.cancel()
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(turn, timeout=1)
+
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1
+ assert metered["token_reports"] == 0
+
+ asyncio.run(exercise())
+
+
+def test_no_ending_of_a_turn_decides_for_itself_what_the_call_did() -> None:
+ """The metering facts have one owner, so an ending is a *when*, not a *what*.
+
+ Endings that answered locally answered in the vocabulary of the shape they
+ happened to see, and the boundary — which can see either — got the buffered
+ one wrong. An ending added later is covered by construction if it cannot pass
+ the answer in, so that is what is asserted rather than today's three endings.
+ """
+
+ path = Path(__file__).parents[1] / "core/handlers/model_hub/turn_gateway.py"
+ calls = [
+ node
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8")))
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "_record_usage"
+ ]
+
+ assert calls, "the gateway must still meter the calls whose body it forwards"
+ assert all(len(call.args) == 1 and not call.keywords for call in calls)
+
+
def test_gateway_meters_a_failed_turn_that_upstream_already_billed(
tmp_path: Path,
) -> None:
diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.py
index 56c447821..0e343d348 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -382,7 +382,23 @@ def test_a_document_with_no_readable_report_yields_none(payload: dict) -> None:
# --- Persistence: bounded, credential-free, and safe to load -----------------
+class _Clock:
+ """The moment a write happens, which a test moves independently of `at`.
+
+ They are the same clock read at two times, and the gap between them is the
+ point: `at` is captured when a call ends, this is read when its row is
+ persisted, and metering runs off the event loop in between.
+ """
+
+ def __init__(self, moment: datetime) -> None:
+ self.moment = moment
+
+ def __call__(self) -> datetime:
+ return self.moment
+
+
def _ledger(tmp_path: Path, **kwargs) -> BoundedUsageLedger:
+ kwargs.setdefault("now", _Clock(NOW + timedelta(hours=12)))
return BoundedUsageLedger(tmp_path / "state" / "usage.json", **kwargs)
@@ -505,12 +521,14 @@ def test_a_requested_window_is_clamped_to_what_is_retained(
def test_retention_drops_rows_past_the_horizon(tmp_path: Path) -> None:
- ledger = _ledger(tmp_path, retention_days=3)
+ clock = _Clock(NOW - timedelta(days=10))
+ ledger = _ledger(tmp_path, retention_days=3, now=clock)
- ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW - timedelta(days=10))
+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=clock.moment)
assert len(ledger.window(days=3, now=NOW - timedelta(days=10))) == 1
- # Recording under a later day is what advances the horizon.
+ # Writing under a later day is what advances the horizon.
+ clock.moment = NOW
ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)
persisted = json.loads(ledger.path.read_text(encoding="utf-8"))
assert [row["day"] for row in persisted] == [local_usage_day(NOW).isoformat()]
@@ -578,7 +596,8 @@ def test_a_new_call_is_metered_whatever_recency_the_ledger_already_claims(
without editing this test.
"""
- ledger = _ledger(tmp_path, max_rows=3)
+ clock = _Clock(NOW)
+ ledger = _ledger(tmp_path, max_rows=3, now=clock)
ahead = NOW + timedelta(days=400)
ledger.path.parent.mkdir(parents=True, exist_ok=True)
ledger.path.write_text(
@@ -607,7 +626,41 @@ def test_a_new_call_is_metered_whatever_recency_the_ledger_already_claims(
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())
+ assert all(
+ datetime.fromisoformat(row["last_metered_at"]) <= clock.moment for row in rows.values()
+ )
+
+
+def test_a_write_never_rewrites_what_a_later_stamped_write_already_persisted(
+ tmp_path: Path,
+) -> None:
+ """Review 4964520496: one call's stamp cannot bound the whole ledger.
+
+ Metering runs off the event loop, so concurrent calls reach the lock in
+ whatever order the executor ran them, not in stamp order. Seed one row of
+ every shape a later-stamped write can leave behind — an instant this write
+ has not reached, and a day it has not reached — then let the earlier-stamped
+ write land on top of them. It contributes its own row and nothing else;
+ stating that rather than listing the two shapes covers whatever a later write
+ persists next.
+ """
+
+ clock = _Clock(NOW)
+ ledger = _ledger(tmp_path, now=clock)
+ for model_id, stamp in (
+ ("model-later-instant", NOW + timedelta(minutes=5)),
+ ("model-later-day", NOW + timedelta(days=1)),
+ ):
+ clock.moment = stamp
+ ledger.record(source_id="src_a", model_id=model_id, usage=None, at=stamp)
+ persisted = {row["model_id"]: row for row in json.loads(ledger.path.read_text("utf-8"))}
+
+ # Captured before both of them, reaching the lock after both.
+ ledger.record(source_id="src_a", model_id="model-earlier", usage=None, at=NOW)
+
+ after = {row["model_id"]: row for row in json.loads(ledger.path.read_text("utf-8"))}
+ assert {model_id: after.get(model_id) for model_id in persisted} == persisted
+ assert after["model-earlier"]["requests"] == 1
@pytest.mark.parametrize(