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): key a metered model by its pair, bound conversion, abandon writes

cyha9c7a184b401
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index e36ffeda9..11558f877 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -110,7 +110,7 @@ from .resolver import (
source_runnable,
)
from .revocations import CredentialRevocationJournal
-from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, UsageWriter
+from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity, UsageWriter
CONTRACT_VERSION = 6
AGENT_CHAIN_CONTRACT_VERSION = 6
@@ -3630,16 +3630,24 @@ class ModelHubService:
leaked to a caller, and it silently dropped the label of every identity the
key fold exists for.
- A model's own identity is its label, which matters for the same reason:
- a folded row publishes a key, not the identifier the user typed.
+ What it hands over is therefore the shape config actually has — Sources, each
+ carrying the models listed under it — and not a flat map per key level. A
+ metered model's identity is the pair, so a flat model map cannot say which
+ Source an ID came from, and answers for one Source with another's models.
"""
config = self.store.load()
return self.usage.summary(
days=days,
now=self.now(),
- source_labels={source.id: source.display_name for source in config.sources},
- model_labels={model.id: model.id for source in config.sources for model in source.models},
+ identities=[
+ SourceIdentity(
+ source_id=source.id,
+ label=source.display_name,
+ model_ids=[model.id for model in source.models],
+ )
+ for source in config.sources
+ ],
)
def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index 7a310b047..672739503 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -22,8 +22,10 @@ from __future__ import annotations
import asyncio
import json
import logging
+import queue
import threading
-from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import Executor
+from concurrent.futures import Future as CFuture
from dataclasses import dataclass, replace
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
@@ -65,14 +67,42 @@ def _utc_now() -> datetime:
return datetime.now(timezone.utc)
+def _carried(moment: datetime) -> Optional[datetime]:
+ """Carry one moment through every conversion this module performs, or refuse it.
+
+ `datetime` conversion is not total. A value near either end of the representable
+ range, offset far enough, leaves that range on the way to another zone and raises
+ `OverflowError` — which is an `ArithmeticError`, so it passes straight through a
+ handler written for bad data and takes the flush task with it, stopping metering
+ for the rest of the process while the row that caused it stays on disk.
+
+ Bounding the accepted years would leave a free parameter for the next value to
+ probe. The conversion itself is the bound instead: what this module can carry is
+ what its own conversions return, measured rather than declared. Both are
+ performed here — UTC for the spelling it publishes, local for the day it buckets
+ — so nothing that escapes this door can raise at either of them later.
+ """
+
+ try:
+ carried = moment.astimezone(timezone.utc)
+ carried.astimezone()
+ except (OverflowError, OSError, ValueError):
+ return None
+ return carried
+
+
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.
+
+ Total, unlike the persisted-read door: a caller is reporting a call an upstream
+ already billed, and a moment this module cannot carry is a reason to date the row
+ by the only instant it can measure, never a reason to lose the row.
"""
- return moment if moment.tzinfo is not None else moment.astimezone()
+ return _carried(moment) or _utc_now()
def local_usage_day(moment: datetime) -> date:
@@ -82,7 +112,7 @@ def local_usage_day(moment: datetime) -> date:
day boundary here is the user's midnight, not UTC's.
"""
- return moment.astimezone().date()
+ return _aware(moment).astimezone().date()
def _bounded_counter(value: object) -> int:
@@ -130,6 +160,10 @@ def _instant(value: object) -> Optional[datetime]:
notion of what a day is.
A naive value is read as local time, the same calendar the day buckets use.
+
+ Parsing is not the whole of reading it: a value `fromisoformat` accepts may still
+ be one no conversion can carry, so it goes through `_carried` before it escapes
+ and degrades to absent when it cannot make the trip.
"""
if not isinstance(value, str) or _calendar_day(value) is not None:
@@ -138,7 +172,7 @@ def _instant(value: object) -> Optional[datetime]:
parsed = datetime.fromisoformat(value)
except ValueError:
return None
- return parsed if parsed.tzinfo is not None else parsed.astimezone()
+ return _carried(parsed)
def _timestamp(value: object) -> Optional[str]:
@@ -159,7 +193,7 @@ def _timestamp(value: object) -> Optional[str]:
parsed = _instant(_text(value))
if parsed is None:
return None
- return parsed.astimezone(timezone.utc).isoformat()
+ return parsed.isoformat()
def _normalize_row(row: object) -> Optional[dict]:
@@ -196,25 +230,55 @@ def _normalize_row(row: object) -> Optional[dict]:
return normalized
-def _keyed_labels(labels: Optional[Mapping[str, Optional[str]]]) -> dict[str, Optional[str]]:
- """Key one identity-to-label mapping the way the rows it will join were keyed.
+@dataclass(frozen=True)
+class SourceIdentity:
+ """One Source as config holds it, for joining onto the rows metered under it.
+
+ Nested rather than two flat maps, because a metered model's identity *is* the
+ pair: the same common model ID lives on several Sources, and a flat model map
+ cannot say which one it came from — it answered for a model removed from Source A
+ as long as Source B still listed it, labelling a retained row as though the
+ identity were still there. Arity is the whole of that defect, so it is carried in
+ the type rather than in a rule each caller has to remember.
+
+ `label` is the only genuinely caller-owned text here. A model's label is its own
+ identity, which the ledger can derive, and which matters only because a folded row
+ publishes a key rather than the identifier the user typed.
+ """
+
+ source_id: str
+ label: Optional[str] = None
+ model_ids: Sequence[str] = ()
+
- The read half of the rule `record_many` applies on the write half: an identity
- a caller holds is not the key its rows carry, and a long one differs from it
+def _keyed_identities(
+ identities: Optional[Sequence[SourceIdentity]],
+) -> tuple[dict[str, Optional[str]], dict[tuple[str, str], str]]:
+ """Key what config holds the way the rows it will join were keyed.
+
+ The read half of the rule `record_many` applies on the write half: an identity a
+ caller holds is not the key its rows carry, and a long one differs from it
entirely. Deriving here rather than in the caller is what keeps a join from
- silently missing exactly the identities the fold exists for.
+ silently missing exactly the identities the fold exists for — and keying both
+ levels here is what keeps a model's join inside its own Source.
Two identities that key the same are the same identity spelled differently —
- `usage_ledger_key` is injective over anything else — so the later one wins, as
- it would in the mapping the caller built.
+ `usage_ledger_key` is injective over anything else — so the later one wins, as it
+ would in the mapping a caller built.
"""
- keyed: dict[str, Optional[str]] = {}
- for identity, label in (labels or {}).items():
- key = usage_ledger_key(identity)
- if key is not None:
- keyed[key] = label
- return keyed
+ sources: dict[str, Optional[str]] = {}
+ models: dict[tuple[str, str], str] = {}
+ for identity in identities or ():
+ source_key = usage_ledger_key(identity.source_id)
+ if source_key is None:
+ continue
+ sources[source_key] = identity.label
+ for model_id in identity.model_ids:
+ model_key = usage_ledger_key(model_id)
+ if model_key is not None:
+ models[(source_key, model_key)] = model_id
+ return sources, models
def _recency(row: dict) -> tuple[str, datetime]:
@@ -454,7 +518,7 @@ class BoundedUsageLedger:
today = local_usage_day(measured)
oldest = (today - timedelta(days=self.retention_days - 1)).isoformat()
newest = today.isoformat()
- ceiling = measured.astimezone(timezone.utc).isoformat()
+ ceiling = _aware(measured).isoformat()
placed = []
for row in rows:
if not oldest <= row["day"] <= newest:
@@ -481,19 +545,24 @@ class BoundedUsageLedger:
*,
days: int = USAGE_DEFAULT_WINDOW_DAYS,
now: datetime,
- source_labels: Optional[Mapping[str, Optional[str]]] = None,
- model_labels: Optional[Mapping[str, Optional[str]]] = None,
+ identities: Optional[Sequence[SourceIdentity]] = None,
) -> dict:
"""Aggregate the window into the read shape the settings page consumes.
Labels are joined here rather than persisted, because a display name is
user-supplied text this ledger has no business storing and a join keeps a
- rename visible immediately instead of freezing old copies. They arrive as
- *identities* and are keyed here rather than by the caller, because a row is
- keyed and the component holding config is not the one that knows that: the
- caller that keyed its own map looked a label up by `row["source_id"]`, so a
- source whose ID is past the admission bound reported no label while still
- existing, and its renames never appeared.
+ rename visible immediately instead of freezing old copies. What arrives is
+ what config holds — identities, nested by Source — and this method keys it,
+ because a row is keyed and the component holding config is not the one that
+ knows that: the caller that keyed its own map looked a label up by
+ `row["source_id"]`, so a source whose ID is past the admission bound reported
+ no label while still existing, and its renames never appeared.
+
+ The nesting is the other half of the same rule. A model's identity is its
+ Source and its ID together, so a flat model map answers for the wrong Source
+ whenever a common model ID is listed on more than one — which is every
+ interesting case. `SourceIdentity` makes that arity part of the argument's
+ type, so there is no keying convention left for a caller to hold.
A model's label is its own identity, which only matters for a folded row.
There the key is a head plus a digest, so a tab drawing `model_id` would
@@ -503,8 +572,7 @@ class BoundedUsageLedger:
bounded_days = max(1, min(int(days), self.retention_days))
today = local_usage_day(now)
rows = self.window(days=bounded_days, now=now)
- keyed_source_labels = _keyed_labels(source_labels)
- keyed_model_labels = _keyed_labels(model_labels)
+ keyed_source_labels, keyed_model_labels = _keyed_identities(identities)
totals = _empty_totals()
sources: dict[str, dict] = {}
@@ -531,7 +599,7 @@ class BoundedUsageLedger:
row["model_id"],
{
"model_id": row["model_id"],
- "label": keyed_model_labels.get(row["model_id"]),
+ "label": keyed_model_labels.get((row["source_id"], row["model_id"])),
**_empty_totals(),
},
)
@@ -562,15 +630,60 @@ class BoundedUsageLedger:
}
+class _AbandonableWriter(Executor):
+ """One serialized worker for ledger writes that the process can walk away from.
+
+ `ThreadPoolExecutor` is the obvious way to spell "one worker thread", and it is
+ the one mechanism this module may not use: its workers are non-daemon and it
+ registers an `atexit` hook that joins them. A worker wedged in `fsync` on an
+ unresponsive disk therefore holds interpreter shutdown open forever — *after*
+ every bounded wait in this module has already returned and told its caller the
+ write was unfinished. Bounding the coroutine is not the same as being able to
+ abandon the work, and this is the resource where only the second one counts:
+ metering is optional, so a stop or restart must never wait on it.
+
+ A daemon thread says exactly that, and CPython does not join one at shutdown.
+ The `Executor` interface is kept so `run_in_executor` still bridges the thread
+ to the loop; a worker is started on the first write and lives as long as the
+ process, which is the same single idle thread the pool cost.
+ """
+
+ def __init__(self) -> None:
+ self._queue: "queue.SimpleQueue[tuple[CFuture, Callable, tuple, dict]]" = queue.SimpleQueue()
+ self._worker = threading.Thread(
+ target=self._serve,
+ name="model-hub-usage",
+ daemon=True,
+ )
+ self._worker.start()
+
+ def submit(self, fn: Callable, /, *args: object, **kwargs: object) -> CFuture:
+ future: CFuture = CFuture()
+ self._queue.put((future, fn, args, kwargs))
+ return future
+
+ def _serve(self) -> None:
+ while True:
+ future, fn, args, kwargs = self._queue.get()
+ if not future.set_running_or_notify_cancel():
+ continue
+ try:
+ result = fn(*args, **kwargs)
+ except BaseException as exc: # noqa: BLE001 - relayed to the waiting future
+ future.set_exception(exc)
+ else:
+ future.set_result(result)
+
+
_LEDGER_EXECUTOR_LOCK: Final = threading.Lock()
-_LEDGER_EXECUTOR: Optional[ThreadPoolExecutor] = None
+_LEDGER_EXECUTOR: Optional[_AbandonableWriter] = None
# How long a metering caller waits for its own row to reach the disk. Sized for a
# local read-modify-write and an fsync plus scheduling slack, which is orders of
# magnitude under it, so nothing but a disk that has stopped answering gets here.
_DURABILITY_WAIT_SECONDS: Final = 2.0
-def _ledger_executor() -> ThreadPoolExecutor:
+def _ledger_executor() -> _AbandonableWriter:
"""The one thread ledger writes run on, created when something is first metered.
Deliberately not the loop's default executor. `record_many` holds the ledger's
@@ -580,12 +693,15 @@ def _ledger_executor() -> ThreadPoolExecutor:
for no gain, since the lock admits one writer regardless. Owning the
serialization makes it explicit instead of emergent, and it costs a single
idle thread once anything has been metered at all.
+
+ Owning it is also what makes it abandonable; see `_AbandonableWriter` for why
+ the stdlib pool is the one mechanism that cannot be used here.
"""
global _LEDGER_EXECUTOR
with _LEDGER_EXECUTOR_LOCK:
if _LEDGER_EXECUTOR is None:
- _LEDGER_EXECUTOR = ThreadPoolExecutor(max_workers=1, thread_name_prefix="model-hub-usage")
+ _LEDGER_EXECUTOR = _AbandonableWriter()
return _LEDGER_EXECUTOR
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index 3f9110562..ff7c40d1d 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -943,6 +943,79 @@ ending's first statement and the ending must be the only one there is, and the c
instant must be captured in `_resolved_response` and carried rather than re-read at the
write. Six mutations, six distinct failures.
+### Round 17 (head `27aae667e`)
+
+Three P2 findings, and **all three repeat a class already seen**. The circuit breaker is
+tripped, so the round opens with the diagnosis rather than an edit. Inventory across the
+five findings-bearing heads: class **K** — *identity keying done by whoever happened to
+need it* — is on its 4th head (R13, R14, R15, R17); class **B** — *a bound stated at the
+wrong layer* — is on its 3rd (R15, R16, R17).
+
+**Scope decision, recorded: continue, no owner escalation.** The architecture is not what
+is wrong. Ledger-owns-keying survives R17 — no caller keyed anything this round — and
+one-serialized-writer survives too. What was never stated as an *owned property* is
+narrower than either: **identity arity** and **worker abandonability**. Each finding has
+exactly one terminal rule, each is reversible and contract-preserving, and two of the
+three *delete* a concept rather than add one, which is what makes the smallest complete
+action clear enough to take without asking.
+
+**F1: a model's label was keyed by its ID alone (class K, 4th head).** A common model ID
+exists precisely so several Sources can offer it, so a flat `{model_id: label}` answered
+for whichever Source asked — a model removed from Source A kept its label there for as
+long as Source B still listed it, and a retained row read as though its own identity were
+still configured. The previous three rounds moved *who* does the keying; none of them
+asked what a metered model's identity *is*. It is the pair. Two flat 1-arity maps cannot
+express a 2-arity identity, so no amount of relocating the lookup could have closed this,
+and the class was never going to end while the argument shape still admitted the mistake.
+`summary()` now takes `Sequence[SourceIdentity]` — the shape config actually holds, Sources
+each carrying their listed models — and derives both key levels itself. Arity lives in the
+type, so there is no keying convention left for a caller to hold. Model labels are derived
+on the way through (a model's label is its own identity), so the caller no longer passes
+`{model.id: model.id}` at all: one concept deleted, not relocated.
+
+**F2: `datetime` conversion was assumed total (class B, 3rd head).** A value near either
+end of the representable range, offset far enough, leaves that range on the way to another
+zone and raises `OverflowError` — an `ArithmeticError`, so it passes straight through a
+handler written for bad data, out of the flush task, and stops metering for the rest of the
+process while the row that caused it stays on disk to do it again. The tempting fix is a
+year range, and the project rule rules it out: a bound with a free parameter is not the
+terminal rule, it is the next thing to probe. **The conversion is the bound.** `_carried`
+performs both conversions this module makes — UTC for the spelling it publishes, local for
+the day it buckets — and returns nothing when either refuses, so what escapes it is safe
+at both by construction. The two doors differ in what they do with a refusal, and correctly
+so: persisted text degrades to absent, while a caller's moment cannot be lost, so it dates
+the row by the only instant the module can measure. The `(OSError, ValueError)` handlers
+were deliberately *not* widened — that would be a second answer to the same question and
+would hide the next real bug; the door makes the class unreachable instead.
+
+**F3: the write was bounded but not abandonable (class B, same round).** Every wait this
+module makes a caller do is bounded, which is what keeps a served turn off a disk. Shutdown
+is where a bound stops being the question: the write is still running after the last
+bounded wait has already returned and told its caller the row was unfinished, so all that
+is left is whether the process may walk away. `ThreadPoolExecutor` will not — its workers
+are non-daemon and it registers an `atexit` hook that joins them — so a worker wedged in
+`fsync` holds interpreter shutdown open forever, and a stop or restart waits on optional
+metering. `_AbandonableWriter` is one daemon thread over a `queue.SimpleQueue`, keeping the
+`Executor` interface so `run_in_executor` still bridges it to the loop. Same single idle
+thread, same call sites; the atexit join that *was* the whole defect is gone.
+
+**Evidence.** `MH-USAGE-013` states F1 as the biconditional over every pair the ledger
+holds — a label is published exactly when config lists that model under that Source — with
+both directions asserted, because a join that labels everything and one that labels nothing
+each satisfy half of it, and over both key populations so the scoping survives the fold.
+`MH-USAGE-014` seeds the two spellings that break the naive conversion regardless of the
+machine's zone and asserts first that they still raise `ArithmeticError`, which is the
+finding itself; then both directions of the door in one test. `MH-USAGE-015` runs a real
+subprocess, because `atexit` hooks and non-daemon joins run after the interpreter has
+finished with `__main__` and nothing in-process distinguishes a worker that will be
+abandoned from one that will be waited on forever. Two structure guards carry what behavior
+cannot: `usage_summary` may construct no mapping at all (a map built there is a join key
+whose arity the caller chose), and no module in the package may build a pool or start a
+non-daemon thread — scanned package-wide rather than asserted about the one class that had
+the defect, since the next worker inherits the rule. Six mutations, six distinct failures;
+the pool mutation fails by hanging the child for the full timeout, which is the defect
+verbatim.
+
## Todo
- [x] Usage taxonomy and extraction in `stream_wire.py`
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 90c9e7be9..f0e819ecd 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -191,6 +191,24 @@ scenarios:
kind: persistence
layer: unit
test: tests/test_model_hub_config.py::test_a_live_chain_is_refused_the_duplicate_a_persisted_chain_is_repaired
+ - id: MH-USAGE-013
+ name: A model's label belongs to the Source it was metered under, not to its ID alone
+ status: covered
+ kind: persistence
+ layer: unit
+ test: tests/test_model_hub_usage.py::test_a_model_label_is_scoped_to_the_source_it_was_metered_under
+ - id: MH-USAGE-014
+ name: An instant no conversion can carry degrades instead of stopping metering
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_usage.py::test_an_instant_no_conversion_can_carry_never_stops_metering
+ - id: MH-USAGE-015
+ name: A wedged ledger write cannot hold the process open at exit
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_usage.py::test_a_wedged_ledger_write_cannot_hold_the_process_open
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 80777f035..7884aebcd 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -916,7 +916,48 @@ def test_a_usage_row_is_labelled_without_its_caller_knowing_how_it_was_keyed() -
]
handoffs = [node for node in ast.walk(reader) if _call_name(node) == "summary"]
assert len(handoffs) == 1
- assert {keyword.arg for keyword in handoffs[0].keywords} >= {"source_labels", "model_labels"}
+ assert "identities" in {keyword.arg for keyword in handoffs[0].keywords}
+ # Review 4967250750 finding 1: a mapping built here is a join key whose arity the
+ # caller chose, and arity is what went wrong on the fourth head. A metered model's
+ # identity is the pair (source, model), so a flat ``{model.id: ...}`` answered for
+ # a model removed from one Source as long as another Source still listed it.
+ # Handing the nesting down as a typed record leaves no arity to get wrong.
+ assert not [node for node in ast.walk(reader) if isinstance(node, (ast.Dict, ast.DictComp))]
+
+
+def test_no_hub_worker_thread_can_be_waited_on_at_process_exit() -> None:
+ """Review 4967250750 finding 3: metering must be abandonable, not merely bounded.
+
+ Every wait the hub makes a caller do is bounded, which is what keeps a served turn
+ off a disk. Shutdown is where a bound stops being the question: the work is still
+ running after the last bounded wait returned, so what matters is whether the
+ runtime will walk away from it. `ThreadPoolExecutor` will not — it registers an
+ `atexit` hook that joins non-daemon workers — so a worker wedged in `fsync` holds
+ interpreter shutdown open forever.
+
+ Scanned over the package rather than asserted about the one class that had the
+ defect: a second worker started anywhere in the hub inherits the same rule, which
+ is the part nobody remembers when adding one. ``MH-USAGE-015`` proves the
+ behaviour; this keeps the next thread from having to rediscover it.
+ """
+
+ started = 0
+ for path in sorted((ROOT / "core/handlers/model_hub").rglob("*.py")):
+ for node in ast.walk(_tree(path)):
+ if not isinstance(node, ast.Call):
+ continue
+ name = _call_name(node)
+ assert name not in {
+ "ThreadPoolExecutor",
+ "ProcessPoolExecutor",
+ }, f"{path.name} builds a pool whose workers are joined at exit"
+ if name != "Thread":
+ continue
+ started += 1
+ daemon = [keyword for keyword in node.keywords if keyword.arg == "daemon"]
+ assert len(daemon) == 1, f"{path.name} starts a thread without saying whether it is a daemon"
+ assert daemon[0].value.value is True, f"{path.name} starts a thread the runtime will wait on"
+ assert started, "no hub worker thread found -- the scan has stopped covering anything"
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 417c61485..63578747d 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -17,6 +17,9 @@ import json
import logging
import os
import stat
+import subprocess
+import sys
+import textwrap
import threading
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
@@ -42,6 +45,7 @@ from core.handlers.model_hub.stream_wire import (
from core.handlers.model_hub.usage import (
USAGE_RETENTION_DAYS,
BoundedUsageLedger,
+ SourceIdentity,
UsageWriter,
local_usage_day,
)
@@ -1412,11 +1416,10 @@ def test_a_label_reaches_the_row_of_every_identity_the_ledger_can_key(tmp_path:
return ledger.summary(
days=30,
now=NOW,
- source_labels={identity: f"{naming} {identity}" for identity in sources},
- # A model's label is its own identity: a folded row publishes a head
- # plus a digest, so a tab drawing `model_id` would show a string
- # nobody typed.
- model_labels={identity: identity for identity in models},
+ identities=[
+ SourceIdentity(source_id=source_id, label=f"{naming} {source_id}", model_ids=models)
+ for source_id in sources
+ ],
)
for naming in ("named", "renamed"):
@@ -1443,12 +1446,135 @@ def test_a_label_no_config_still_holds_is_absent_rather_than_stale(tmp_path: Pat
ledger = _ledger(tmp_path)
ledger.record(source_id="src_gone0001", model_id="model-gone", usage=None, at=NOW)
- source = ledger.summary(days=30, now=NOW, source_labels={}, model_labels={})["sources"][0]
+ source = ledger.summary(days=30, now=NOW, identities=[])["sources"][0]
assert source["label"] is None
assert source["models"][0]["label"] is None
+def test_a_model_label_is_scoped_to_the_source_it_was_metered_under(tmp_path: Path) -> None:
+ """MH-USAGE-013, review 4967250750: a metered model's identity is the pair.
+
+ A common model ID exists precisely so several Sources can offer it, so a label
+ looked up by model ID alone answers for whichever Source happens to ask. A model
+ removed from one Source therefore kept its label there for as long as any other
+ Source still listed it, and a retained row read as though its own identity were
+ still configured.
+
+ Stated as the biconditional over every pair the ledger holds: a label is
+ published exactly when config lists that model under that Source. Both
+ directions are the test — a join that labels everything and one that labels
+ nothing each satisfy only half — and the models span both key populations, so
+ the scoping has to survive the fold as well as the verbatim case.
+ """
+
+ listing, withholding = "src_lists001", "src_hides001"
+ models = _keying_populations("model-")
+ ledger = _ledger(tmp_path)
+ for source_id in (listing, withholding):
+ for model_id in models:
+ ledger.record(source_id=source_id, model_id=model_id, usage=None, at=NOW)
+
+ summary = ledger.summary(
+ days=30,
+ now=NOW,
+ identities=[
+ SourceIdentity(source_id=listing, label="lists", model_ids=models),
+ # Configured, so its own label is present: what config no longer holds is
+ # only this Source's listing of these models.
+ SourceIdentity(source_id=withholding, label="hides", model_ids=()),
+ ],
+ )
+
+ assert {source["source_id"] for source in summary["sources"]} == {
+ usage_ledger_key(listing),
+ usage_ledger_key(withholding),
+ }
+ assert all(source["label"] is not None for source in summary["sources"])
+ assert {
+ (source["source_id"], model["model_id"]): model["label"]
+ for source in summary["sources"]
+ for model in source["models"]
+ } == {
+ (usage_ledger_key(source_id), usage_ledger_key(model_id)): (
+ model_id if source_id == listing else None
+ )
+ for source_id in (listing, withholding)
+ for model_id in models
+ }
+
+
+def test_an_instant_no_conversion_can_carry_never_stops_metering(tmp_path: Path) -> None:
+ """MH-USAGE-014, review 4967250750: the conversion is the bound, not a year range.
+
+ `datetime` conversion is not total. A value near either end of the representable
+ range, offset far enough, leaves that range on the way to another zone and raises
+ `OverflowError` — an `ArithmeticError`, so it passes straight through a handler
+ written for bad data and out of the flush task, stopping metering for the rest of
+ the process while the row that caused it stays on disk.
+
+ Bounding the accepted years would leave a free parameter for the next value to
+ probe, so the conversion itself is the bound: what this module carries is what its
+ own conversions return. Persisted text degrades to absent; a caller's moment
+ cannot be lost, so it dates the row by the only instant the module can measure.
+ """
+
+ uncarriable = ("0001-01-01T00:00:00+14:00", "9999-12-31T23:59:59.999999-14:00")
+ # Seeds are only seeds while they still break the naive conversion, and the
+ # exception is the finding: `ArithmeticError` is not what a bad-data handler
+ # catches, so this raises out of every caller that only guarded `ValueError`.
+ for spelling in uncarriable:
+ with pytest.raises(ArithmeticError):
+ datetime.fromisoformat(spelling).astimezone(timezone.utc)
+
+ 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": f"src_carry{index:03d}",
+ "model_id": "model-carry",
+ "requests": 1,
+ "token_reports": 1,
+ "input_tokens": 5,
+ "cached_input_tokens": 0,
+ "output_tokens": 0,
+ "last_metered_at": spelling,
+ }
+ for index, spelling in enumerate(uncarriable)
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ summary = ledger.summary(days=30, now=NOW)
+
+ assert summary["totals"]["input_tokens"] == 5 * len(uncarriable)
+ assert [source["last_metered_at"] for source in summary["sources"]] == [None] * len(uncarriable)
+
+ # The other direction of the same door: a caller reports a call an upstream
+ # already billed, so an uncarriable moment dates the row by the instant this
+ # module measures rather than dropping the usage.
+ live = BoundedUsageLedger(tmp_path / "live" / "usage.json")
+ for hours in (14, -14):
+ edge = datetime.min if hours > 0 else datetime.max
+ live.record(
+ source_id="src_carry999",
+ model_id="model-carry",
+ usage=None,
+ at=edge.replace(tzinfo=timezone(timedelta(hours=hours))),
+ )
+
+ rows = live.window(days=2, now=datetime.now(timezone.utc))
+ assert len(rows) == 1
+ assert rows[0]["requests"] == len((14, -14))
+ stamped = rows[0]["last_metered_at"]
+ assert stamped is not None
+ assert rows[0]["day"] == local_usage_day(datetime.fromisoformat(stamped)).isoformat()
+
+
# --- Ownership: one queue, bounded by identity, loud when it loses a batch -----
@@ -1569,3 +1695,51 @@ def test_a_ledger_that_cannot_be_written_is_reported_once_per_outage(
assert ledger.summary(days=1, now=NOW)["totals"]["requests"] == 1
asyncio.run(exercise())
+
+
+def test_a_wedged_ledger_write_cannot_hold_the_process_open(tmp_path: Path) -> None:
+ """MH-USAGE-015, review 4967250750: metering must be abandonable, not just bounded.
+
+ Every wait this module makes a caller do is bounded, which is what keeps a served
+ turn from depending on a disk. Shutdown is the case where a bound is not enough:
+ the write is still running when the last bounded wait has already returned, so the
+ only question left is whether the process may walk away from it. Metering is
+ optional, so it must — a stop or a restart that waits on an unresponsive disk is
+ the hub failing at something it never promised.
+
+ Run as a real process because that is where the property lives. `atexit` hooks and
+ non-daemon thread joins run after the interpreter has finished with `__main__`, so
+ nothing observable in-process distinguishes a worker the runtime will abandon from
+ one it will wait on forever.
+ """
+
+ child = textwrap.dedent(
+ """
+ import threading
+ from core.handlers.model_hub.usage import _ledger_executor
+
+ wedged = threading.Event()
+ started = threading.Event()
+
+ def never_returns():
+ started.set()
+ wedged.wait()
+
+ _ledger_executor().submit(never_returns)
+ assert started.wait(10), "the ledger write never started"
+ print("wedged", flush=True)
+ """
+ )
+
+ result = subprocess.run(
+ [sys.executable, "-c", child],
+ cwd=Path(__file__).resolve().parents[1],
+ capture_output=True,
+ text=True,
+ # Generous next to the ~0s a walk-away costs, and finite because a hang is
+ # the defect: `TimeoutExpired` here is the test's failure signal.
+ timeout=60,
+ )
+
+ assert result.stdout.split() == ["wedged"], result.stderr
+ assert result.returncode == 0, result.stderr