Repository navigation
perf(codex-usage): resume rollout scans at the last parsed byte - #21102
Conversation
Codex rollout files are append-only and grow all day, but any append changed both mtime and size, so `canReuse` discarded the cached entry and the scanner re-read the whole file from byte 0 on the Electron main process. On one real corpus that was 6.59 GB re-read per cycle across 26.63 GB / 21,110 files. Each parsed file now persists a resume point: the offset just past the last newline-terminated line, the parse context at that offset (session id, cwd, model, running totals), a sha256 of the 4 KiB before it, and the file's dev:ino. A grown file resumes there and merges the appended rollup into the cached one; anything unproven falls back to a full reparse — truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never depends on mtime equality, so a coarse-mtime filesystem cannot hide an append. Fixture: a 75,737-byte rollout with a 758-byte append re-read 76,495 bytes before and 8,950 after (the append plus two bounded 4 KiB boundary windows). Also bounds the automation-attribution force predicate for both Codex and Claude: it keyed on `lastScanError`, so a persistently failing scan forced a fresh full rescan on every single lookup. It now keys on the most recent scan attempt, which is one forced scan per run regardless of outcome.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe change adds byte-offset JSONL reading and resumable Codex rollout parsing. Resume state includes parser context, file identity, and head and boundary digests. Invalid resume states trigger full reparses. The scanner merges resumed projections and preserves event ownership. Tests cover appends, partial lines, rewrites, rotations, legacy copies, and fork claims. Claude and Codex automation scans now force at most one scan attempt per run after a failure. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Some rewritten rollout files can produce stale usage totals instead of triggering a full reparse, so this should be resolved before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides extensive technical context, rationale, measurements, testing, limitations, and verification results. However, it omits the required Linked Issue, Visual Proof section with an explicit N/A for this non-UI change, and several required template sections and checklist confirmations. Resolution Add the required template sections or clearly map existing content to them. Include a valid issue reference under Linked Issue using
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 44f65060-34c9-4fce-bdb6-b9de017b5162
📒 Files selected for processing (13)
src/main/claude-usage/claude-usage-automation-attribution.tssrc/main/claude-usage/store.test.tssrc/main/codex-usage/codex-automation-run-attribution.tssrc/main/codex-usage/codex-rollout-file-parse.tssrc/main/codex-usage/codex-rollout-resume-state.tssrc/main/codex-usage/codex-usage-aggregation.tssrc/main/codex-usage/scanner-incremental-append.test.tssrc/main/codex-usage/scanner-paths.test.tssrc/main/codex-usage/scanner.tssrc/main/codex-usage/store-automation-usage.test.tssrc/main/codex-usage/types.tssrc/main/usage/jsonl-line-offsets.test.tssrc/main/usage/jsonl-line-offsets.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
There was a problem hiding this comment.
ℹ️ One correctness gap in the new resume path — details inline. Everything else reads clean.
Reviewed changes
- Per-file resume point —
CodexUsageParseResumeStatenow persists the offset past the last newline-terminated line, a sha256 of the 4 KiB before it,dev:ino, and the parser context;resolveCodexRolloutResumefails closed on a short read, a digest mismatch, or a changed physical id, and deliberately ignoresmtime. - Byte-accurate JSONL reader —
src/main/usage/jsonl-line-offsets.tsreplacesreadline(which hides bytes-per-line) and yields{ line, endOffset, terminated }; CRLF is stripped from the text but counted in the offset, so no per-line drift. - Parser extraction —
parseCodexUsageFile/getProcessedFileInfomoved intocodex-rollout-file-parse.tsand the aggregation intocodex-usage-aggregation.ts; the scanner seeds cross-file event ownership from reused and resumed files, infilesorder. - Attribution forcing bounded — Codex and Claude now force at most one scan attempt per run, keyed on
Math.max(lastScanStartedAt, lastScanCompletedAt)instead of the stickylastScanError;lastScanStartedAtis stamped on every attempt before the first await, so the predicate can't false-positive on an in-flight scan. - Coverage — new incremental-append suite measures bytes actually streamed, plus JSONL offset, legacy-bridge reparse, and attribution regression tests.
The resume merge is sound for append-only growth: the checkpoint (parsedBytes + context) is a faithful snapshot because previousTotals is always reassigned, never mutated in place, so the shallow resumeContext copy at a partial tail is safe; and byte accounting is exact for CRLF/multibyte. I could not construct a divergence for appends, truncation, or rotation that lands before validation.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The resume guard proved only the 4 KiB before the resume offset, and leaned on dev:ino to catch a rollout that was replaced at the same path. ext4 and overlayfs hand a recreated file the inode the old one freed, so on Linux that check passes and a same-length prefix swap resumes over changed history. Measured 20/20 inode reuse on ext4 and overlayfs, 0/20 on APFS and tmpfs -- which is why the case only failed in CI. An in-place prefix rewrite kept no inode change on any platform, so that variant was missed on macOS too. Digest a bounded window at the start of the parsed prefix as well. When the two windows meet, one read covers the whole prefix and leaves no gap. The head window is carried across a resume rather than re-read, so a resumed scan reads the appended bytes plus three 4 KiB windows.
There was a problem hiding this comment.
ℹ️ No new issues in the incremental commits. I traced the head-window guard end to end and could not construct a case where a changed prefix is resumed over; an independent pass reached the same verdict.
Reviewed changes
- Head-window verification (
f077f014a4) —CodexUsageParseResumeStategains a second digest,headDigestover[0, 4096), andresolveCodexRolloutResumenow requires bothheadDigestandboundaryDigestto match. A same-length rewrite that changes the leading records but leaves the tail and inode intact — missed on every platform before, sincephysicalFileIdcannot catch an in-place rewrite — now falls back to a full reparse.isUsableResumeStaterejects states persisted before the field existed. - Carried head digest —
readPrefixDigestsaccepts acarriedHeadDigestand skips re-reading the head window when it already starts with4096:. This is only safe because a4096:digest is produced over exactly[0, 4096)(theparsedBytes === 4096coalesced case is the same range), the layout is a pure function ofparsedBytes, and parsing can only advance that offset — so single-window → disjoint is the only transition and the carry is accepted only for the byte range it was computed over.resolvenever trusts the carry, so a head that changed after the read is caught by the next scan. - Window coalescing — when
parsedBytes <= 8192the two windows meet and a single read covers the whole prefix, leaving no unhashed gap; both digests are set to that one value. - Tests (
cd13871fe0,b31afd795f,88a8db59db) — added the single→disjoint layout switch, a tail-only swap that isolates the boundary window, a rotation whose prefix is swapped, and an in-place prefix rewrite pinned to an unchanged inode, plus a carry-sensitive byte-count bound (appended + 3×4096). Each of these fails under the corresponding mutation.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
… gone The scanner verifies a rollout's prefix in its first pass and reads it in the second, so a truncation in between left the merged projection holding the whole pre-truncation history while `processedFile` was re-stat'd to the new, smaller size. Size and mtime then matched disk with no resume state left to reject, so the reuse path served the stale total on every later scan. The resume-state builder returns null only on a short read, which is exactly that signal; on it, drop the merge and reparse the file from zero. Also covers three guards that no test was holding: the unterminated-tail resume suppression (a tail that is valid JSON minus its newline is counted, so resuming over it double-counts), the short-read check in `readWindowDigest` (without it a resume point past EOF verifies against itself), and the legacy-suffix exclusion in the scanner's resume guard (bridge markers can appear on a file that already has a resume state).
The scanner verified each resume point while walking the sessions directory, then parsed the files afterwards, so every file discovered or parsed in between widened the gap between the check and the read. A rollout replaced in that gap resumed at the old offset into unrelated bytes: the cached session id, cwd, model and running totals were stitched onto another file's records, and because the projection was then re-stat'd to the new size, the reuse path froze the corrupted numbers. A shrink was the visible half of this; a replacement larger than the recorded offset never short-reads and corrupts instead of going stale. Re-run the full check — inode, head window and boundary window — inside the parse, against the file about to be read. The short-read fallback added alongside it still covers the narrower case of a truncation landing after that check, during the read itself. Cost, measured on the existing byte oracle: a resumed file now reads `appended + 5 * 4096` rather than `appended + 3 * 4096`, paid only by files that changed since the last scan; untouched rollouts still read nothing. Two byte-total assertions that a 15 KB rollout can no longer satisfy now assert their intent directly — that the parse read did not reopen at byte 0 — via a stream oracle that records each read's offset.
The mid-scan replacement case was written with a heavier replacement so the token totals diverged, which overstated how visible the defect is. Rebuilt on the variant where the stale prefix contributes exactly as many events as the resumed read skips: daily aggregates and token totals then match a cold scan byte for byte, and the misattribution — 60 records of one session recorded against another — is the only remaining signal. Oracle is now the session shape. Removing the point-of-use re-verification fails it with `session-grower` in place of `session-other`; every totals-based assertion still passes under that mutation.
There was a problem hiding this comment.
ℹ️ No critical issues — the mid-scan truncation freeze is fixed; one residual race in the same guard is detailed inline.
Reviewed changes
- Shrink-fallback guard —
parseCodexUsageFilenow recurses into a full reparse whenbuildCodexRolloutResumeStatereturnsnull(a short read) after consuming a resume plan, so a rollout truncated between discovery and parse no longer merges its pre-truncation projection under the smaller(size, mtimeMs)thatcanReusethen serves forever (codex-rollout-file-parse.ts:135-154). - Resume-state unit tests — new
codex-rollout-resume-state.test.tspins the short-read refusal (whole-prefix and disjoint-boundary layouts) andresolveCodexRolloutResume's truncation-vs-growth verdicts. - Mid-scan mutation seam + scanner test —
scanner-incremental-append.test.tsgains anonStreamOpenhook that mutates the tree between two files' parse reads, plus a test that shrinks a rollout in that exact window and asserts the merged total is not frozen by a later reuse. - Legacy-bridge coverage —
scanner-paths.test.tsadds a test that a source which gains bridge markers after being resumed reparses in full rather than resuming over the copied prefix.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Point-of-use resume re-verification —
parseCodexUsageFilenow re-runsresolveCodexRolloutResumeagainst the file about to be read, beforegetProcessedFileInfo, so a rollout rewritten, rotated, or truncated during the discovery→parse gap falls back to a full reparse instead of stitching the cached session id, cwd, model, and running totals onto unrelated records (codex-rollout-file-parse.ts:91-102). This closes the truncation and equal-or-larger rewrite cases of the phase-gap concern. - Read oracle in the scanner test — the
createReadStreammock now recordsstart/bounded, andreparsedFromStartasserts a full reparse from the unbounded read's offset rather than inferring it from byte totals. - Mid-scan replacement test — a replacement larger than the recorded offset (where no short read can fire) is now covered; the oracle is session shape via
eventCountsBySession, since the stale-prefix and resumed-skip event counts make token totals provably identical to a cold scan for that fixture. - Window budget updated — the point-of-use re-check makes five bounded 4 KiB windows per resumed file; the byte-bound assertion and the PR measurement text both reflect it.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 7f2a2afd-d9f2-42cb-852f-0c2fdad143a2
📒 Files selected for processing (2)
src/main/codex-usage/codex-rollout-file-parse.tssrc/main/codex-usage/scanner-incremental-append.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
…r it Point-of-use re-verification made a resumed scan cost five bounded windows, which is more than re-reading a small rollout outright. Measured against a cold reparse of the same file, resuming lost below a 12,288 B prefix and lost badly under 8 KiB, where the coalesced-window layout rehashed the whole prefix on each of the three verification passes. Set the floor at that break-even — 3 * 4096, the point where two verification passes plus the recorded boundary stop being cheaper than reading the prefix once — and refuse to record or accept a resume point below it. Measured: a 12,568 B prefix now reads 21,234 B resumed against 21,514 B cold, and a 76,484 B rollout reads 21,238 B against 84,676 B. No size band reads more than a cold scan any more; under the floor the windows are skipped entirely and a scan reads exactly the file. With every offset past the floor the two windows can no longer overlap, so the coalesced-layout branch and the empty-window branch are gone. The floor is also input validation: a persisted offset below it would put the boundary window at a negative start and throw ERR_OUT_OF_RANGE. Tests that meant to exercise the resume path were silently reparsing whole once the floor landed — the suite stayed green while three guards lost their only coverage. They now size their rollouts off RESUMABLE_RECORDS and assert the offsets their parse reads actually opened at, so a test that stops resuming fails instead of passing quietly.
`scanner.ts` carries the same `legacySourceSkipBytes === 0` term twice and they are different guards: line 83 gates resuming, line 71 gates reuse. Only the first had a test, so dropping the second left the suite green. It is load-bearing. A cached entry can predate the bridge marker while the source file is untouched, so size and mtime still match and nothing else stops the scan serving a full-history projection for a file that is now parsed suffix-only. With a total-only record after the copy point the two readings diverge — baseline worth nothing against a delta worth three — and the reused entry reports 18 tokens where a cold scan reports 15.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Resumable-prefix floor —
codex-rollout-resume-state.tsnow definesMIN_RESUMABLE_PREFIX_BYTES = 3 × 4096andisResumablePrefixLength.buildCodexRolloutResumeStaterefuses to record at or below the floor before it reads anything, andisUsableResumeStaterejects a persisted offset there — which is also what keeps the boundary window's start non-negative. The strict>sits exactly on the break-even (resumed = appended + five windows, cold = prefix + appended + two windows ⇒ prefix = 3 × 4096). Below the floor a scan reads exactly the file. - Digest layout simplification — the coalesced-window and empty-window branches are gone. Every reachable offset is past the floor, so the head
[0, 4096)and boundary[parsedBytes − 4096, parsedBytes)windows are always disjoint and full-sized, and the carried head digest is always4096:-prefixed. Digests recorded by earlier revisions for prefixes above the floor were already this exact layout, so no schema bump is needed. - Short-read fallback rationale —
codex-rollout-file-parse.tsdocuments why, with a resume plan present, the builder's only remaining null is a short read:startOffsetis a validated state'sparsedBytes(already past the floor) andparsedBytesonly advances. I checked every production caller ofbuildCodexRolloutResumeState/resolveCodexRolloutResumeand each is gated by the same floor check. - Test hardening — the scanner suites size fixtures off
RESUMABLE_RECORDS = 40(≈15,150 B prefix, clears the floor by ~2.8 KB) and assert the actual unbounded parse-read offsets viaparseReadOffsets, so a fixture that silently stops resuming now fails instead of passing. Added the floor boundary case (null at 12,288, non-null at 12,289), persisted-under-floor rejection, and a fork reclaiming the records of a rewritten rollout.
The focused suites pass locally (46 tests across the three files), and the four prior Pullfrog threads are resolved by the point-of-use re-verification.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Reuse-gate legacy-bridge test —
scanner-paths.test.tsadds the companion to the existing resume-gate case. A cached entry that predates the bridge marker while the source file is untouched still matches on(size, mtime), soscanner.ts's reuse-sidelegacySourceSkipBytes === 0term is the only thing stopping the scan from serving a full-history projection for a source now parsed suffix-only. The fixture pins that the stat is unchanged and diverges the two readings via a trailing total-only record (baseline 0 vs a delta of 3); ablating that term reproduces exactly the stated18 vs 15failure. The other 18 cases in the file still pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The changed-code quality gate rejects any non-const type assertion, and
`onStreamOpen: { current: null as (...) | null }` is one, so `static
analysis` failed on this PR. A typed local carries the same intent.
# Conflicts: # src/main/codex-usage/scanner.ts
`shouldForceAutomationUsageScan` keyed on `max(lastScanStartedAt, lastScanCompletedAt)`, so a scan that started after the run completed but is still running counted as a finished attempt. The lookup then called `refresh(false)`, which returns early inside the 5-minute staleness window instead of joining the scan, and the run's usage read `unavailable`. Forcing instead just awaits the shared `scanPromise`. While a scan is in flight its start time is no longer treated as an attempt, so the once-per-run bound still holds: a failed scan leaves `lastScanStartedAt` past the run and stops re-forcing. The two providers' copies of the predicate were byte-identical, so it now lives in `src/main/usage/automation-usage-scan-forcing.ts`.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Shared scan-forcing predicate — the byte-identical Codex and Claude copies of
shouldForceAutomationUsageScanwere extracted intosrc/main/usage/automation-usage-scan-forcing.ts; both call sites keep the same behavior otherwise. - An in-flight scan no longer counts as a finished attempt — the predicate now takes
isScanning, and while a scan is in flight it keys only onlastScanCompletedAt. A lookup for a run that finished before that scan started now forces and joins the sharedscanPromise, instead of takingrefresh(false)'s staleness early-return and reading a pre-run cache. The one-force-per-run bound is unchanged;runScanawaits the existing promise rather than starting a second scan. - Coverage for the fix — one test per provider drives a real in-flight scan through
UsageProviderStoreLifecycleand asserts the run resolvesknown; each fails with the pre-fix predicate.store-test-harness.tsgainscreateWorktreeUsageSessionto share the fixture. - Merge adaptation —
main'sUsageWorktreeResolverrefactor is carried throughparseCodexUsageFile/scanner.tswith no behavioral change.
Both store suites pass (20 tests). All four prior Pullfrog threads remain resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…lyai#21102) * perf(codex-usage): resume rollout scans at the last parsed byte Codex rollout files are append-only and grow all day, but any append changed both mtime and size, so `canReuse` discarded the cached entry and the scanner re-read the whole file from byte 0 on the Electron main process. On one real corpus that was 6.59 GB re-read per cycle across 26.63 GB / 21,110 files. Each parsed file now persists a resume point: the offset just past the last newline-terminated line, the parse context at that offset (session id, cwd, model, running totals), a sha256 of the 4 KiB before it, and the file's dev:ino. A grown file resumes there and merges the appended rollup into the cached one; anything unproven falls back to a full reparse — truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never depends on mtime equality, so a coarse-mtime filesystem cannot hide an append. Fixture: a 75,737-byte rollout with a 758-byte append re-read 76,495 bytes before and 8,950 after (the append plus two bounded 4 KiB boundary windows). Also bounds the automation-attribution force predicate for both Codex and Claude: it keyed on `lastScanError`, so a persistently failing scan forced a fresh full rescan on every single lookup. It now keys on the most recent scan attempt, which is one forced scan per run regardless of outcome. * fix(codex-usage): verify the head of a resumed rollout prefix The resume guard proved only the 4 KiB before the resume offset, and leaned on dev:ino to catch a rollout that was replaced at the same path. ext4 and overlayfs hand a recreated file the inode the old one freed, so on Linux that check passes and a same-length prefix swap resumes over changed history. Measured 20/20 inode reuse on ext4 and overlayfs, 0/20 on APFS and tmpfs -- which is why the case only failed in CI. An in-place prefix rewrite kept no inode change on any platform, so that variant was missed on macOS too. Digest a bounded window at the start of the parsed prefix as well. When the two windows meet, one read covers the whole prefix and leaves no gap. The head window is carried across a resume rather than re-read, so a resumed scan reads the appended bytes plus three 4 KiB windows. * test(codex-usage): cover the resume window layout switch * test(codex-usage): cover the boundary window in isolation * test(codex-usage): isolate the boundary window with disjoint windows * fix(codex-usage): restart a rollout parse when its verified prefix is gone The scanner verifies a rollout's prefix in its first pass and reads it in the second, so a truncation in between left the merged projection holding the whole pre-truncation history while `processedFile` was re-stat'd to the new, smaller size. Size and mtime then matched disk with no resume state left to reject, so the reuse path served the stale total on every later scan. The resume-state builder returns null only on a short read, which is exactly that signal; on it, drop the merge and reparse the file from zero. Also covers three guards that no test was holding: the unterminated-tail resume suppression (a tail that is valid JSON minus its newline is counted, so resuming over it double-counts), the short-read check in `readWindowDigest` (without it a resume point past EOF verifies against itself), and the legacy-suffix exclusion in the scanner's resume guard (bridge markers can appear on a file that already has a resume state). * fix(codex-usage): re-verify a rollout resume point at the point of use The scanner verified each resume point while walking the sessions directory, then parsed the files afterwards, so every file discovered or parsed in between widened the gap between the check and the read. A rollout replaced in that gap resumed at the old offset into unrelated bytes: the cached session id, cwd, model and running totals were stitched onto another file's records, and because the projection was then re-stat'd to the new size, the reuse path froze the corrupted numbers. A shrink was the visible half of this; a replacement larger than the recorded offset never short-reads and corrupts instead of going stale. Re-run the full check — inode, head window and boundary window — inside the parse, against the file about to be read. The short-read fallback added alongside it still covers the narrower case of a truncation landing after that check, during the read itself. Cost, measured on the existing byte oracle: a resumed file now reads `appended + 5 * 4096` rather than `appended + 3 * 4096`, paid only by files that changed since the last scan; untouched rollouts still read nothing. Two byte-total assertions that a 15 KB rollout can no longer satisfy now assert their intent directly — that the parse read did not reopen at byte 0 — via a stream oracle that records each read's offset. * test(codex-usage): pin mid-scan replacement on attribution, not totals The mid-scan replacement case was written with a heavier replacement so the token totals diverged, which overstated how visible the defect is. Rebuilt on the variant where the stale prefix contributes exactly as many events as the resumed read skips: daily aggregates and token totals then match a cold scan byte for byte, and the misattribution — 60 records of one session recorded against another — is the only remaining signal. Oracle is now the session shape. Removing the point-of-use re-verification fails it with `session-grower` in place of `session-other`; every totals-based assertion still passes under that mutation. * perf(codex-usage): stop resuming a rollout prefix too short to pay for it Point-of-use re-verification made a resumed scan cost five bounded windows, which is more than re-reading a small rollout outright. Measured against a cold reparse of the same file, resuming lost below a 12,288 B prefix and lost badly under 8 KiB, where the coalesced-window layout rehashed the whole prefix on each of the three verification passes. Set the floor at that break-even — 3 * 4096, the point where two verification passes plus the recorded boundary stop being cheaper than reading the prefix once — and refuse to record or accept a resume point below it. Measured: a 12,568 B prefix now reads 21,234 B resumed against 21,514 B cold, and a 76,484 B rollout reads 21,238 B against 84,676 B. No size band reads more than a cold scan any more; under the floor the windows are skipped entirely and a scan reads exactly the file. With every offset past the floor the two windows can no longer overlap, so the coalesced-layout branch and the empty-window branch are gone. The floor is also input validation: a persisted offset below it would put the boundary window at a negative start and throw ERR_OUT_OF_RANGE. Tests that meant to exercise the resume path were silently reparsing whole once the floor landed — the suite stayed green while three guards lost their only coverage. They now size their rollouts off RESUMABLE_RECORDS and assert the offsets their parse reads actually opened at, so a test that stops resuming fails instead of passing quietly. * test(codex-usage): cover the reuse gate's own legacy-bridge check `scanner.ts` carries the same `legacySourceSkipBytes === 0` term twice and they are different guards: line 83 gates resuming, line 71 gates reuse. Only the first had a test, so dropping the second left the suite green. It is load-bearing. A cached entry can predate the bridge marker while the source file is untouched, so size and mtime still match and nothing else stops the scan serving a full-history projection for a file that is now parsed suffix-only. With a total-only record after the copy point the two readings diverge — baseline worth nothing against a delta worth three — and the reused entry reports 18 tokens where a cold scan reports 15. * fix(codex-usage): annotate the mid-scan seam instead of asserting it The changed-code quality gate rejects any non-const type assertion, and `onStreamOpen: { current: null as (...) | null }` is one, so `static analysis` failed on this PR. A typed local carries the same intent. * fix(usage): force an automation lookup onto a scan already in flight `shouldForceAutomationUsageScan` keyed on `max(lastScanStartedAt, lastScanCompletedAt)`, so a scan that started after the run completed but is still running counted as a finished attempt. The lookup then called `refresh(false)`, which returns early inside the 5-minute staleness window instead of joining the scan, and the run's usage read `unavailable`. Forcing instead just awaits the shared `scanPromise`. While a scan is in flight its start time is no longer treated as an attempt, so the once-per-run bound still holds: a failed scan leaves `lastScanStartedAt` past the run and stops re-forcing. The two providers' copies of the predicate were byte-identical, so it now lives in `src/main/usage/automation-usage-scan-forcing.ts`.
…lyai#21102) * perf(codex-usage): resume rollout scans at the last parsed byte Codex rollout files are append-only and grow all day, but any append changed both mtime and size, so `canReuse` discarded the cached entry and the scanner re-read the whole file from byte 0 on the Electron main process. On one real corpus that was 6.59 GB re-read per cycle across 26.63 GB / 21,110 files. Each parsed file now persists a resume point: the offset just past the last newline-terminated line, the parse context at that offset (session id, cwd, model, running totals), a sha256 of the 4 KiB before it, and the file's dev:ino. A grown file resumes there and merges the appended rollup into the cached one; anything unproven falls back to a full reparse — truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never depends on mtime equality, so a coarse-mtime filesystem cannot hide an append. Fixture: a 75,737-byte rollout with a 758-byte append re-read 76,495 bytes before and 8,950 after (the append plus two bounded 4 KiB boundary windows). Also bounds the automation-attribution force predicate for both Codex and Claude: it keyed on `lastScanError`, so a persistently failing scan forced a fresh full rescan on every single lookup. It now keys on the most recent scan attempt, which is one forced scan per run regardless of outcome. * fix(codex-usage): verify the head of a resumed rollout prefix The resume guard proved only the 4 KiB before the resume offset, and leaned on dev:ino to catch a rollout that was replaced at the same path. ext4 and overlayfs hand a recreated file the inode the old one freed, so on Linux that check passes and a same-length prefix swap resumes over changed history. Measured 20/20 inode reuse on ext4 and overlayfs, 0/20 on APFS and tmpfs -- which is why the case only failed in CI. An in-place prefix rewrite kept no inode change on any platform, so that variant was missed on macOS too. Digest a bounded window at the start of the parsed prefix as well. When the two windows meet, one read covers the whole prefix and leaves no gap. The head window is carried across a resume rather than re-read, so a resumed scan reads the appended bytes plus three 4 KiB windows. * test(codex-usage): cover the resume window layout switch * test(codex-usage): cover the boundary window in isolation * test(codex-usage): isolate the boundary window with disjoint windows * fix(codex-usage): restart a rollout parse when its verified prefix is gone The scanner verifies a rollout's prefix in its first pass and reads it in the second, so a truncation in between left the merged projection holding the whole pre-truncation history while `processedFile` was re-stat'd to the new, smaller size. Size and mtime then matched disk with no resume state left to reject, so the reuse path served the stale total on every later scan. The resume-state builder returns null only on a short read, which is exactly that signal; on it, drop the merge and reparse the file from zero. Also covers three guards that no test was holding: the unterminated-tail resume suppression (a tail that is valid JSON minus its newline is counted, so resuming over it double-counts), the short-read check in `readWindowDigest` (without it a resume point past EOF verifies against itself), and the legacy-suffix exclusion in the scanner's resume guard (bridge markers can appear on a file that already has a resume state). * fix(codex-usage): re-verify a rollout resume point at the point of use The scanner verified each resume point while walking the sessions directory, then parsed the files afterwards, so every file discovered or parsed in between widened the gap between the check and the read. A rollout replaced in that gap resumed at the old offset into unrelated bytes: the cached session id, cwd, model and running totals were stitched onto another file's records, and because the projection was then re-stat'd to the new size, the reuse path froze the corrupted numbers. A shrink was the visible half of this; a replacement larger than the recorded offset never short-reads and corrupts instead of going stale. Re-run the full check — inode, head window and boundary window — inside the parse, against the file about to be read. The short-read fallback added alongside it still covers the narrower case of a truncation landing after that check, during the read itself. Cost, measured on the existing byte oracle: a resumed file now reads `appended + 5 * 4096` rather than `appended + 3 * 4096`, paid only by files that changed since the last scan; untouched rollouts still read nothing. Two byte-total assertions that a 15 KB rollout can no longer satisfy now assert their intent directly — that the parse read did not reopen at byte 0 — via a stream oracle that records each read's offset. * test(codex-usage): pin mid-scan replacement on attribution, not totals The mid-scan replacement case was written with a heavier replacement so the token totals diverged, which overstated how visible the defect is. Rebuilt on the variant where the stale prefix contributes exactly as many events as the resumed read skips: daily aggregates and token totals then match a cold scan byte for byte, and the misattribution — 60 records of one session recorded against another — is the only remaining signal. Oracle is now the session shape. Removing the point-of-use re-verification fails it with `session-grower` in place of `session-other`; every totals-based assertion still passes under that mutation. * perf(codex-usage): stop resuming a rollout prefix too short to pay for it Point-of-use re-verification made a resumed scan cost five bounded windows, which is more than re-reading a small rollout outright. Measured against a cold reparse of the same file, resuming lost below a 12,288 B prefix and lost badly under 8 KiB, where the coalesced-window layout rehashed the whole prefix on each of the three verification passes. Set the floor at that break-even — 3 * 4096, the point where two verification passes plus the recorded boundary stop being cheaper than reading the prefix once — and refuse to record or accept a resume point below it. Measured: a 12,568 B prefix now reads 21,234 B resumed against 21,514 B cold, and a 76,484 B rollout reads 21,238 B against 84,676 B. No size band reads more than a cold scan any more; under the floor the windows are skipped entirely and a scan reads exactly the file. With every offset past the floor the two windows can no longer overlap, so the coalesced-layout branch and the empty-window branch are gone. The floor is also input validation: a persisted offset below it would put the boundary window at a negative start and throw ERR_OUT_OF_RANGE. Tests that meant to exercise the resume path were silently reparsing whole once the floor landed — the suite stayed green while three guards lost their only coverage. They now size their rollouts off RESUMABLE_RECORDS and assert the offsets their parse reads actually opened at, so a test that stops resuming fails instead of passing quietly. * test(codex-usage): cover the reuse gate's own legacy-bridge check `scanner.ts` carries the same `legacySourceSkipBytes === 0` term twice and they are different guards: line 83 gates resuming, line 71 gates reuse. Only the first had a test, so dropping the second left the suite green. It is load-bearing. A cached entry can predate the bridge marker while the source file is untouched, so size and mtime still match and nothing else stops the scan serving a full-history projection for a file that is now parsed suffix-only. With a total-only record after the copy point the two readings diverge — baseline worth nothing against a delta worth three — and the reused entry reports 18 tokens where a cold scan reports 15. * fix(codex-usage): annotate the mid-scan seam instead of asserting it The changed-code quality gate rejects any non-const type assertion, and `onStreamOpen: { current: null as (...) | null }` is one, so `static analysis` failed on this PR. A typed local carries the same intent. * fix(usage): force an automation lookup onto a scan already in flight `shouldForceAutomationUsageScan` keyed on `max(lastScanStartedAt, lastScanCompletedAt)`, so a scan that started after the run completed but is still running counted as a finished attempt. The lookup then called `refresh(false)`, which returns early inside the 5-minute staleness window instead of joining the scan, and the run's usage read `unavailable`. Forcing instead just awaits the shared `scanPromise`. While a scan is in flight its start time is no longer treated as an attempt, so the once-per-run bound still holds: a failed scan leaves `lastScanStartedAt` past the run and stops re-forcing. The two providers' copies of the predicate were byte-identical, so it now lives in `src/main/usage/automation-usage-scan-forcing.ts`.
…lyai#21102) * perf(codex-usage): resume rollout scans at the last parsed byte Codex rollout files are append-only and grow all day, but any append changed both mtime and size, so `canReuse` discarded the cached entry and the scanner re-read the whole file from byte 0 on the Electron main process. On one real corpus that was 6.59 GB re-read per cycle across 26.63 GB / 21,110 files. Each parsed file now persists a resume point: the offset just past the last newline-terminated line, the parse context at that offset (session id, cwd, model, running totals), a sha256 of the 4 KiB before it, and the file's dev:ino. A grown file resumes there and merges the appended rollup into the cached one; anything unproven falls back to a full reparse — truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never depends on mtime equality, so a coarse-mtime filesystem cannot hide an append. Fixture: a 75,737-byte rollout with a 758-byte append re-read 76,495 bytes before and 8,950 after (the append plus two bounded 4 KiB boundary windows). Also bounds the automation-attribution force predicate for both Codex and Claude: it keyed on `lastScanError`, so a persistently failing scan forced a fresh full rescan on every single lookup. It now keys on the most recent scan attempt, which is one forced scan per run regardless of outcome. * fix(codex-usage): verify the head of a resumed rollout prefix The resume guard proved only the 4 KiB before the resume offset, and leaned on dev:ino to catch a rollout that was replaced at the same path. ext4 and overlayfs hand a recreated file the inode the old one freed, so on Linux that check passes and a same-length prefix swap resumes over changed history. Measured 20/20 inode reuse on ext4 and overlayfs, 0/20 on APFS and tmpfs -- which is why the case only failed in CI. An in-place prefix rewrite kept no inode change on any platform, so that variant was missed on macOS too. Digest a bounded window at the start of the parsed prefix as well. When the two windows meet, one read covers the whole prefix and leaves no gap. The head window is carried across a resume rather than re-read, so a resumed scan reads the appended bytes plus three 4 KiB windows. * test(codex-usage): cover the resume window layout switch * test(codex-usage): cover the boundary window in isolation * test(codex-usage): isolate the boundary window with disjoint windows * fix(codex-usage): restart a rollout parse when its verified prefix is gone The scanner verifies a rollout's prefix in its first pass and reads it in the second, so a truncation in between left the merged projection holding the whole pre-truncation history while `processedFile` was re-stat'd to the new, smaller size. Size and mtime then matched disk with no resume state left to reject, so the reuse path served the stale total on every later scan. The resume-state builder returns null only on a short read, which is exactly that signal; on it, drop the merge and reparse the file from zero. Also covers three guards that no test was holding: the unterminated-tail resume suppression (a tail that is valid JSON minus its newline is counted, so resuming over it double-counts), the short-read check in `readWindowDigest` (without it a resume point past EOF verifies against itself), and the legacy-suffix exclusion in the scanner's resume guard (bridge markers can appear on a file that already has a resume state). * fix(codex-usage): re-verify a rollout resume point at the point of use The scanner verified each resume point while walking the sessions directory, then parsed the files afterwards, so every file discovered or parsed in between widened the gap between the check and the read. A rollout replaced in that gap resumed at the old offset into unrelated bytes: the cached session id, cwd, model and running totals were stitched onto another file's records, and because the projection was then re-stat'd to the new size, the reuse path froze the corrupted numbers. A shrink was the visible half of this; a replacement larger than the recorded offset never short-reads and corrupts instead of going stale. Re-run the full check — inode, head window and boundary window — inside the parse, against the file about to be read. The short-read fallback added alongside it still covers the narrower case of a truncation landing after that check, during the read itself. Cost, measured on the existing byte oracle: a resumed file now reads `appended + 5 * 4096` rather than `appended + 3 * 4096`, paid only by files that changed since the last scan; untouched rollouts still read nothing. Two byte-total assertions that a 15 KB rollout can no longer satisfy now assert their intent directly — that the parse read did not reopen at byte 0 — via a stream oracle that records each read's offset. * test(codex-usage): pin mid-scan replacement on attribution, not totals The mid-scan replacement case was written with a heavier replacement so the token totals diverged, which overstated how visible the defect is. Rebuilt on the variant where the stale prefix contributes exactly as many events as the resumed read skips: daily aggregates and token totals then match a cold scan byte for byte, and the misattribution — 60 records of one session recorded against another — is the only remaining signal. Oracle is now the session shape. Removing the point-of-use re-verification fails it with `session-grower` in place of `session-other`; every totals-based assertion still passes under that mutation. * perf(codex-usage): stop resuming a rollout prefix too short to pay for it Point-of-use re-verification made a resumed scan cost five bounded windows, which is more than re-reading a small rollout outright. Measured against a cold reparse of the same file, resuming lost below a 12,288 B prefix and lost badly under 8 KiB, where the coalesced-window layout rehashed the whole prefix on each of the three verification passes. Set the floor at that break-even — 3 * 4096, the point where two verification passes plus the recorded boundary stop being cheaper than reading the prefix once — and refuse to record or accept a resume point below it. Measured: a 12,568 B prefix now reads 21,234 B resumed against 21,514 B cold, and a 76,484 B rollout reads 21,238 B against 84,676 B. No size band reads more than a cold scan any more; under the floor the windows are skipped entirely and a scan reads exactly the file. With every offset past the floor the two windows can no longer overlap, so the coalesced-layout branch and the empty-window branch are gone. The floor is also input validation: a persisted offset below it would put the boundary window at a negative start and throw ERR_OUT_OF_RANGE. Tests that meant to exercise the resume path were silently reparsing whole once the floor landed — the suite stayed green while three guards lost their only coverage. They now size their rollouts off RESUMABLE_RECORDS and assert the offsets their parse reads actually opened at, so a test that stops resuming fails instead of passing quietly. * test(codex-usage): cover the reuse gate's own legacy-bridge check `scanner.ts` carries the same `legacySourceSkipBytes === 0` term twice and they are different guards: line 83 gates resuming, line 71 gates reuse. Only the first had a test, so dropping the second left the suite green. It is load-bearing. A cached entry can predate the bridge marker while the source file is untouched, so size and mtime still match and nothing else stops the scan serving a full-history projection for a file that is now parsed suffix-only. With a total-only record after the copy point the two readings diverge — baseline worth nothing against a delta worth three — and the reused entry reports 18 tokens where a cold scan reports 15. * fix(codex-usage): annotate the mid-scan seam instead of asserting it The changed-code quality gate rejects any non-const type assertion, and `onStreamOpen: { current: null as (...) | null }` is one, so `static analysis` failed on this PR. A typed local carries the same intent. * fix(usage): force an automation lookup onto a scan already in flight `shouldForceAutomationUsageScan` keyed on `max(lastScanStartedAt, lastScanCompletedAt)`, so a scan that started after the run completed but is still running counted as a finished attempt. The lookup then called `refresh(false)`, which returns early inside the 5-minute staleness window instead of joining the scan, and the run's usage read `unavailable`. Forcing instead just awaits the shared `scanPromise`. While a scan is in flight its start time is no longer treated as an attempt, so the once-per-run bound still holds: a failed scan leaves `lastScanStartedAt` past the run and stops re-forcing. The two providers' copies of the predicate were byte-identical, so it now lives in `src/main/usage/automation-usage-scan-forcing.ts`.

Problem
Codex rollout files are append-only and grow all day. Any append changes both
mtimeandsize, so the scanner'scanReusecheck discarded the cached entry and re-read the entire file from byte 0 on the Electron main process.On the corpus from the Slack report — 26.63 GB across 21,110 files — that was 6.59 GB re-read per scan cycle, with an ~18 minute scan. This is the main-process work behind the "app is unusable" reports.
Fix
Each parsed file now persists a resume point:
dev:ino.A grown file resumes there and merges the appended rollup into the cached projection.
Everything unproven falls back to a full reparse: truncation, an in-place rewrite, rotation, a counted tail with no trailing newline, a legacy copied-session suffix offset, or a file that must reclaim deferred fork claims. Resume never consults
mtime,ctimeorbirthtime: filesystem clock granularity varies, so no timestamp can separate an append from a same-tick rewrite.dev:inois kept only as a cheap extra catch, not as a rotation check — see Known limits.readlinewas replaced with a byte-accurate JSONL reader (src/main/usage/jsonl-line-offsets.ts) becausereadlinehides how many bytes a line consumed — a CRLF transcript would drift one byte per line.No cache schema bump. An old cache simply lacks
parseResumeState, which reads as "full reparse" and heals on the next scan. Bumping would have forced every user through one full 18-minute scan.Measurement
The oracle is a
createReadStreamwrapper recording(path, start, end)per call and tallying bytes — no wall-clock, so it is machine-insensitive and CI-gateable.A resumed file costs
appended + 5 × 4096: two verification passes (head + boundary — once at discovery to gate ownership seeding, once at the point of use to gate the merge) plus the boundary window that records the moved offset. Untouched files still read 0 bytes.Resume is skipped below a 12,288-byte prefix. That is the break-even, derived rather than rounded: a resumed scan pays a constant 20,480 bytes, a cold reparse pays
prefix + appended + 8192, and they are equal at 12,288. Before this floor a 7,667-byte prefix read 46% more resumed than cold, because the coalesced-window layout rehashed the entire prefix on every verification pass. With the floor no size band loses, and a small changed rollout now reads exactly its own bytes — better than the pre-PR baseline for that band. The window-coalescing branch is deleted as unreachable.The fixed cost is ~12 KiB per changed file, so the saving is thin for small rollouts — the 15 KB fixture above saves only 2,179 bytes. It is negligible against the ~1.26 MB average file in the reported 26.63 GB corpus, which is what this PR targets.
Both "after" figures are measured, but note the tests assert bounds (
≤ appended + 3×4096), not these exact values. The file sizes are also machine-specific: the fixture embeds its ownmkdtemppath in the log, which is shorter on Linux, so the same fixture is ~44 bytes smaller on CI. Appended counts and after-counts are path-independent.Also: bounded automation-attribution forcing
codex-automation-run-attribution.tsandclaude-usage-automation-attribution.tskeyed the force-rescan predicate onlastScanError. SincelastScanCompletedAtis not updated on failure, a persistently failing scanner forced a fresh full rescan on every lookup, forever. It now keys on the most recent scan attempt (lastScanStartedAt, which is written on every attempt regardless of outcome), bounding it to one forced scan per run.The trade: a run whose forced scan fails is now not retried —
resolveAutomationRunUsagereturnsunavailableReason: 'scan_failed'and that run's usage stays missing until an ordinary staleness-driven scan (>5 min,STALE_MSinusage-provider-store-lifecycle.ts) succeeds on its own. Both new store tests assert exactly this. That is the deliberate cost of bounding the unbounded path.The once-per-run force is deliberately kept — attribution genuinely needs data covering the run, and that scan is now cheap.
A scan already in flight does not count as an attempt. Keying purely on
max(lastScanStartedAt, lastScanCompletedAt)regressed the case where a scan starts after the run completes and is still running when the lookup arrives: the predicate saw a finished attempt, calledrefresh(false), and that returns early inside the 5-minute staleness window instead of joining the scan — so the run reportedunavailablewhere pre-PR it forced and joined. The predicate now ignores the in-flight scan's start time (isScanning, already published bygetScanState()and threaded in as one dep per store), so the lookup forces;UsageProviderStoreLifecycle.runScanthen simply awaits the sharedscanPromiserather than starting a second scan. The once-per-run bound is unchanged, because a scan that finished — successfully or not — leaveslastScanStartedAtpast the run and stops re-forcing.The two providers' copies of this predicate were byte-identical, so it now lives once in
src/main/usage/automation-usage-scan-forcing.ts. One new store test per provider (store-automation-usage.test.ts,claude-usage/store.test.ts) drives a real in-flight scan through the lifecycle and asserts the run resolvesknown; both fail with the pre-fix predicate.Correction: the replacement guard did not work
The first revision relied on
dev:inoto catch a file deleted and replaced. CI caught it, and the investigation found a bigger hole than the failing test implied.Inode reuse, measured over 20 delete-and-recreate iterations: 20/20 on ext4, 20/20 on overlayfs, 0/20 on tmpfs, 0/20 on macOS APFS. ext4 and overlayfs hand back the freed inode every time; APFS and tmpfs allocate monotonically. That is the macOS-passes / Linux-fails split exactly.
It was never Linux-only. Driving
resolveCodexRolloutResumewith an in-place prefix rewrite — no delete, so no inode change, tail identical by construction — was missed on every platform including macOS; 5 of 8 cases silently resumed over changed history. The test'srmSyncis the only reason macOS ever passed: it was passing for the wrong reason and never exercised the digest path.Fix: a second 4 KiB digest at the start of the parsed prefix.
Signals rejected:
ctimechanges on append too, so it cannot tell an append from a rewrite.birthtimeis stable across appends and real on ext4/overlayfs/tmpfs, but it is clock-granularity-blind (back-to-back rotation showed identical values) and NTFS file-system tunneling preserves creation time for a delete+recreate within 15s — a guard that only fires when a clock tick elapsed cannot be tested or relied on. Widening the boundary window moves the blind spot rather than removing it.Known limits
dev:inois not a rotation check. ext4 and overlayfs hand a recreated path the inode the old file just freed: measured 20/20 reuse on both, against 0/20 on APFS and tmpfs. So on Linux a delete-and-replace keeps the samedev:inoand this check does nothing; it is retained only as a free extra catch on filesystems that do allocate a fresh inode. The head window is what actually catches rotation. This gap is what madetest / tests node 24 2/8fail on ubuntu while passing on macOS, and the in-place variant of the same rewrite was missed on every platform, macOS included.(size, mtime)equality rule. Strengthening it would add a read to all ~21k unchanged files, and its blind spot is pre-existing.JSON.stringifycache write. Real, unmeasured, and belongs with the separate cache-write ticket.Verification
pnpm tc→ exit 0pnpm run check:code-quality:changed→ 0 findings, 13 files. No type assertions and nomax-linesdisables added.pnpm run audit:anti-slop→ exit 0src/main/codex-usage/+src/main/claude-usage/+src/main/usage/→ 18 files, 123 tests passingMutation checks re-run independently of the authoring agent (not self-graded):
One over-claim found while checking: the author listed "rewritten rollout also grows" as killed by dropping the digest check; it survives that mutation. Other two tests in that group do kill it.
Mutation checks for the head window (applied, run, restored — each on the full
src/main/codex-usage/suite, 57 tests):resolvestops comparingheadDigestresolvestops comparingboundaryDigestreadWindowDigestLinux reproduction (the macOS/Linux split is the whole point, so it was verified on Linux, not inferred):
resolveCodexRolloutResumewas driven directly on each filesystem. Before: 5 of 8 rewrite cases silently resumed. After: 8 of 8 fall back.os.tmpdir()bind-mounted onto it) in anode:24-bookwormcontainer: 17/17 pass with the fix; against the pre-fix production code the two prefix-swap tests fail there, with the sameinputTokens: 40vs80symptom as CI. On macOS the same pre-fix code fails only the in-place test — APFS allocates a fresh inode, which is exactly why CI caught what local runs did not.