Skip to content

Recover usage rows after a crash without changing charges - #2387

Merged
AbirAbbas merged 7 commits into
app/v3from
c27/usage-flush-gap
Nov 11, 2026
Merged

AbirAbbas merged 7 commits into
app/v3from
c27/usage-flush-gap

Conversation

@santoshkumarradha

@santoshkumarradha santoshkumarradha commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

What changes

A usage row that was still in memory when the process exited at the 2-second flush deadline was lost. The next start or chat open did not bring it back when the chat had other rows, and rows with no chat behind them (image calls, Factory triage, team proposals) had nothing to rebuild from. Model-only calls after a lost hold had no saved receipt.

This PR makes every complete usage row durable before RecordUsage returns, at microsecond cost.

  • Journal: <ledger>.pending-v1.jsonl (normally usage.jsonl.pending-v1.jsonl). Each line is one complete session.UsageLine row, identified by its ChargeID.
  • Append: one O_APPEND write of the full line while holding a shared lock on the ledger. Appenders don't contend with each other. A process checks the ledger generation after taking the lock and opens the journal fresh, so no row can land in a file that compaction already replaced.
  • Sync: fsync runs in the background every 100 ms or every 64 rows, whichever comes first, and always at clean close. The directory is synced only when the file is created or replaced.
  • Replay and compaction: at startup, rows whose ChargeID the ledger lacks are booked with their original amount, day, owner and billing facts. At startup and at clean close, the journal is rewritten atomically under the exclusive ledger lock (temp file, fsync, rename, directory fsync) to keep only rows the ledger still lacks. After a clean exit the journal is normally empty.
  • Errors: a failed write keeps the row in memory and retries with capped exponential backoff, logging one line per identity. A ledger or journal error never fails a chat. Unknown or torn lines are kept or set aside, never treated as booked.
  • Model-only calls: a new WAL line {"V":3,"op":"model","model":{...}} serializes cellstore.ModelCall as-is, so a refused seal can recover its receipt on reopen.

Durability

Exact on a process crash: every row whose write returned is booked exactly once. On power loss, up to the last 100 ms batch can be lost, as on base.

Compatibility

  • Older engines ignore the journal file. Its rows wait for a newer engine to replay them.
  • Today's WAL reader skips the V3 line and keeps every V1/V2 line around it (TestOpenWALSkipsV3ModelWithoutLosingV1V2Records in wal_model_compat_test.go).
  • A downgrade can lose model-call receipt detail when an older engine rewrites the WAL. It never loses money, which is kept in the usage journal.

Performance

RecordUsage, 1,000 rows per run, 3 alternating base/head pairs on the same machine:

Pair base p50 / p95 this PR p50 / p95
1 1.7 / 5.4 µs 10.7 / 22.5 µs
2 1.8 / 4.2 µs 12.4 / 25.2 µs
3 1.7 / 5.7 µs 13.4 / 25.3 µs

Base only queues the row in memory. This PR also writes it to the journal.

Live 4-crew wall time, sealed

TestLiveFourCrewsWallTime (in this PR, //go:build e2e) runs four crews, each writing 20 files, with deepseek/deepseek-v4.1-flash for every call. It ran in a container with no real home folder, keychain, D-Bus or GitHub credentials, and only the provider key passed by name. Runs alternated base and this PR. In every run, all four crews wrote 20/20 files, every ledger row recorded deepseek/deepseek-v4.1-flash, the ledger's dollars equalled the provider-billed dollars exactly, and the file and socket trace showed 0 attempts on home, keychain or credential paths.

Pair base wall this PR wall base provider time / calls this PR provider time / calls
1 9.96 s 15.48 s not measured not measured
2 8.22 s 10.15 s not measured not measured
3 9.12 s 14.65 s not measured not measured
4 8.71 s 10.26 s 37.3 s / 37 40.8 s / 35
5 7.32 s 9.99 s 37.7 s / 35 47.4 s / 39

Medians: base 8.71 s, this PR 10.26 s. Total live spend: $0.272.

Engine time with the provider held fixed: the same test against a local provider with a fixed 300 ms delay per call, 10 alternating pairs. Base took 1.873–1.990 s (median 1.883 s) and this PR took 1.884–2.047 s (median 1.927 s), about +40 ms (+2%).

Pairs 6-8, base first, with time-to-first-byte (TTFB) and stream-read time from the timing proxy:

Pair base wall this PR wall TTFB median base / PR stream-read sum base / PR max in flight base / PR
6 9.21 s 11.57 s 91 / 153 ms 36.2 / 42.4 s 10 / 8
7 8.17 s 9.38 s 87 / 107 ms 33.2 / 35.3 s 10 / 8
8 8.22 s 11.13 s 125 / 162 ms 32.0 / 42.0 s 8 / 9

Pairs 9-10, this PR first. The spend stop ended the run after one and a half pairs.

Pair this PR wall base wall TTFB median PR / base stream-read sum PR / base output tokens PR / base
9 11.12 s 16.81 s 149 / 144 ms 40.4 / 40.2 s 13,887 / 11,775
10 8.58 s not run 164 ms / – 34.3 s / – 11,959 / –

All live runs passed every check. Total live spend was $0.522 across three approvals, each with its own stop line.

Further checks:

  • Offline, nothing in the engine runs per stream chunk. Each model call does one RecordUsage, one journal append and about 1.1 fsyncs. With 200 streamed chunks at 5 ms, 10 alternating pairs, the wall median was 6.850 s on base and 6.849 s on this PR, with equal time-to-first-byte and stream-read time. A 50 ms block injected into the background fsync did not move wall time.
  • Captured requests are identical between the trees apart from the temp working directory and the per-session prompt_cache_key. Total request bytes were 726,032 vs 726,016, with the same tools and no max_tokens.
  • Run order: in the first 8 pairs base ran first, and the second run (this PR) was slower every time. In the one complete pair with this PR first, base ran second and was slower: this PR 11.12 s, base 16.81 s. Output tokens vary by about 18% between runs of the same script.

Reading: no engine slowdown was shown. Requests are identical, the offline engine shows no gap, and the one reversed pair flips the difference. Limits: there was only one complete reversed pair; output tokens vary by about ±18% between runs of the same script; and in every complete pair the second run was slower.

Earlier reading of pairs 1-5: the live gap follows provider-call time. Each call, measured from request to the end of the streamed reply, averaged 1.01–1.08 s on base and 1.17–1.22 s on this PR in the timed pairs. That interval includes the engine reading the stream, so this measurement cannot fully separate model latency from stream consumption. With the provider fixed, the engine difference is about 40 ms.

Validation

  • Red tests for the three measured gaps now pass: a rebuild skipping an exited writer's last charge, rows with no chat, and a model-only call after a lost hold.
  • New tests, each passing 10 times:
    • A crash between the ledger append and the journal rewrite books the charge exactly once and compacts the journal.
    • A crash in the middle of a rewrite leaves the old journal intact, books nothing twice, and cleans up the temp file.
    • Two processes append while a third compacts: no row lost, none doubled.
    • A process killed with SIGKILL right after RecordUsage returns, with projection and fsync blocked: replay books the row once.
    • With the disk failed, retries back off up to a cap and log one line.
    • Batch triggers at 100 ms and 64 rows, using a virtual clock.
  • 190 existing focused tests pass in session, cellindex, cellstore, syncsetup and manual. gofmt and vet pass.

🤖 Generated with Claude Code

santoshkumarradha and others added 7 commits November 5, 2026 03:45
Queued usage could disappear after the close deadline, and model-only receipts could disappear after a refused seal. Sync complete rows to a pending journal, replay by ChargeID under the ledger generation lock, and compact only after syncing booked money. Retain failed rows with capped retry and one identity log. Persist model WAL V3 records while preserving anonymous legacy receipt semantics.

Validation: 189 focused tests, six alternating base/head latency measurements, gofmt and vet. The requested pr: 0 changelog placeholder is the sole changelog-check failure.
A crash after receipt publication but before WAL cleanup left the model in both stores. Share the identity membership check between recorder reopen and SealRecovered, then prune the stale WAL model after successful recovery. Anonymous historical calls keep their existing semantics.

The new regression failed with two receipts before the fix and now passes with exactly one. Focused cellindex, cellstore and syncsetup checks pass, and cellstore vet passes.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
It times four crews writing 20 files each, sums provider time through a
timing proxy, checks every ledger row's model and that ledger dollars equal
the provider-billed dollars. A local fake provider runs it offline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split fake completions across flushed deltas, record first-byte and stream-read timings, and retain canceled proxy calls. Add a test-only overlay generator for usage, lock, fsync and model WAL counters and background-sync contention injection. Production sources remain unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@AbirAbbas
AbirAbbas merged commit e92fcd0 into app/v3 Nov 11, 2026
1 check passed
@AbirAbbas
AbirAbbas deleted the c27/usage-flush-gap branch November 11, 2026 17:42
AbirAbbas added a commit that referenced this pull request Nov 11, 2026
The durable journal created batch channels on recording callers, but the shared usage writer could send to them after that caller scope ended. The projection-fsync follow-up exposed fatal synctest sends in dev Memory cases. Start synchronizers from a separately joined writer-owned loop, retain independent batching under stalled projection, and keep all existing assertions and shutdown ceilings.
AbirAbbas added a commit that referenced this pull request Nov 11, 2026
…16 of 22) (#2597)

* app tests: B2 recovery must show its worker's answer, not only a settled state (#2198)

* Typing into your own idle chat reopens it instead of saying it's available (#2469)

* app: answered receipts and quiet notices disappear after relaunch (#2586)

* A big move from the hosted relay goes through; a move sync answered with an error says so (#2366)

* tests: FIFO and Unix-helper cases build for Windows; make vet checks the Windows test build (#2192)

* session: split the task and memory roads back under the endings ceiling (#2149)

* Book a tool completion once when the process dies between seal and WAL cleanup (#2377)

* Keep waiting job actions from going stale on bookkeeping (#2463)

* factory: keep close revision checks strict after action history merge

* Spending: daily rollup for date-only spend.report (#2269)

* Retain Library activity in the rollup byte budget during replay

* Keep billing facts and missing receipts when taking a chat (#2386)

* Retain the Library receipt helper while replaying the billing merge

* session: retain Library activity on sealed missing-receipt rows

* An idle job chat stops reading every job ten times a second (#2358)

* Set the explicit Memory-off premise in the idle discovery fixture

* agentdid: add encrypted custody, purpose-bound signing and v1 identity documents (#2090)

* Idle factory workers wait for changes instead of re-decoding the store (#1931)

* store: distinguish file identity stamps from shared cache stamps

* factory: bind retained caches to complete file identity and avoid duplicate pull beats

* Count unchanged-floor settlement passes without decoding jobs

* Recover usage rows after a crash without changing charges (#2387)

* session: keep journal appends in the usage funnel and back off by delay

* Crossing the day cap stops running work, not only the next turn (#2364)

* session: sample the opening job budget before idle admission

* Factory: compare failing Go tests with the base, and Accept as is (#2570)

* factory: retain strict revision guard when pausing recovery

* app: release the recovery-chat host lock through defer

* Keep explicit test completion rules and conflict ownership

* docs: record the local app/v3 integration wave

* tests: open the Knowledge offer with Memory explicitly off

* session: let the journal own projection durability until compaction

* tests: join routed receipt settlement before inspecting its charge

* tests: request the job-vault discovery passes that the fixture checks

* tests: arm the admission ledger probe after the startup snapshot

* fix(session): preserve free helper admission through shared daily gates (#2364)

* fix(factory): compare pinned failures through the command fence (#2570)

* changes: the app/v3 open-PR wave names its pull request

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* test(sync): pair shared fixtures before #2090 custody saves a solo identity

Custody now creates a quiet local profile on first save. Establish the shared fixtures paired premise before that save so Ensure does not preserve an unintended solo marker. Keep every notice, read-count, ownership, and explicit solo assertion.

* fix(factory): invalidate #2358 handover look before stale admission

The new cheap stop watcher saw a stopped job handed to a chat while the retained full admission memo trusted an older floor for 100 ms. Revalidate the shared floor identity before reuse. Keep unchanged document reads at zero and retain all allocation caps.

* test(factory): keep #2570 belt fixture outside its profile ancestor

The new PR-base tool test put codeaf state under its requested workspace, so dev correctly refused the Factory chat before any tool ran. Give the profile its own temporary directory while preserving the real tool call and repair assertions.

* fix(session): keep #2387 journal sync in its process writer scope

The durable journal created batch channels on recording callers, but the shared usage writer could send to them after that caller scope ended. The projection-fsync follow-up exposed fatal synctest sends in dev Memory cases. Start synchronizers from a separately joined writer-owned loop, retain independent batching under stalled projection, and keep all existing assertions and shutdown ceilings.

* fix(session): route #2570 base-sync arguments through the shared decoder

The new tool decoded its own arguments directly, violating dev’s common argument-decoder law. Reuse decodeToolArguments while preserving its empty-object and bound-checkout checks, existing refusal text, and every assertion. Existing structural and carried tool tests pass, with unchanged 208-byte/4-allocation successful calls.

* test(session): initialize stalled journal fixtures through the writer owner

The journal-scope repair made the process writer own a joined synchronizer. Three dev fixtures still built raw writers and skipped that initialization, panicking at close. Reuse the existing constructor before installing their projection blockers. Keep every assertion, shutdown ceiling, and all 200 by 4 close/flush race iterations; no production source changes.

* test(app): end the stray child portably so the Windows test build vets (#2192)

#2192 makes `make vet` check the Windows test build. The one-engine test
that landed with app/v3 ended its stray child with syscall.Kill, which
does not exist on Windows, so the new vet step failed on dev's tree.
os.Process.Kill sends the same signal on Unix and builds everywhere.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants