Skip to content

perf(codex-usage): resume rollout scans at the last parsed byte - #21102

Merged
Jinwoo-H merged 13 commits into
mainfrom
perf/codex-usage-incremental-rollout-scan
Sep 17, 2026
Merged

Jinwoo-H merged 13 commits into
mainfrom
perf/codex-usage-incremental-rollout-scan

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1332 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1332
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​529 $\color{#cf222e}{\Huge{\mathbf{−}}}$​111 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​418

Problem

Codex rollout files are append-only and grow all day. Any append changes both mtime and size, so the scanner's canReuse check 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:

  • the byte offset just past the last newline-terminated line,
  • the parse context at that offset (session id, cwd, model, running totals),
  • a sha256 of a 4 KiB window at the start of the parsed prefix, and one of the 4 KiB immediately before the offset (a single window, hashed once, when the prefix is small enough that the two meet),
  • the file's 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, ctime or birthtime: filesystem clock granularity varies, so no timestamp can separate an append from a same-tick rewrite. dev:ino is kept only as a cheap extra catch, not as a rotation check — see Known limits.

readline was replaced with a byte-accurate JSONL reader (src/main/usage/jsonl-line-offsets.ts) because readline hides 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 createReadStream wrapper recording (path, start, end) per call and tallying bytes — no wall-clock, so it is machine-insensitive and CI-gateable.

fixture file size appended bytes re-read on 2nd scan (before) after
76,484 B rollout + 2 records 76,484 758 84,676 21,238
rollout with prefix under 12,288 B 9,175 — 9,929 9,929 (resume skipped)
untouched rollout — 0 0 0

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 own mkdtemp path 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.ts and claude-usage-automation-attribution.ts keyed the force-rescan predicate on lastScanError. Since lastScanCompletedAt is 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 — resolveAutomationRunUsage returns unavailableReason: 'scan_failed' and that run's usage stays missing until an ordinary staleness-driven scan (>5 min, STALE_MS in usage-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, called refresh(false), and that returns early inside the 5-minute staleness window instead of joining the scan — so the run reported unavailable where pre-PR it forced and joined. The predicate now ignores the in-flight scan's start time (isScanning, already published by getScanState() and threaded in as one dep per store), so the lookup forces; UsageProviderStoreLifecycle.runScan then simply awaits the shared scanPromise rather than starting a second scan. The once-per-run bound is unchanged, because a scan that finished — successfully or not — leaves lastScanStartedAt past 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 resolves known; both fail with the pre-fix predicate.

Correction: the replacement guard did not work

The first revision relied on dev:ino to 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 resolveCodexRolloutResume with 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's rmSync is 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: ctime changes on append too, so it cannot tell an append from a rewrite. birthtime is 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

  • What the two windows do and do not detect. Any change touching either hashed window forces a full reparse. When the parsed prefix is 8 KiB or smaller the windows meet, so the whole prefix is verified and there is no gap at all. Above that, a rewrite that keeps the file's length identical, leaves both windows byte-identical, and changes only bytes between them is not detected. That is inherent to a bounded guard — proving an N-byte prefix intact cannot be done in O(1) reads — and append-only JSONL does not produce that shape. Stating it rather than claiming coverage.
  • dev:ino is 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 same dev:ino and 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 made test / tests node 24 2/8 fail on ubuntu while passing on macOS, and the in-place variant of the same rewrite was missed on every platform, macOS included.
  • The zero-read reuse path keeps the existing (size, mtime) equality rule. Strengthening it would add a read to all ~21k unchanged files, and its blind spot is pre-existing.
  • The resume state adds ~300-550 bytes/file (order of 10 MB on a 21k-file corpus, estimated from the record shape, not measured) to the JSON.stringify cache write. Real, unmeasured, and belongs with the separate cache-write ticket.
  • The Claude scanner is not made incremental here — only its attribution predicate. It reads through a different path and is a separate change.
  • Numbers above are the synthetic fixture only. No run against the real 26.63 GB corpus.

Verification

  • pnpm tc → exit 0
  • pnpm run check:code-quality:changed → 0 findings, 13 files. No type assertions and no max-lines disables added.
  • pnpm run audit:anti-slop → exit 0
  • src/main/codex-usage/ + src/main/claude-usage/ + src/main/usage/ → 18 files, 123 tests passing

Mutation checks re-run independently of the authoring agent (not self-graded):

mutation result
resume disabled entirely kills both incremental-append tests
boundary digest check dropped kills the truncation and same-size-rewrite tests
offset advanced past an unterminated line kills the partial-tail double-count test

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):

