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): meter the call the vendor billed, not the bookkeeping that followed

cyh27aae667e209
diff --git a/config/v2_config.py b/config/v2_config.py
index c2f3a8879..f4d3dbe14 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -2552,6 +2552,8 @@ def _collapse_settled_duplicates(
identity: Callable[[_SettledItem], object],
as_written: list,
message: str,
+ *,
+ repairing: bool,
) -> list[_SettledItem]:
"""Keep a collection of model identifiers unique after spelling is settled.
@@ -2563,16 +2565,32 @@ def _collapse_settled_duplicates(
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.
+ Duplicates **as written** are a malformed payload either way and raise.
+ Duplicates that appear only once spelling is settled depend on where the
+ payload came from, which is what `repairing` names:
+
+ - Repairing a payload already on disk, 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.
+ - Admitting a payload from a caller, the same pair is a request to name one
+ model twice, and silently keeping one half answers with a collection the
+ caller did not send. It raises, so the caller learns which spelling survived
+ by being told rather than by reading the response.
+
+ Required, and not defaulted, because the answer is a property of the caller
+ rather than of the collection: a parser cannot infer whether it is repairing
+ history or admitting a request, and a default would let the next call site
+ inherit whichever guess this one made.
"""
if len(set(as_written)) != len(as_written):
raise ValueError(message)
+ if not repairing:
+ settled_ids = [identity(item) for item in parsed]
+ if len(set(settled_ids)) != len(settled_ids):
+ raise ValueError(message)
+ return list(parsed)
collapsed: list[_SettledItem] = []
seen: set[object] = set()
for item in parsed:
@@ -2803,7 +2821,7 @@ class ModelHubSourceConfig:
masked_credential: Optional[str] = None
@classmethod
- def from_payload(cls, payload: dict) -> "ModelHubSourceConfig":
+ def from_payload(cls, payload: dict, *, repairing: bool = False) -> "ModelHubSourceConfig":
if not isinstance(payload, dict):
raise ValueError("Config 'model_hub.sources' entries must be objects")
allowed_fields = {
@@ -2864,6 +2882,7 @@ class ModelHubSourceConfig:
lambda model: model.id,
model_ids,
"Config 'model_hub.sources.models' contains duplicate ids",
+ repairing=repairing,
)
usage_payload = payload.get("usage")
base_url = payload.get("base_url")
@@ -2986,7 +3005,7 @@ class ModelHubRouteConfig:
hops: tuple[ModelHubRouteHopConfig, ...] = ()
@classmethod
- def from_payload(cls, payload: object) -> "ModelHubRouteConfig":
+ def from_payload(cls, payload: object, *, repairing: bool = False) -> "ModelHubRouteConfig":
if not isinstance(payload, dict) or set(payload) != {"hops"}:
raise ValueError("Config 'model_hub.agents.routes' entries must contain hops")
hops = payload.get("hops")
@@ -2999,6 +3018,7 @@ class ModelHubRouteConfig:
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",
+ repairing=repairing,
)
)
)
@@ -3078,7 +3098,13 @@ class ModelHubAgentSupplyConfig:
)
@classmethod
- def from_payload(cls, payload: dict, *, expected_backend: Optional[str] = None) -> "ModelHubAgentSupplyConfig":
+ def from_payload(
+ cls,
+ payload: dict,
+ *,
+ expected_backend: Optional[str] = None,
+ repairing: bool = False,
+ ) -> "ModelHubAgentSupplyConfig":
if not isinstance(payload, dict):
raise ValueError("Config 'model_hub.agents' entries must be objects")
if set(payload) - {"backend", "mode", "menu_kind", "sources", "routes", "menu"}:
@@ -3108,7 +3134,7 @@ class ModelHubAgentSupplyConfig:
if backend != "opencode" and menu_payload is not None:
raise ValueError("Config 'model_hub.agents.menu' is only valid for opencode")
routes = {
- model_id: ModelHubRouteConfig.from_payload(route)
+ model_id: ModelHubRouteConfig.from_payload(route, repairing=repairing)
for model_id, route in routes_payload.items()
}
menu = ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None
@@ -3188,7 +3214,7 @@ class ModelHubConfig:
return list(self.agents[backend].sources.order)
@classmethod
- def from_payload(cls, payload: dict) -> "ModelHubConfig":
+ def from_payload(cls, payload: dict, *, repairing: bool = False) -> "ModelHubConfig":
if not isinstance(payload, dict):
raise ValueError("Config 'model_hub' must be an object")
if set(payload) - {"sources", "agents"}:
@@ -3201,7 +3227,10 @@ class ModelHubConfig:
raise ValueError("Config 'model_hub.agents' must be an object")
if set(agents_payload) - set(MODEL_HUB_BACKENDS):
raise ValueError("Config 'model_hub.agents' contains unknown backends")
- sources = [ModelHubSourceConfig.from_payload(source) for source in sources_payload]
+ sources = [
+ ModelHubSourceConfig.from_payload(source, repairing=repairing)
+ for source in sources_payload
+ ]
source_ids = [source.id for source in sources]
if len(set(source_ids)) != len(source_ids):
raise ValueError("Config 'model_hub.sources' contains duplicate ids")
@@ -3236,6 +3265,7 @@ class ModelHubConfig:
agents[backend] = ModelHubAgentSupplyConfig.from_payload(
raw_agent,
expected_backend=backend,
+ repairing=repairing,
)
expected_menu_ids = (
model_hub_fixed_menu_ids(backend)
@@ -3819,7 +3849,15 @@ class V2Config:
# the user explicitly opts in after the release capability is enabled.
model_hub = ModelHubConfig()
else:
- model_hub = ModelHubConfig.from_payload(model_hub_payload)
+ # The one repairing door, because this is the one caller parsing a
+ # document a previous release wrote. Every other entry into these
+ # constructors is either a request from a client — which must be told
+ # it named a model twice rather than answered with half of what it
+ # sent — or a round trip of objects this process already settled. The
+ # save paths reach here too, but never with this subtree: the config
+ # API drops ``model_hub`` from what the client sends, so the payload
+ # under this key is always what was last read off disk.
+ model_hub = ModelHubConfig.from_payload(model_hub_payload, repairing=True)
ui_payload = payload.get("ui") or {}
if not isinstance(ui_payload, dict):
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index a00038837..e36ffeda9 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -4957,13 +4957,14 @@ class ModelHubService:
Which is also why the write is the writer's and not this call's: a resolve
cancelled downstream while its row sat queued would otherwise discard usage
- the vendor had already billed. Shielded rather than dropped so the ordinary
- path still leaves the row on disk before the caller sees its outcome.
+ the vendor had already billed. The writer's own bounded wait keeps the
+ ordinary path leaving the row on disk before the caller sees its outcome,
+ without putting an unresponsive disk in front of the next failover hop.
"""
if outcome.usage is None:
return
- await asyncio.shield(
+ await self.usage_writer.wait_recorded(
self.usage_writer.record(
source_id=source_id,
model_id=model_id,
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 63e2f9b5c..d18848ec9 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -105,6 +105,12 @@ class _TurnExecution:
# wire tracker to read them from.
buffered_usage: ProtocolUsageReport | None = None
buffered_outcome: StreamTerminalOutcome | None = None
+ # When the upstream body ended, published here for the same reason the two
+ # facts above are: it is the instant the call belongs to, and everything after
+ # it is bookkeeping whose duration is not the call's. A settlement that hangs
+ # for a minute, or across local midnight, would otherwise move the row to a
+ # day the vendor never billed.
+ completed_at: datetime | None = None
# The writer-owned task that persists this turn's row, and by its existence
# the record that this turn has already been metered. A flag would only say
# the write was started by something whose own death could still take it.
@@ -186,6 +192,21 @@ class _TurnExecution:
return self.buffered_outcome == "served"
return self.handle is not None
+ @property
+ def owes_metering(self) -> bool:
+ """Whether a row for this turn is still owed to the ledger.
+
+ Asked by the recorder, and by the boundary deciding whether an ending has
+ anything left to do. Two readers, one answer: a boundary that asked
+ "settled?" instead skipped the ending for a turn that was settled by force
+ after its upstream call had already reported tokens, and the vendor billed
+ that call either way.
+ """
+
+ if self.usage_write is not None or self.resolved is None:
+ return False
+ return self.reached_model or self.reported_usage is not None
+
@dataclass(frozen=True)
class _RenderedTurnOutcome:
@@ -423,17 +444,11 @@ class ModelHubTurnGateway:
)
raise error
if error is not None:
- if execution.handle is not None and not execution.settlement_recorded:
- _outcome, settlement = await self._settle_turn_handle(
- execution,
- terminalizer,
- termination_origin="upstream_terminal",
- )
- self._commit_and_render_handle_settlement(
- execution,
- terminalizer,
- settlement,
- )
+ await self._settle_boundary_termination(
+ execution,
+ terminalizer,
+ termination_origin="upstream_terminal",
+ )
raise error
assert response is not None
return response
@@ -503,7 +518,16 @@ class ModelHubTurnGateway:
terminalizer,
timeout_settlement,
)
- if not execution.settlement_recorded:
+ # Settle if unsettled, meter if unmetered — two debts, either one
+ # worth the ending. Asking only about settlement dropped the row for
+ # a call the upstream had already answered, because abandoning the
+ # request above writes an engine-down terminal and that made the turn
+ # settled. Asking about neither would be simpler still, but the
+ # deadline is spent by the time we get here in exactly the case that
+ # matters, and a task with no debt to discharge could not be drained
+ # before it was abandoned — a resource leak recorded against a turn
+ # that had nothing left to do.
+ if not execution.settlement_recorded or execution.owes_metering:
settlement_task = asyncio.create_task(
self._settle_boundary_termination(
execution,
@@ -686,6 +710,7 @@ class ModelHubTurnGateway:
payload = bytearray()
async for chunk in handle.stream:
payload.extend(chunk)
+ execution.completed_at = self._now()
# Published before settling, not after: settling can be cancelled by a
# downstream disconnect, and facts only this frame's local knew about
# would leave the boundary with nothing to meter.
@@ -696,19 +721,14 @@ class ModelHubTurnGateway:
)
execution.buffered_usage = observation.usage
execution.buffered_outcome = observation.outcome
- outcome, settlement = await self._settle_turn_handle(
+ outcome, settlement, rendered = await self._settle_metered_turn(
execution,
terminalizer,
termination_origin="upstream_terminal",
)
- rendered = self._commit_and_render_handle_settlement(
- execution,
- terminalizer,
- settlement,
- )
assert outcome is not None
+ assert settlement is not None
assert settlement.decision is not None
- await self._record_usage(execution)
if settlement.decision.action != "return":
return self._outcome_response(
outcome,
@@ -741,17 +761,12 @@ class ModelHubTurnGateway:
if wire_state.model_output_started and not output_started_before:
terminalizer.mark_stream_started()
await self._downstream_io(response.write(chunk))
- _outcome, settlement = await self._settle_turn_handle(
+ execution.completed_at = self._now()
+ _outcome, _settlement, rendered = await self._settle_metered_turn(
execution,
terminalizer,
termination_origin="upstream_terminal",
)
- rendered = self._commit_and_render_handle_settlement(
- execution,
- terminalizer,
- settlement,
- )
- await self._record_usage(execution)
await self._write_stream_terminal_copy(
response,
protocol,
@@ -783,6 +798,12 @@ class ModelHubTurnGateway:
first ending to describe it wins and every later one is a no-op. One call
is one request, whatever killed it.
+ The no-op is `execution.owes_metering` rather than a condition spelled
+ here, because an ending that has to decide whether to run at all asks the
+ same question. Answering it in two places is how the abandonment path came
+ to skip a billed call: it asked whether the turn was *settled*, which a
+ forced terminal had already made true.
+
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
@@ -795,31 +816,34 @@ class ModelHubTurnGateway:
change the turn the caller sees.
Which also means the turn cannot own the write. `UsageWriter` holds it, and
- the only await here is shielded, so an ending is a *when* in one more
- sense: it decides when a call is metered and never whether the metering
- survives. Nothing suspends between reading the facts and handing the write
- over, so a cancellation lands either before this turn was ever going to be
- metered or after the write is already someone else's to finish.
-
- Shielded rather than detached because the ordinary path should still leave
- the row on disk before the turn ends — a caller reading the tab right after
- its own call sees it. Cancellation is the one ending that ordering cannot
- survive, and it is the ledger's guarantee that gives way, not the write.
+ holds the waiting for it too, so an ending is a *when* in one more sense: it
+ decides when a call is metered and never whether the metering survives, nor
+ how long the turn waits on a disk. Nothing suspends between reading the
+ facts and handing the write over, so a cancellation lands either before this
+ turn was ever going to be metered or after the write is already someone
+ else's to finish.
+
+ Every ending calls this before it settles, and the completion instant is
+ read from the turn rather than here. Both say the same thing: a metered call
+ is the upstream call, and settlement, history, and rendering are bookkeeping
+ that happens to follow it. Reading the clock here dated the row by when the
+ bookkeeping got around to it — across local midnight, the wrong day — and
+ settling first meant an ending that raised on the way through never reached
+ this at all, for a call the vendor had already billed.
"""
- resolved = execution.resolved
- if execution.usage_write is not None or resolved is None:
+ if not execution.owes_metering:
return
+ resolved = execution.resolved
+ assert resolved is not None
usage = execution.reported_usage
- if not execution.reached_model and usage is None:
- return
execution.usage_write = self._usage_writer.record(
source_id=resolved.source_id,
model_id=resolved.model_id,
usage=usage,
- at=self._now(),
+ at=execution.completed_at or self._now(),
)
- await asyncio.shield(execution.usage_write)
+ await self._usage_writer.wait_recorded(execution.usage_write)
async def _write_stream_terminal_copy(
self,
@@ -854,30 +878,72 @@ class ModelHubTurnGateway:
except (ConnectionResetError, BrokenPipeError) as exc:
raise _DownstreamDisconnected(str(exc)) from exc
- async def _settle_boundary_termination(
+ async def _settle_metered_turn(
self,
execution: _TurnExecution,
terminalizer: GatewayTurnTerminalizer,
*,
termination_origin: HandleTerminationOrigin,
- ) -> None:
- # Ahead of the settlement guard: a downstream disconnect can arrive after
- # 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.
+ ) -> tuple[RawCallOutcome | None, HandleSettlement | None, _RenderedTurnOutcome | None]:
+ """End one turn: meter the call, then settle it, then commit what it was.
+
+ One owner for the order, because the order is the whole property. Metering
+ used to be each ending's own step, and every ending placed it after its
+ bookkeeping — where a settlement that raised skipped it entirely, for a call
+ the vendor had already billed. It cannot be placed wrongly here: it is this
+ function's first statement, and there is nowhere else to place it.
+
+ Bookkeeping after metering is also why the recorder needs no ending to be
+ careful. A settlement is a fact about a handle and the settlement owner
+ rejects one without it, so a turn that failed before adopting a body has
+ nothing to settle — and, having reached no model, nothing to meter either.
+ The guard for that sits behind the recorder rather than in front of it,
+ which is what makes "settled here" imply "metered here" for every ending
+ there is and every ending there will be.
+
+ Answers with all three facts so an ending can render its own response
+ without settling a second time. An ending that arrives after the turn was
+ already committed gets the committed rendering and no settlement, which is
+ the same thing the projection choke would have handed it.
+ """
+
await self._record_usage(execution)
if execution.settlement_recorded:
- return
- _outcome, settlement = await self._settle_turn_handle(
+ return None, None, execution.rendered_turn_outcome
+ if termination_origin == "upstream_terminal" and execution.handle is None:
+ return None, None, execution.rendered_turn_outcome
+ outcome, settlement = await self._settle_turn_handle(
execution,
terminalizer,
termination_origin=termination_origin,
)
- self._commit_and_render_handle_settlement(
+ rendered = self._commit_and_render_handle_settlement(
execution,
terminalizer,
settlement,
)
+ return outcome, settlement, rendered
+
+ async def _settle_boundary_termination(
+ self,
+ execution: _TurnExecution,
+ terminalizer: GatewayTurnTerminalizer,
+ *,
+ termination_origin: HandleTerminationOrigin,
+ ) -> None:
+ """End a turn the boundary is ending, rather than the request path.
+
+ A downstream disconnect can arrive after the upstream already answered, so
+ the turn was billed even though the request path never reached its own
+ ending. Which is the whole of what a boundary ending adds over that ending:
+ it is a *when*, and the turn already holds every *what*.
+ """
+
+ await self._settle_metered_turn(
+ execution,
+ terminalizer,
+ termination_origin=termination_origin,
+ )
if execution.settlement_origin == "downstream_cancel":
terminalizer.mark_downstream_canceled()
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index 00b817b08..7a310b047 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -564,6 +564,10 @@ class BoundedUsageLedger:
_LEDGER_EXECUTOR_LOCK: Final = threading.Lock()
_LEDGER_EXECUTOR: Optional[ThreadPoolExecutor] = 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:
@@ -677,8 +681,9 @@ class UsageWriter:
on a disk that is already failing.
"""
- def __init__(self, ledger: BoundedUsageLedger):
+ def __init__(self, ledger: BoundedUsageLedger, *, durability_wait: float = _DURABILITY_WAIT_SECONDS):
self.ledger = ledger
+ self._durability_wait = durability_wait
self._pending: dict[tuple[str, str, str, bool], _QueuedRow] = {}
# The batch on its way to disk, kept visible so a drain that times out
# can count it: in the executor is not the same as persisted.
@@ -706,10 +711,10 @@ class UsageWriter:
than re-read, because the flush that persists this can start well after
it and a queued write is still a report about the moment it finished.
- A caller that wants the row on disk before it returns awaits the result
- through `asyncio.shield`; one that does not can simply drop it. Callers
- whose calls fold together share one future, which is the same promise each
- would have had alone: it completes when their row reaches the disk.
+ A caller that wants the row on disk before it returns hands the result to
+ `wait_recorded`; one that does not can simply drop it. Callers whose calls
+ fold together share one future, which is the same promise each would have
+ had alone: it completes when their row reaches the disk.
"""
call = UsageCall(source_id=source_id, model_id=model_id, usage=usage, at=at)
@@ -723,6 +728,32 @@ class UsageWriter:
self._flush = asyncio.create_task(self._flush_pending())
return queued.done
+ async def wait_recorded(self, write: "asyncio.Future[None]") -> bool:
+ """Wait out one queued write, bounded, and answer whether it landed.
+
+ Two properties every metering caller wants and none of them owns. The
+ shield is why a caller cancelled here loses its ordering and not the row.
+ The bound is why a ledger that has stopped answering cannot hold a served
+ turn open behind it: the wait exists so a caller reading the usage tab
+ right after its own call sees that call, which is an ordering convenience,
+ not a durability requirement the turn is allowed to fail for.
+
+ Both used to be spelled at each metering call site, which made the bound
+ the one property a new call site could omit by writing the obvious thing —
+ and it did: awaiting a write with no deadline puts a stuck disk on the
+ turn's critical path. Here there is nothing to omit.
+
+ A timed-out write is not lost or cancelled. It stays this writer's, keeps
+ its place in the queue, and keeps counting in `unpersisted` until the disk
+ answers; only the caller's wait for it ends.
+ """
+
+ try:
+ await asyncio.wait_for(asyncio.shield(write), self._durability_wait)
+ except asyncio.TimeoutError:
+ return False
+ return True
+
@property
def unpersisted(self) -> int:
"""How many metered calls this writer still owes the ledger.
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index e80a32abc..3f9110562 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -883,6 +883,66 @@ next async-only read is carried without an edit. With that fixed, the driver val
real summary against `usage-summary.schema.json`, which is what makes `label` a contract
rather than a field the ledger happens to emit.
+### Round 16 (head `a85a88569`)
+
+Four P2 findings, and three of them are one class: **metering was positioned relative to
+our bookkeeping instead of relative to the upstream call.** That is the class name, and
+naming it is what makes the remaining members predictable — every ending that settles a
+turn is a member, and so is every property that follows from *when* the row is taken.
+The fourth finding is unrelated and closed on its own terms. Per the property-ownership
+rule the fix moves ownership rather than patching the sites.
+
+**F1: a settlement that raised took the billed row with it.** Metering was each ending's
+own step, written after that ending's bookkeeping, so an exception on the way through
+settlement skipped the recorder — the vendor had already billed the call, and our ledger
+never heard about it. The sites were the members; the owner was missing. `_settle_metered_turn`
+is now the single ending owner for every shape a turn can end in, and `await self._record_usage(execution)`
+is its first executable statement, ahead of every branch that can fail. Doing it exactly
+once needed a second piece: the boundary that catches the raise re-enters the same ending,
+so "is a row still owed" had to stop being each caller's inference. `_TurnExecution.owes_metering`
+is now that one answer, read by the recorder and by the abandonment boundary alike.
+
+**F2: the row was dated by when bookkeeping got around to it.** The recorder read the
+clock itself, so a call that ended at 23:59:58 and settled at 00:00:01 landed in the next
+local day — the wrong day's usage for a call the vendor billed on the previous one. The
+completion instant is now captured where the upstream body ends, which is the one place
+that has a body to end, and carried into `record(at=...)`; the writer keeps
+`metered_at = min(call.at, persisted_at)` so a row is dated by its call and clamped
+forward only by the persist instant. What is worth recording is *why this one is not a
+behavior test*: with the recorder as the first statement of the ending, nothing suspends
+between the capture and the queue, so no clock can advance in between and no test can make
+one. The unreachability is the fix, so the guard asserts where the instant comes from
+rather than driving a gap that no longer exists.
+
+**F3: the durability wait was spelled at each call site.** Metering waits out its own
+write so a client that opens the usage tab right after its call already sees that call.
+Two call sites each wrote their own version of that wait, and the gateway's was
+unbounded — hold the single thread ledger writes run on and a served response waits
+behind a disk that has stopped answering. `UsageWriter.wait_recorded` now owns both
+halves once: shielded, so a timed-out write is queued rather than cancelled, and bounded,
+so the convenience cannot become the turn's critical path. `service._meter_call` was
+migrated onto it instead of keeping its own copy.
+
+**F4: canonical duplicates were repaired on live writes instead of refused.** Collapsing
+a duplicate hop is right for a persisted tree we must be able to load, and wrong for a
+request we can still answer: the caller that named one model in two spellings gets half
+of what it sent, silently. The two doors are now distinct — `from_payload(..., repairing=True)`
+collapses, the default raises — and there is exactly one repairing door,
+`V2Config.from_payload`. `create_source` already refused, because it round-trips through
+`to_payload()`; only the route-hop path reproduced. Client config saves cannot reach the
+repairing door either way, since `vibe/api.py` strips `model_hub` from them.
+
+**Evidence.** `MH-USAGE-010` states F1's property in both shapes — buffered and streamed
+reach the ending from different frames — with `requests == 1` rather than `>= 1`, because
+exactly-once is the half that the re-entering boundary threatens. `MH-USAGE-011` states
+F3's property as its two halves at once: the turn is served while the ledger hangs, and
+the row is still queued rather than dropped. `MH-USAGE-012` states F4's property as one
+payload through both doors with opposite answers, which is why it is one test rather than
+two. Two structure guards carry what behavior cannot reach: the recorder must be the
+ending's first statement and the ending must be the only one there is, and the completion
+instant must be captured in `_resolved_response` and carried rather than re-read at the
+write. Six mutations, six distinct failures.
+
## 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 f567bb7ae..90c9e7be9 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -173,6 +173,24 @@ scenarios:
kind: concurrency
layer: unit
test: tests/test_model_hub_usage.py::test_the_write_queue_is_bounded_by_identities_not_by_arrival_rate
+ - id: MH-USAGE-010
+ name: A turn whose settlement raises still meters the call the vendor billed
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_l3.py::test_a_settlement_that_raises_still_meters_the_call_it_was_settling
+ - id: MH-USAGE-011
+ name: A ledger that stopped answering cannot hold the served turn open behind it
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_l3.py::test_a_ledger_that_stopped_answering_cannot_hold_the_served_turn_open
+ - id: MH-USAGE-012
+ name: A caller that names one model twice is refused rather than answered with half of what it sent
+ status: covered
+ 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-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
index a7c419253..a73cc9c82 100644
--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -192,8 +192,11 @@ def _assert_sources_validated_before_commit(
original_validator = ModelHubSourceConfig.from_payload.__func__
validated_source_ids: set[str] = set()
- def tracked_validator(cls, payload):
- source = original_validator(cls, payload)
+ # Pass-through on purpose: what this double observes is which sources were
+ # validated, so it must not pin the validator's signature. Spelling out today's
+ # arguments made a policy flag the owner grew into a migration conflict.
+ def tracked_validator(cls, *args, **kwargs):
+ source = original_validator(cls, *args, **kwargs)
validated_source_ids.add(source.id)
return source
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 18087135e..22da27772 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import ast
import copy
+import inspect
import json
import re
import stat
@@ -1815,6 +1816,42 @@ def test_every_normalized_identifier_collection_collapses_through_one_owner():
assert len(collapsing) == len(normalizing)
+def test_collapsing_a_settled_duplicate_is_a_repair_no_caller_gets_by_default():
+ # The other half of the collapse: *who* asked. Repairing a file a released
+ # build wrote has to keep loading, and admitting a request that names one
+ # model twice has to say so — the same pair, two answers, so the parser cannot
+ # infer it and the caller has to state it. This asserts the default rather
+ # than the two call sites, because the default is what a call site added later
+ # inherits without deciding: an ordinary `from_payload` collapses nothing.
+ for owner in (ModelHubSourceConfig, ModelHubRouteConfig, ModelHubAgentSupplyConfig, ModelHubConfig):
+ signature = inspect.signature(owner.from_payload)
+ assert signature.parameters["repairing"].default is False, owner.__name__
+
+ settled = inspect.signature(v2_config._collapse_settled_duplicates)
+ assert settled.parameters["repairing"].default is inspect.Parameter.empty
+ assert settled.parameters["repairing"].kind is inspect.Parameter.KEYWORD_ONLY
+
+
+def test_a_live_chain_is_refused_the_duplicate_a_persisted_chain_is_repaired():
+ """MH-USAGE-012: one payload, both doors, opposite answers.
+
+ Which is the property, and the reason it is one test. The chain names one
+ upstream model in two spellings, so it is one ledger row either way; what
+ differs is whether the caller gets to learn that before it becomes one.
+ """
+
+ hops = [
+ {"source_id": "src_same0001", "model_id": "model-a"},
+ {"source_id": "src_same0001", "model_id": " model-a "},
+ ]
+
+ with pytest.raises(ValueError, match="unique pairs"):
+ ModelHubRouteConfig.from_payload({"hops": copy.deepcopy(hops)})
+
+ repaired = ModelHubRouteConfig.from_payload({"hops": copy.deepcopy(hops)}, repairing=True)
+ assert [hop.model_id for hop in repaired.hops] == ["model-a"]
+
+
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)
@@ -2643,7 +2680,8 @@ def test_route_hops_allow_one_source_to_supply_distinct_models():
{"source_id": "src_same0001", "model_id": "model-a"},
{"source_id": "src_same0001", "model_id": " model-a "},
]
- }
+ },
+ repairing=True,
)
assert [(hop.source_id, hop.model_id) for hop in collapsed.hops] == [
("src_same0001", "model-a"),
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 4e3d78d15..f9cc3965b 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -72,7 +72,7 @@ from core.handlers.model_hub.turn_gateway import (
render_protocol_terminal_event,
)
from core.handlers.model_hub.stream_wire import ProtocolSSEState, ProtocolUsageReport
-from core.handlers.model_hub.usage import BoundedUsageLedger, _ledger_executor
+from core.handlers.model_hub.usage import BoundedUsageLedger, UsageWriter, _ledger_executor
from core.run_settlement import (
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLED_BY_STOPPED,
@@ -7184,3 +7184,131 @@ def test_a_usage_ledger_failure_cannot_change_the_served_turn(tmp_path: Path) ->
assert service.store.load().sources[0].state.status == "standby"
asyncio.run(exercise())
+
+
+def test_a_settlement_that_raises_still_meters_the_call_it_was_settling(
+ tmp_path: Path,
+) -> None:
+ """MH-USAGE-010: the vendor billed the call before our bookkeeping got a turn.
+
+ Metering used to be each ending's own step, placed after that ending's
+ bookkeeping, so a settlement that raised on the way through took the row with
+ it. Both shapes, because the two reach the ending from different frames and
+ each used to carry its own copy of the order — and `requests == 1` rather than
+ `>= 1`, because the boundary that catches the raise re-enters the same ending.
+ """
+
+ async def exercise(stream: bool) -> None:
+ state = tmp_path / ("stream" if stream else "buffer")
+ state.mkdir()
+ source = _source("src_meterraise1", "Broken settlement")
+ chunks = (
+ (
+ b'event: response.completed\ndata: {"type":"response.completed",'
+ b'"sequence_number":1,"response":{"usage":{"input_tokens":256,'
+ b'"output_tokens":12}}}\n\n',
+ )
+ if stream
+ else (b'{"usage":{"input_tokens":256,"output_tokens":12}}',)
+ )
+ service = _service(
+ state,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(
+ RawOutcomeKind.SUCCESS,
+ status=200,
+ source_id=source.id,
+ stream_started=stream,
+ ),
+ chunks,
+ )
+ ],
+ )
+
+ async def exploding_settlement(*args: object, **kwargs: object):
+ raise RuntimeError("settlement exploded")
+
+ service.settle_handle_outcome = exploding_settlement
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id=f"turn_meter_raise_{'stream' if stream else 'buffer'}",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=stream,
+ )
+
+ with patch(
+ "core.handlers.model_hub.turn_gateway.web.StreamResponse",
+ return_value=FakeStreamResponse(),
+ ):
+ with pytest.raises(RuntimeError, match="settlement exploded"):
+ await asyncio.wait_for(gateway._handle_request(request), timeout=5)
+ await gateway.close()
+
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1, stream
+ assert metered["token_reports"] == 1, stream
+ assert metered["input_tokens"] == 256, stream
+ assert metered["output_tokens"] == 12, stream
+
+ for stream in (False, True):
+ asyncio.run(exercise(stream))
+
+
+def test_a_ledger_that_stopped_answering_cannot_hold_the_served_turn_open(
+ tmp_path: Path,
+) -> None:
+ """MH-USAGE-011: waiting for the row is an ordering convenience, not a gate.
+
+ Metering waits out its own write so a client that opens the usage tab right
+ after its call already sees that call. Unbounded, the convenience becomes the
+ turn's critical path: hold the one thread ledger writes run on and the served
+ response waits behind a disk that has stopped answering. Bounded, the turn is
+ served and the row stays queued — timed out is not dropped, which is the other
+ half of the same wait.
+ """
+
+ async def exercise() -> None:
+ source = _source("src_meterhang01", "Unresponsive ledger")
+ body = json.dumps({"usage": {"input_tokens": 64, "output_tokens": 4}}).encode("utf-8")
+ service = _service(
+ tmp_path,
+ sources=[source],
+ live_handles=[
+ LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id),
+ (body,),
+ )
+ ],
+ )
+ service.usage_writer = UsageWriter(service.usage, durability_wait=0.05)
+ requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service)
+ request = _prepared_gateway_request(
+ gateway,
+ turn_id="turn_meter_hung_ledger",
+ requested_model=requested_model,
+ source_id=source.id,
+ stream=False,
+ )
+
+ with _occupied_ledger_writer():
+ result = await asyncio.wait_for(gateway._handle_request(request), timeout=1)
+ assert result.status == 200
+ assert result.body == body
+ # The scenario is only the scenario while the write is still queued,
+ # and a queued write is still the writer's to finish.
+ assert service.usage_writer.unpersisted == 1
+ assert _usage_of(service, source.id) == {}
+
+ assert await service.usage_writer.drain(timeout=5) == 0
+ metered = _usage_of(service, source.id)
+ assert metered["requests"] == 1
+ assert metered["input_tokens"] == 64
+ assert metered["output_tokens"] == 4
+
+ asyncio.run(exercise())
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 4b0924343..80777f035 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -405,7 +405,11 @@ def test_g2_outcome_reads_have_one_settlement_owner() -> None:
)
assert response_owner is not None
stream_at = response_owner.index("response = web.StreamResponse")
- settle_at = response_owner.index("await self._settle_turn_handle", stream_at)
+ # Settlement now reaches the handle through the one function that meters the
+ # turn first, so the t4 slot in this ordering is named by that owner. The
+ # ordering it constrains is unchanged: the response exists, then the turn is
+ # ended, then the terminal copy renders into it.
+ settle_at = response_owner.index("await self._settle_metered_turn", stream_at)
render_at = response_owner.index("await self._write_stream_terminal_copy", settle_at)
eof_at = response_owner.index("await self._downstream_io(response.write_eof())", render_at)
assert settle_at < render_at < eof_at
@@ -595,14 +599,129 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:
assert meter_calls[0] in set(ast.walk(invoke))
# Any of the gateway's endings may report the forwarded call, so exactly-once
# rests on the write it owns; a caller that pre-checks or clears that handle
- # would move the decision outside the owner.
+ # would move the decision outside the owner. An ending may still need to know
+ # whether a row is owed — the abandonment path decides whether to run at all —
+ # so that question is a property of the turn and the only other reader of the
+ # handle. Review 4970...: it used to ask whether the turn was *settled*, which
+ # a forced terminal had already made true for a call the vendor billed.
+ owes = _functions(gateway_tree)["owes_metering"]
+ readers = (recorder, owes)
handles = [
node
for node in ast.walk(gateway_tree)
if isinstance(node, ast.Attribute) and node.attr == "usage_write"
]
assert handles
- assert all(handle in set(ast.walk(recorder)) for handle in handles)
+ assert all(any(handle in set(ast.walk(reader)) for reader in readers) for handle in handles)
+ assert not [
+ node
+ for node in ast.walk(owes)
+ if isinstance(node, ast.Assign) or isinstance(node, ast.AugAssign)
+ ]
+
+
+def test_settling_a_turn_is_what_meters_it_for_every_ending_there_will_be() -> None:
+ # Review 4970...: metering was positioned relative to bookkeeping rather than to
+ # the upstream call, and each ending paid for it differently — one settled first
+ # and skipped the row when settlement raised, one never metered at all. Naming
+ # the class instead of its endings: there is one function that ends a metered
+ # turn, the recorder is its first statement, and no ending can settle without
+ # going through it. An ending added later inherits the order rather than
+ # restating it, because there is nowhere else to state it.
+ gateway_tree = _tree(TURN_GATEWAY)
+ functions = _functions(gateway_tree)
+ owner = functions["_settle_metered_turn"]
+ recorded = [node for node in ast.walk(gateway_tree) if _call_name(node) == "_record_usage"]
+ assert len(recorded) == 1
+ assert recorded[0] in set(ast.walk(owner))
+ # The first *executable* statement, and the statement itself rather than
+ # anything nested in one: metering under a condition is what every ending that
+ # got this wrong already did.
+ body = [node for node in owner.body if not (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant))]
+ assert isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Await)
+ assert body[0].value.value is recorded[0]
+ # And the settlement it wraps is reachable only through it, so "settled here"
+ # cannot come apart from "metered here" at a call site the next round adds.
+ settlements = [node for node in ast.walk(gateway_tree) if _call_name(node) == "_settle_turn_handle"]
+ assert len(settlements) == 1
+ assert settlements[0] in set(ast.walk(owner))
+ endings = [node for node in ast.walk(gateway_tree) if _call_name(node) == "_settle_metered_turn"]
+ assert len(endings) >= 2
+ assert all(
+ any(ending in set(ast.walk(functions[name])) for name in ("_settle_boundary_termination", "_resolved_response"))
+ for ending in endings
+ )
+
+
+def test_a_metered_row_is_dated_by_the_call_and_not_by_what_followed_it() -> None:
+ # Review 4970...: the other half of the same class. The recorder read the clock
+ # itself, so a row carried the moment bookkeeping got around to it rather than
+ # the moment the call ended — across local midnight, the wrong day's usage for a
+ # call the vendor billed on the previous one. Asserted here rather than driven,
+ # because the fix is what makes it unreachable: nothing suspends between the
+ # body ending and the row being queued, so no clock can move in between and no
+ # test can make one. What is left to protect is where the instant comes from.
+ gateway_tree = _tree(TURN_GATEWAY)
+ functions = _functions(gateway_tree)
+ # Captured where the upstream body ends, which is the one function that has a
+ # body to end. A capture anywhere else is a second answer to when the call
+ # finished, and the endings are exactly the places that would get it wrong.
+ captures = [
+ node
+ for node in ast.walk(gateway_tree)
+ if isinstance(node, ast.Assign)
+ and any(
+ isinstance(target, ast.Attribute) and target.attr == "completed_at"
+ for target in node.targets
+ )
+ ]
+ assert captures
+ assert all(capture in set(ast.walk(functions["_resolved_response"])) for capture in captures)
+ # And carried from there to the ledger rather than re-read at the write.
+ handoff = next(
+ node for node in ast.walk(functions["_record_usage"]) if _call_name(node) == "record"
+ )
+ dated = next(keyword for keyword in handoff.keywords if keyword.arg == "at")
+ assert any(
+ isinstance(node, ast.Attribute) and node.attr == "completed_at"
+ for node in ast.walk(dated.value)
+ )
+
+
+def test_how_long_a_turn_waits_on_the_ledger_is_the_writers_to_bound() -> None:
+ # Reviews 4964754924 / 4964894667 / 4970...: the wait was spelled at each
+ # metering call site, which made the bound the one property a new site could
+ # omit by writing the obvious `await` — and one did, putting an unresponsive
+ # disk on a turn's critical path and in front of the next failover hop. Both
+ # halves, shield and bound, now sit behind one name. The scan keys on the usage
+ # write specifically, so an unrelated shielded task is not mistaken for one.
+ waited = {"shield", "wait_for"}
+ usage_names = {"record", "usage_write", "wait_recorded", "usage_writer"}
+
+ def wraps_a_usage_write(tree: ast.AST) -> list[ast.Call]:
+ return [
+ node
+ for node in ast.walk(tree)
+ if _call_name(node) in waited
+ and any(
+ isinstance(inner, ast.Attribute) and inner.attr in usage_names
+ or isinstance(inner, ast.Name) and inner.id in usage_names
+ for argument in node.args
+ for inner in ast.walk(argument)
+ )
+ ]
+
+ usage_tree = _tree(USAGE)
+ waiter = _functions(usage_tree)["wait_recorded"]
+ assert {name for node in ast.walk(waiter) if (name := _call_name(node)) in waited} == waited
+ # Inside the writer the wait is spelled over its own parameter, so the name-keyed
+ # scan is aimed outward: at the modules that hold a `usage_write` and could wait
+ # on it themselves. Every one of them must go through the name above instead.
+ assert all(node in set(ast.walk(waiter)) for node in wraps_a_usage_write(usage_tree))
+ for module in sorted((ROOT / "core/handlers/model_hub").glob("*.py")):
+ if module == USAGE:
+ continue
+ assert not wraps_a_usage_write(_tree(module)), module.name
def test_every_body_fact_the_turn_reads_can_come_from_the_engine_that_read_it() -> None: