Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): observe wire bytes before buffering and give state writes one owner
cyh915c3a73b02c
diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.pyindex a6eaaf7ba..33cbed89d 100644--- a/core/handlers/model_hub/events.py+++ b/core/handlers/model_hub/events.py@@ -3,9 +3,7 @@from __future__ import annotationsimport json-import osimport re-import tempfileimport threadingimport uuidfrom dataclasses import dataclass@@ -15,6 +13,8 @@ from typing import Literal, Optional, TypeAlias, get_argsfrom vibe.i18n import t as i18n_t+from .state_file import write_state_document+EventAgent = Literal["claude", "codex", "opencode", "system"]EventKind = Literal["switch",@@ -288,15 +288,7 @@ class BoundedEventLog:]def _write(self, payload: list[dict]) -> None:- self.path.parent.mkdir(parents=True, exist_ok=True)- content = json.dumps(payload[-self.max_entries :], ensure_ascii=False, separators=(",", ":"))- with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=self.path.parent, delete=False) as tmp:- tmp.write(content)- tmp.flush()- os.fsync(tmp.fileno())- temp_name = tmp.name- os.chmod(temp_name, 0o600)- os.replace(temp_name, self.path)+ write_state_document(self.path, payload[-self.max_entries :])def append(self, event: ResolutionEvent) -> None:payload = event.to_payload()diff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.pyindex 4edd71e74..0abd85608 100644--- a/core/handlers/model_hub/oauth.py+++ b/core/handlers/model_hub/oauth.py@@ -4,9 +4,7 @@ from __future__ import annotationsimport asyncioimport json-import osimport re-import tempfileimport threadingfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -14,6 +12,7 @@ from pathlib import Pathfrom typing import Callable, Literal, Optional, Protocol, get_argsfrom .adapter import OAuthFlowState+from .state_file import write_state_documentOAuthChannel = Literal["native_cli", "hub"]OAuthNonceStatus = Literal["released", "in_flight", "committed"]@@ -266,9 +265,9 @@ class OAuthFlowRegistry:return flowsdef _write(self, payload: dict[str, OAuthFlowBinding]) -> None:- self.path.parent.mkdir(parents=True, exist_ok=True)bounded = dict(list(payload.items())[-self.max_entries :])- content = json.dumps(+ write_state_document(+ self.path,{flow_id: {"channel": binding.channel,@@ -284,16 +283,7 @@ class OAuthFlowRegistry:}for flow_id, binding in bounded.items()},- ensure_ascii=False,- separators=(",", ":"),)- with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=self.path.parent, delete=False) as tmp:- tmp.write(content)- tmp.flush()- os.fsync(tmp.fileno())- temp_name = tmp.name- os.chmod(temp_name, 0o600)- os.replace(temp_name, self.path)def remember(self,diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex b846f8155..4b3f55d65 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -5,9 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-import osimport secrets-import tempfileimport threadingfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezone@@ -33,6 +31,7 @@ from .events import (event_reason_label,)from .resolver import ModelHubTurnResolution, source_eligible_for_backend+from .state_file import write_state_documentBackendName = Literal["claude", "codex", "opencode"]@@ -707,24 +706,7 @@ class BoundedProvenanceStore:return self._read_path(self.path)def _write_path(self, path: Path, records: list[dict]) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- content = json.dumps(- records[-self.max_entries :],- ensure_ascii=False,- separators=(",", ":"),- )- with tempfile.NamedTemporaryFile(- "w",- encoding="utf-8",- dir=path.parent,- delete=False,- ) as tmp:- tmp.write(content)- tmp.flush()- os.fsync(tmp.fileno())- temporary_path = tmp.name- os.chmod(temporary_path, 0o600)- os.replace(temporary_path, path)+ write_state_document(path, records[-self.max_entries :])def _write(self, records: list[dict]) -> None:self._write_path(self.path, records)diff --git a/core/handlers/model_hub/revocations.py b/core/handlers/model_hub/revocations.pyindex 023ee2fa4..7becda19d 100644--- a/core/handlers/model_hub/revocations.py+++ b/core/handlers/model_hub/revocations.py@@ -3,13 +3,13 @@from __future__ import annotationsimport json-import os-import tempfileimport threadingfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Literal, cast, get_args+from .state_file import write_state_document+RevocationOperation = Literal["revoke_credential",@@ -80,23 +80,17 @@ class CredentialRevocationJournal:return entriesdef _write(self, entries: list[PendingCredentialRevocation]) -> None:- self.path.parent.mkdir(parents=True, exist_ok=True)- payload = [- {- "source_id": entry.source_id,- "credential_ref": entry.credential_ref,- "operation": entry.operation,- }- for entry in entries- ]- content = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))- with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=self.path.parent, delete=False) as tmp:- tmp.write(content)- tmp.flush()- os.fsync(tmp.fileno())- temp_name = tmp.name- os.chmod(temp_name, 0o600)- os.replace(temp_name, self.path)+ write_state_document(+ self.path,+ [+ {+ "source_id": entry.source_id,+ "credential_ref": entry.credential_ref,+ "operation": entry.operation,+ }+ for entry in entries+ ],+ )def add(self,diff --git a/core/handlers/model_hub/state_file.py b/core/handlers/model_hub/state_file.pynew file mode 100644index 000000000..b3cd7db44--- /dev/null+++ b/core/handlers/model_hub/state_file.py@@ -0,0 +1,58 @@+"""Durable replacement for the Model Hub's private on-disk state documents.++Five collections persist under the state directory — resolution events, source+provenance, credential revocations, OAuth flow bindings, token usage — and every+one of them wants the same three things: the parent directory to exist, one+compact credential-free JSON encoding, and a replacement that either lands whole+or leaves the previous document exactly as it was.++Each of them used to spell that out for itself, in the same seven lines. Which is+how one temp file that outlived a failed write was really five latent orphans in+one directory: the writers deliberately swallow ``OSError`` so metering and event+recording cannot be broken by a full disk, and nothing downstream would ever+notice the residue. A bounded ledger whose state directory grows without bound is+not bounded.+"""++from __future__ import annotations++import json+import os+import tempfile+from contextlib import suppress+from pathlib import Path+from typing import Any++STATE_FILE_MODE = 0o600+++def write_state_document(path: Path, payload: Any) -> None:+ """Replace ``path`` with ``payload`` as one compact owner-only JSON document.++ The temporary file is removed unless the replacement itself succeeded, so an+ encoding, ``fsync``, ``chmod``, or rename that raises costs the caller the+ write it was already prepared to lose and nothing else.+ """++ path.parent.mkdir(parents=True, exist_ok=True)+ content = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))+ handle = tempfile.NamedTemporaryFile(+ "w",+ encoding="utf-8",+ dir=path.parent,+ delete=False,+ )+ temporary = Path(handle.name)+ replaced = False+ try:+ with handle:+ handle.write(content)+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temporary, STATE_FILE_MODE)+ os.replace(temporary, path)+ replaced = True+ finally:+ if not replaced:+ with suppress(OSError):+ temporary.unlink()diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex 5e395c7dc..72f2c6718 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -22,8 +22,6 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-import os-import tempfileimport threadingfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass@@ -32,6 +30,7 @@ from pathlib import Pathfrom typing import Callable, Final, Optional, Sequencefrom .identifiers import canonical_model_id+from .state_file import write_state_documentfrom .stream_wire import USAGE_TOKEN_CEILING, ProtocolUsageReportlogger = logging.getLogger(__name__)@@ -299,25 +298,8 @@ class BoundedUsageLedger:return sorted(rows.values(), key=_row_key)def _write(self, rows: list[dict]) -> None:- self.path.parent.mkdir(parents=True, exist_ok=True)retained = sorted(rows, key=_recency)[-self.max_rows :]- content = json.dumps(- sorted(retained, key=_row_key),- ensure_ascii=False,- separators=(",", ":"),- )- with tempfile.NamedTemporaryFile(- "w",- encoding="utf-8",- dir=self.path.parent,- delete=False,- ) as tmp:- tmp.write(content)- tmp.flush()- os.fsync(tmp.fileno())- temp_name = tmp.name- os.chmod(temp_name, 0o600)- os.replace(temp_name, self.path)+ write_state_document(self.path, sorted(retained, key=_row_key))def record(self,diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex 4fd0d9708..abe716221 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -666,6 +666,58 @@ reader asking only fakes for it. The behavioural test reuses round 10's enumeratform, driving the same `FakeStreamResponse` failure points and asserting the prelude's1028 input tokens land in the ledger at every one of them.+### Round 12 (head `69c51cbaf`)++Three findings. One is class C a ninth time, but through the half every earlier round+was not.++**Reader half versus producer half.** Rounds 7 through 11 were all readers: a fact had+been observed, and some ending could not reach it. Each fix pointed one more ending at+the observation. This finding is upstream of all of them — bytes the socket delivered+that nobody extracted. `_read_stream_prelude` asked the storage question before the+reading question, so a `prelude.write` that refused the chunk which overflowed the+16 MiB budget returned before anything parsed it. A vendor that reports usage in the+frame that happens to land past the budget was billed and never metered, and no+reader-side fallback can recover it: unobserved bytes leave nothing behind to fall back+to.++**Why `_received` is the terminal form.** Two questions get asked about the same bytes+and only the second can fail — what they say, and whether there is room to keep a replay+of them. Whether we can hold a copy is not a question about what happened upstream, so+it cannot come first. Both arrival sites now go through one owner that observes before it+buffers, and that owner is the sole caller of `prelude.write`, so an arrival site added+later cannot reorder the two questions by forgetting which comes first. The overflow path+then reaches `ended()`, which has attached the wire's report to the outcome since round 7.+`test_wire_bytes_reach_the_observer_before_the_buffer_that_can_refuse_them` states the+ordering; `test_tokens_reported_by_the_chunk_that_overflows_the_prelude_are_still_metered`+drives it, with the overflowing chunk carrying a complete `message_start`.++**Class D: five copies of one durability property.** The review flagged+`usage.py:_write` for leaving its temporary file behind when the replacement raised. The+members were enumerable immediately: `revocations.py`, `events.py`, `usage.py`,+`provenance.py`, and `oauth.py` each carried the same seven lines — mkdir, compact+credential-free `json.dumps`, `NamedTemporaryFile`, fsync, `chmod 0o600`, `os.replace` —+so one orphan was really five latent orphans in one directory. Nothing downstream can+notice: the recorders swallow `OSError` deliberately, so a full disk cannot break+metering. A ledger bounded to `max_rows` whose state directory grows by one file per+failed write is not bounded. `state_file.write_state_document` now owns the property and+the five call sites shrank to one to three lines each. The guard is enumeration-free by+construction: no module in the package other than `state_file.py` may name `tempfile`,+`os.replace`, or `os.rename`, so a sixth collection cannot spell its own replacement.++**Scope decision on the sixth site.** `config/v2_config._atomic_write_text` is the same+property in another subsystem and is already correct, including directory fsync. Promoting+both onto one owner would mean editing a widely used config module inside a metering PR+for no behavioural gain, so it stays where it is; the shared home is worth revisiting when+something else needs it.++**Class E: the catalog rows this stage never wrote.** Five `MH-USAGE-*` scenarios now name+the properties the stage actually claims — a reported token count surviving the turn's+ending, per-hop attribution on failover, a failed write costing only that write, the+read-modify-write staying off the event loop, and a report surviving a full prelude buffer.+`tests/test_model_hub_l3.py` and `tests/test_model_hub_usage.py` join `canonical_tests` and+the project index, and each scenario ID is greppable from its test's docstring.+## Todo- [x] Usage taxonomy and extraction in `stream_wire.py`diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 603540a77..4587c733a 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -117,6 +117,8 @@ capabilities:- tests/test_model_hub_resolution.py- tests/test_model_hub_injection.py- tests/test_model_hub_runtime.py+ - tests/test_model_hub_l3.py+ - tests/test_model_hub_usage.py- tests/test_opencode_server.py- id: harness_failure_recoveryname: Harness per-Session failure recoverydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 5b4648fc1..de851339f 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -8,6 +8,8 @@ capability:- tests/test_model_hub_resolution.py- tests/test_model_hub_injection.py- tests/test_model_hub_runtime.py+ - tests/test_model_hub_l3.py+ - tests/test_model_hub_usage.py- tests/test_opencode_server.py- tests/scenarios/model_hub/test_model_hub_catalog.py- tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py@@ -117,6 +119,36 @@ scenarios:kind: concurrencylayer: unittest: tests/test_opencode_server.py::test_mh_runtime_004_overlay_reservation_promotes_atomically_to_active_run+ - id: MH-USAGE-001+ name: Tokens an upstream reported before the turn ended are still metered+ status: covered+ kind: recovery+ layer: unit+ test: tests/test_model_hub_l3.py::test_the_tokens_the_engine_already_read_survive_every_ending_before_our_first+ - id: MH-USAGE-002+ name: A billed failover hop is metered against the Source that billed it+ status: covered+ kind: selection+ layer: unit+ test: tests/test_model_hub_l3.py::test_a_billed_failover_hop_is_metered_against_the_source_that_billed_it+ - id: MH-USAGE-003+ name: A failed ledger write leaves neither residue nor a damaged document+ status: covered+ kind: persistence+ layer: unit+ test: tests/test_model_hub_usage.py::test_a_write_that_fails_leaves_neither_residue_nor_a_damaged_document+ - id: MH-USAGE-004+ name: Metering never performs its ledger read-modify-write on the event loop+ status: covered+ kind: concurrency+ layer: unit+ test: tests/test_model_hub_l3.py::test_neither_metering_owner_writes_the_ledger_on_the_event_loop+ - id: MH-USAGE-005+ name: A usage report is metered even when the prelude buffer refuses to keep its bytes+ status: covered+ kind: recovery+ layer: unit+ test: tests/test_model_hub_runtime.py::test_tokens_reported_by_the_chunk_that_overflows_the_prelude_are_still_metered- id: MH-RES-LIVE-001name: Live turn retries an eligible backup before streaming startsstatus: covereddiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex c8354266e..34956e0c8 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -6679,7 +6679,7 @@ def test_no_downstream_ending_after_adoption_can_drop_the_turn_from_the_ledger(def test_the_tokens_the_engine_already_read_survive_every_ending_before_our_first(tmp_path: Path,) -> None:- """Review 4965405530: the engine read the head of this body before we did.+ """MH-USAGE-001, review 4965405530: the engine read this body's head before we did.The gateway asks the engine for a stream, and the engine only knows there isone because it read far enough to see the first model output — which for@@ -6926,7 +6926,7 @@ def test_a_surfaced_buffered_error_still_meters_the_tokens_it_billed(def test_a_billed_failover_hop_is_metered_against_the_source_that_billed_it(tmp_path: Path,) -> None:- """Every hop that reported tokens billed its own Source, not the last one."""+ """MH-USAGE-002: every hop that reported tokens billed its own Source, not the last one."""async def exercise() -> None:first = _source("src_meterhop001", "Billed hop")@@ -7078,7 +7078,7 @@ def test_a_downstream_disconnect_meters_the_terminal_frame_exactly_once(def test_neither_metering_owner_writes_the_ledger_on_the_event_loop(tmp_path: Path,) -> None:- """A ledger read-modify-write is file I/O; the controller loop must not wait."""+ """MH-USAGE-004: a ledger read-modify-write is file I/O; the loop must not wait."""async def exercise() -> None:recording_threads: list[int] = []diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 21fdb2ce4..a379dbfbb 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -269,6 +269,76 @@ def test_stream_prelude_total_budget_ends_as_network_failure_and_cleans_spill(asyncio.run(run())+def test_tokens_reported_by_the_chunk_that_overflows_the_prelude_are_still_metered(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """MH-USAGE-005, review 4965677908: the vendor billed the frame that broke the buffer.++ Every earlier round of this class was a reader that could not reach an+ observed fact. This one is the producer: the socket delivered a complete+ usage report, and the only reason it would go unrecorded is that the prelude+ had no room left to keep a replay of the bytes carrying it. Whether we can+ store a copy is not a question about what the upstream said.+ """++ async def run() -> None:+ message_start = (+ b'event: message_start\ndata: {"type":"message_start","message":{"usage":'+ b'{"input_tokens":900,"cache_read_input_tokens":128}}}\n\n'+ )+ filler = b": " + b"k" * 4090 + b"\n\n"+ budget = len(filler) + len(message_start) - 1+ reads = iter([filler, message_start])++ class TrackingPrelude(client_module._StreamPrelude):+ def __init__(self) -> None:+ super().__init__(memory_limit=budget, total_limit=budget)++ class Content:+ async def read(self, _size: int) -> bytes:+ return next(reads)++ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}+ content = Content()++ def close(self) -> None:+ return None++ class Session:+ async def post(self, *_args, **_kwargs):+ return Response()++ async def close(self) -> None:+ return None++ source = SourceRecord(+ source_id="src_overflowbill",+ vendor="anthropic",+ protocol="anthropic",+ base_url="https://overflow.example.test",+ credential_ref="cred_overflowbill",+ allowed_origins=("codex",),+ model_ids=("claude-sonnet-4-5",),+ prefix="overflow",+ )+ monkeypatch.setattr(client_module, "_StreamPrelude", TrackingPrelude)+ monkeypatch.setattr(client_module.aiohttp, "ClientSession", lambda **_: Session())+ client = EngineClient(+ EngineConnection("http://127.0.0.1:15222", "management", "gateway")+ )++ handle = await client.invoke(source, "claude-sonnet-4-5", {}, stream=True)+ outcome = await handle.outcome()++ assert outcome.kind == RawOutcomeKind.NETWORK_ERROR+ assert outcome.stream_started is False+ assert outcome.usage == ProtocolUsageReport(input_tokens=1028, cached_input_tokens=128)++ asyncio.run(run())++def _write_fixture_archive(tmp_path: Path, *, version: str = "7.2.95") -> tuple[Path, bytes]:tmp_path.mkdir(parents=True, exist_ok=True)binary = (diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex 6c18054ae..932ce943b 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -1111,3 +1111,38 @@ def test_stream_boundary_catalog_exercises_every_enumerated_dimension() -> None:seen_states.add(settlement_state)assert state.terminal_outcome == (None if settlement_state == "pending" else settlement_state)assert seen_states == set(STREAM_BOUNDARY_DIMENSIONS["settlement_state"])+++def test_wire_bytes_reach_the_observer_before_the_buffer_that_can_refuse_them() -> None:+ """Review 4965677908: a full prelude must not erase a report it received.++ Two questions get asked about the same bytes and only the second can fail:+ what they say, and whether there is room to keep a replay of them. Every+ arrival site therefore hands them to one owner, and that owner reads before+ it stores — so a site added later cannot reintroduce the order that drops a+ usage frame the vendor already billed.+ """++ source = CLIENT.read_text(encoding="utf-8")+ assert source.count("prelude.write(") == 1+ owner = ast.get_source_segment(source, _functions(_tree(CLIENT))["_received"])+ assert owner is not None+ assert "prelude.write(" in owner+ assert owner.index("wire_state.observe(") < owner.index("prelude.write(")+++def test_model_hub_state_documents_have_one_atomic_replacement_owner() -> None:+ """Review 4965677908: a failed replacement must not leave a temp file behind.++ Cleanup is unobservable from outside — the writers swallow ``OSError`` so a+ full disk cannot break metering — so it cannot be maintained one collection+ at a time. A module that spells its own temporary file is a second owner of+ the property, whether or not it remembers the cleanup.+ """++ owners = set()+ for module in sorted((ROOT / "core/handlers/model_hub").glob("*.py")):+ text = module.read_text(encoding="utf-8")+ if any(marker in text for marker in ("tempfile", "os.replace", "os.rename")):+ owners.add(module.name)+ assert owners == {"state_file.py"}diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex 0e343d348..bdc46daac 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -21,6 +21,7 @@ from pathlib import Pathimport pytest+from core.handlers.model_hub import state_filefrom core.handlers.model_hub.identifiers import MODEL_ID_MAX_LENGTHfrom core.handlers.model_hub.stream_wire import (PROTOCOL_STREAM_TAXONOMY,@@ -1117,6 +1118,33 @@ def test_a_record_leaves_no_temporary_file_behind(tmp_path: Path) -> None:assert [entry.name for entry in ledger.path.parent.iterdir()] == [ledger.path.name]+def test_a_write_that_fails_leaves_neither_residue_nor_a_damaged_document(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """MH-USAGE-003, review 4965677908: a failed replacement must cost only that write.++ The recorder above this ledger swallows `OSError` so a full disk cannot break+ metering, which means nobody downstream ever sees what a failed write left+ behind. A ledger bounded to `max_rows` whose state directory gains one orphan+ per failure is not bounded, and a half-written document would lose the days+ already recorded — so the write either lands whole or changes nothing.+ """++ ledger = _ledger(tmp_path)+ ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)+ recorded = ledger.path.read_bytes()++ def refuse(*_args, **_kwargs) -> None:+ raise OSError("no space left on device")++ monkeypatch.setattr(state_file.os, "replace", refuse)+ with pytest.raises(OSError):+ ledger.record(source_id="src_b", model_id="model-y", usage=None, at=NOW)++ assert [entry.name for entry in ledger.path.parent.iterdir()] == [ledger.path.name]+ assert ledger.path.read_bytes() == recorded++def test_days_bucket_by_the_host_calendar_not_utc(tmp_path: Path) -> None:"""Avibe is local-first, so a day boundary is the user's midnight."""diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 52c7e8c9b..df192e190 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -651,9 +651,8 @@ async def _read_stream_prelude(raise for the call to be metered."""- if not prelude.write(first):+ if not _received(first, prelude=prelude, wire_state=wire_state):return _prelude_ended_outcome(source, model_id, response.status)- wire_state.observe(first)while not wire_state.model_output_started:outcome = _observed_stream_terminal_outcome(wire_state,@@ -677,12 +676,37 @@ async def _read_stream_prelude(if completion is not None:return completionreturn _prelude_ended_outcome(source, model_id, response.status)- if not prelude.write(chunk):+ if not _received(chunk, prelude=prelude, wire_state=wire_state):return _prelude_ended_outcome(source, model_id, response.status)- wire_state.observe(chunk)return None+def _received(+ chunk: bytes,+ *,+ prelude: _StreamPrelude,+ wire_state: ProtocolSSEState,+) -> bool:+ """Take receipt of bytes the wire delivered: read them, then keep a copy.++ Two different questions get asked about the same bytes, and only the second+ one can fail: what they say, and whether there is room to store a replay of+ them. Asking the storage question first lets a full prelude erase the report+ that arrived in the chunk that filled it — tokens the vendor billed, delivered+ on the socket, dropped because we had nowhere to put a copy. Whether we can+ hold a copy is not a question about what happened.++ Every earlier round of this class was the reading half: a fact was observed+ and some ending could not reach it. This is the writing half, and it has no+ reader-side remedy at all — bytes nobody observed leave nothing behind to fall+ back to. So this is the sole caller of ``prelude.write``, and an arrival site+ added later cannot reorder the two questions by forgetting which comes first.+ """++ wire_state.observe(chunk)+ return prelude.write(chunk)++def _prelude_ended_outcome(source: SourceRecord,model_id: str,