mutation result
resolve stops comparing headDigest kills prefix rewritten in place
resolve stops comparing boundaryDigest kills records before the offset changed
head window read from the boundary instead of offset 0 kills prefix rewritten in place
carry-forward drops its window-size guard kills prefix outgrows the head window
window coalescing never taken survives — equivalent mutant: for a prefix ≤ 8 KiB the two windows already overlap, so coalescing only saves a read, it does not change any verdict
short-read check dropped from readWindowDigest survives — equivalent mutant: the digest encodes the requested byte count, so a truncated file mismatches on the next comparison regardless. Pre-existing code, unchanged here

Linux reproduction (the macOS/Linux split is the whole point, so it was verified on Linux, not inferred):

  • Inode reuse measured with a 20-iteration delete-and-recreate probe: ext4 20/20, overlayfs 20/20, tmpfs 0/20, APFS 0/20.
  • The real resolveCodexRolloutResume was driven directly on each filesystem. Before: 5 of 8 rewrite cases silently resumed. After: 8 of 8 fall back.
  • The vitest file itself was run on a real ext4 loopback mount (with os.tmpdir() bind-mounted onto it) in a node:24-bookworm container: 17/17 pass with the fix; against the pre-fix production code the two prefix-swap tests fail there, with the same inputTokens: 40 vs 80 symptom 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.

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.
@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: fa6945e9-af3b-49b3-b913-66623a5ed357

📥 Commits

Reviewing files that changed from the base of the PR and between 434ed08 and 1aedef8.

📒 Files selected for processing (5)
  • src/main/codex-usage/codex-rollout-file-parse.ts
  • src/main/codex-usage/codex-rollout-resume-state.test.ts
  • src/main/codex-usage/codex-rollout-resume-state.ts
  • src/main/codex-usage/scanner-incremental-append.test.ts
  • src/main/codex-usage/scanner-paths.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/codex-usage/codex-rollout-file-parse.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The 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 1aede

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.21% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 33 functions across 14 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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… Add the required template sections or clearly map existing content to them. Include a valid issue reference under Linked Issue using Fixes #..., write N/A with a reason under Visual Proof, and complete the Testing, AI Disclosure, Review…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: resuming Codex rollout scans from the last parsed byte.
Full details: Description check

Explanation

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 Fixes #..., write N/A with a reason under Visual Proof, and complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections as applicable.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 44f65060-34c9-4fce-bdb6-b9de017b5162

📥 Commits

Reviewing files that changed from the base of the PR and between 9add08b and 5843552.

📒 Files selected for processing (13)
  • src/main/claude-usage/claude-usage-automation-attribution.ts
  • src/main/claude-usage/store.test.ts
  • src/main/codex-usage/codex-automation-run-attribution.ts
  • src/main/codex-usage/codex-rollout-file-parse.ts
  • src/main/codex-usage/codex-rollout-resume-state.ts
  • src/main/codex-usage/codex-usage-aggregation.ts
  • src/main/codex-usage/scanner-incremental-append.test.ts
  • src/main/codex-usage/scanner-paths.test.ts
  • src/main/codex-usage/scanner.ts
  • src/main/codex-usage/store-automation-usage.test.ts
  • src/main/codex-usage/types.ts
  • src/main/usage/jsonl-line-offsets.test.ts
  • src/main/usage/jsonl-line-offsets.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ One correctness gap in the new resume path — details inline. Everything else reads clean.

Reviewed changes

  • Per-file resume point — CodexUsageParseResumeState now persists the offset past the last newline-terminated line, a sha256 of the 4 KiB before it, dev:ino, and the parser context; resolveCodexRolloutResume fails closed on a short read, a digest mismatch, or a changed physical id, and deliberately ignores mtime.
  • Byte-accurate JSONL reader — src/main/usage/jsonl-line-offsets.ts replaces readline (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/getProcessedFileInfo moved into codex-rollout-file-parse.ts and the aggregation into codex-usage-aggregation.ts; the scanner seeds cross-file event ownership from reused and resumed files, in files order.
  • Attribution forcing bounded — Codex and Claude now force at most one scan attempt per run, keyed on Math.max(lastScanStartedAt, lastScanCompletedAt) instead of the sticky lastScanError; lastScanStartedAt is 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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) — CodexUsageParseResumeState gains a second digest, headDigest over [0, 4096), and resolveCodexRolloutResume now requires both headDigest and boundaryDigest to match. A same-length rewrite that changes the leading records but leaves the tail and inode intact — missed on every platform before, since physicalFileId cannot catch an in-place rewrite — now falls back to a full reparse. isUsableResumeState rejects states persisted before the field existed.
  • Carried head digest — readPrefixDigests accepts a carriedHeadDigest and skips re-reading the head window when it already starts with 4096:. This is only safe because a 4096: digest is produced over exactly [0, 4096) (the parsedBytes === 4096 coalesced case is the same range), the layout is a pure function of parsedBytes, 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. resolve never trusts the carry, so a head that changed after the read is caught by the next scan.
  • Window coalescing — when parsedBytes <= 8192 the 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — parseCodexUsageFile now recurses into a full reparse when buildCodexRolloutResumeState returns null (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) that canReuse then serves forever (codex-rollout-file-parse.ts:135-154).
  • Resume-state unit tests — new codex-rollout-resume-state.test.ts pins the short-read refusal (whole-prefix and disjoint-boundary layouts) and resolveCodexRolloutResume's truncation-vs-growth verdicts.
  • Mid-scan mutation seam + scanner test — scanner-incremental-append.test.ts gains an onStreamOpen hook 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.ts adds a test that a source which gains bridge markers after being resumed reparses in full rather than resuming over the copied prefix.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Point-of-use resume re-verification — parseCodexUsageFile now re-runs resolveCodexRolloutResume against the file about to be read, before getProcessedFileInfo, 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 createReadStream mock now records start/bounded, and reparsedFromStart asserts 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 7f2a2afd-d9f2-42cb-852f-0c2fdad143a2

📥 Commits

Reviewing files that changed from the base of the PR and between 05245df and 434ed08.

📒 Files selected for processing (2)
  • src/main/codex-usage/codex-rollout-file-parse.ts
  • src/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Resumable-prefix floor — codex-rollout-resume-state.ts now defines MIN_RESUMABLE_PREFIX_BYTES = 3 × 4096 and isResumablePrefixLength. buildCodexRolloutResumeState refuses to record at or below the floor before it reads anything, and isUsableResumeState rejects 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 always 4096:-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.ts documents why, with a resume plan present, the builder's only remaining null is a short read: startOffset is a validated state's parsedBytes (already past the floor) and parsedBytes only advances. I checked every production caller of buildCodexRolloutResumeState/resolveCodexRolloutResume and 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 via parseReadOffsets, 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Reuse-gate legacy-bridge test — scanner-paths.test.ts adds 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), so scanner.ts's reuse-side legacySourceSkipBytes === 0 term 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 stated 18 vs 15 failure. The other 18 cases in the file still pass.

Pullfrog  | View workflow run | Using 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`.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Shared scan-forcing predicate — the byte-identical Codex and Claude copies of shouldForceAutomationUsageScan were extracted into src/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 on lastScanCompletedAt. A lookup for a run that finished before that scan started now forces and joins the shared scanPromise, instead of taking refresh(false)'s staleness early-return and reading a pre-run cache. The one-force-per-run bound is unchanged; runScan awaits the existing promise rather than starting a second scan.
  • Coverage for the fix — one test per provider drives a real in-flight scan through UsageProviderStoreLifecycle and asserts the run resolves known; each fails with the pre-fix predicate. store-test-harness.ts gains createWorktreeUsageSession to share the fixture.
  • Merge adaptation — main's UsageWorktreeResolver refactor is carried through parseCodexUsageFile/scanner.ts with no behavioral change.

Both store suites pass (20 tests). All four prior Pullfrog threads remain resolved.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit f36a7ce into main Sep 17, 2026
28 checks passed
@Jinwoo-H
Jinwoo-H deleted the perf/codex-usage-incremental-rollout-scan branch September 17, 2026 02:46
github-actions Bot pushed a commit to MAYFCHOI/orca that referenced this pull request Sep 17, 2026
…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`.
Him188 pushed a commit to Him188/orca that referenced this pull request Sep 18, 2026
…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`.
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…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`.
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.

1 participant