You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(usage): reparse a grown transcript after atomic file replacement - #46581
When a transcript that was already scanned is replaced by a larger file (written elsewhere and renamed over the path, as rsync and sync tools do), Usage can keep stale token counts. UsageService resumes any file that grew. readTranscriptRecords checks only the 64 bytes before the saved offset, and those bytes can match while earlier records differ. The resumed parse is then appended to the cached records from the old file (UsageService.ts, dedupeWithinFile([...cached.records, ...parsed.records])), and the stale counts stay in the warm and persisted cache. Claude dedupe keys are messageId:requestId, so the old a (5), the old b (7) and the new c (13) are three distinct keys. They survive dedupeWithinFile and the aggregator's key check, and the aggregator adds their output tokens to the buckets returned by server.getUsageSummary for any window that covers their timestamps: 25 on base, 29 on head.
Deterministic repro on origin/main (42f4bcf63fdf): write two newline-terminated Claude assistant records, a with 5 output tokens and b with 7 output tokens and 100 bytes of padding. Scan the file and keep position. Write a separate file with a changed to 9, b unchanged byte-for-byte, and a new record c with 13 tokens. fs.rename it over the original path and call readTranscriptRecords(path, claudeUsageFormat, position).
Observed: resumed=true and the reader returns only [13], so the warm total is 5+7+13 = 25. A cold scan of the same file returns [9,7,13] = 29.
Expected: the old position is rejected and the whole file is reread. Warm and cold totals are both 29.
Change
Each parse position now stores the opened file's dev:ino, read with stat({ bigint: true }) so 64-bit NTFS file IDs are not rounded. Resume requires that ID to match before the existing guard-bytes check runs. The scan cache saves the ID as an optional fi field. Entries saved before this change have no ID, so a grown file reparses once in full. No cache version bump is needed, and an older server ignores the field. The fix is in the server's shared usage scan, so web, desktop, and mobile Usage views all get the corrected totals.
Scope
Small fix for an obvious bug; no issue needed under CONTRIBUTING.md.
Verification
New usageTranscriptReader.test.ts case "re-parses a grown replacement file even when its guard bytes match": on base it fails with AssertionError: expected true to be false at assert.isFalse(second.resumed). On head it passes and returns [9, 7, 13].
usageScanCache.test.ts round trip now includes a fileId, which shows the ID survives save and load.
vp run check:changed exit 0 on head 91908d7d5dc9 (format, lint, knip, typecheck, tests in the 3 affected files). The log is check-changed-91908d7.md in the same gist.
Not shown: a captured server.getUsageSummary RPC run or scenarios:prove scenario against isolated T3 state (the path to the RPC is traced in Problem above). Not run on Windows (the bigint read keeps NTFS file IDs exact) or on filesystems that report ino 0. On those, the ID check passes and the existing guard check still applies.
Authored by Claude Opus 5.5 (Model Hub); reviewed by GPT-6.2 Sol (Codex).
Not shown
apps/server/src/usage/usageTranscriptReader.test.ts:520 — The reader regression and source trace establish reachability, but the evidence does not run a warmed server through the replacement. For scenarios:prove, use an isolated Claude projects directory, make a non-provisional Usage RPC call to warm the cache, rename the larger fixture over the JSONL, and assert that the next non-provisional response reports 29 output tokens rather than 25. The draft already discloses this gap.
Macroscope's review found this PR approvable — Transcript scans now verify file identity before resuming, reparsing files replaced atomically rather than retaining stale usage records. The change is limited to derived cache handling and leaves source transcripts unchanged.
No code changes detected at 18546c4. Prior analysis still applies.
You can add or adjust custom eligibility rules. Learn more.
Reviewing files that changed from the base of the PR and between fa3d5e5 and 18546c4.
You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.
Use the checkbox below for a quick retry:
Trigger review
No actionable comments were generated in the recent review.
Walkthrough
Transcript resumption now requires the saved file identity to match the opened file. The scan cache stores and restores that identity so it is available in resumed parse positions.
Changes: Transcript Resume Identity
Layer / File(s)
Summary
Check identity before resuming apps/server/src/usage/usageTranscriptReader.ts, apps/server/src/usage/usageTranscriptReader.test.ts
Parse positions include the opened file’s identity. The reader checks it before resuming. A test verifies that replacing a transcript with a longer file that preserves the guard bytes causes all replacement records to be parsed.
Persist identity in the scan cache apps/server/src/usage/usageScanCache.ts, apps/server/src/usage/usageScanCache.test.ts
The cache writes the optional file identity as fi and restores it when fi is a string. The Grok fixture includes a file identity.
This change fixes stale usage totals after a transcript file is replaced by a larger one. It is low risk, and older cache entries simply trigger one full reparse. No blocking issues remain.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title "fix(usage): reparse a grown transcript after atomic file replacement" matches the main change. The PR adds a device-and-inode file ID to parse positions so a replaced file is reparsed inste…
Description check
The description follows the template. It has Problem, Change, Scope, and Verification sections, and each is filled in with specific content. The Problem section gives reproduction steps and expected a…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title "fix(usage): reparse a grown transcript after atomic file replacement" matches the main change. The PR adds a device-and-inode file ID to parse positions so a replaced file is reparsed instead of resumed from the saved offset. The title is specific, follows conventional commit style, and names the affected area (usage).
Full details: Description check
Explanation
The description follows the template. It has Problem, Change, Scope, and Verification sections, and each is filled in with specific content. The Problem section gives reproduction steps and expected and observed behavior. The Change section explains the dev:ino ID, the resume check, and the optional fi cache field. The Scope section explains why no issue is needed. The Verification section lists the failing-then-passing test, the round-trip test, a runnable repro with observed totals, and the check run. It also states what was not verified: the RPC path, Windows, and filesystems that report ino 0. The template's agent attribution line is present. The description is complete, so it passes.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Environment: Linux, real web client and server, Chromium at 1280×800, light theme, fresh synthetic state on each commit.
On fresh isolated app state for each commit: seed a demo project and two newline-terminated Claude assistant records dated 2026-12-01, with 10 input tokens each and outputs 5 and 7; trailing text keeps the 64-byte guard inside unchanged record b. Open Usage > Tokens > 30 days and wait for output 12. Write a separate replacement with outputs 9, 7, and 13, keeping b byte-for-byte unchanged, then rename it over the original. Click Refresh usage. Base shows processed 55 / input 30 / output 25; head shows processed 59 / input 30 / output 29.
Scenario: Usage reparses a grown transcript after atomic replacement
…Wave 1B)
Ported 92 clean, non-locked, non-redline upstream commits from 772e3d4..1e6e7d7
with automated i18n catalog sync (vp run sync:t4-i18n --ref 1e6e7d7),
shared-tooltip alignment (pingdotgg#47040), and macOS realpath compatibility in UsageService.test.ts (pingdotgg#46543).
Upstream commits:
- 46a13b9 fix(web): reload workflow definitions after undoing all edits (pingdotgg#46471)
- 6cb0e70 fix(web): pressing Escape to dismiss Cite no longer closes Find in Thread (pingdotgg#46482)
- 97811c9 fix(bitbucket): reviewer lookup finds members past the first page of 50 (pingdotgg#46223)
- 9183596 fix(gitlab): preserve mode changes in reconstructed merge request patches (pingdotgg#46495)
- b16c455 fix(shared): first threads stay local in POSIX project paths with backslashes (pingdotgg#46496)
- f5b0d08 fix(web): keep Workflows open when a pane link has a blank ID (pingdotgg#46494)
- 2c5bbcd fix(shared): reject a comma as the only JSON array or object entry (pingdotgg#46501)
- d0e786c fix(source-control): fetched inline comments keep filenames with leading or trailing spaces (pingdotgg#46500)
- 8dd95ca fix(web): skip JPEG fill bytes and standalone markers when detecting Display P3 (pingdotgg#46507)
- a4ae535 fix(server): reload keybindings when the file is a symlink and its target is edited (pingdotgg#46521)
- 9790b79 fix(server): storage cleanup removes task-folder checkouts whose branch changed (pingdotgg#46527)
- 8983bb4 fix(web): pressing Escape to close Find in Thread keeps the citation highlight (pingdotgg#46522)
- adf6562 fix(ssh): disconnect no longer waits on a stopped server left as a zombie (pingdotgg#46533)
- 4230a15 fix(usage): skip non-regular transcript files during usage scans (pingdotgg#46543)
- 9eba01e fix(web): issue rows show the hand cursor on hover, like pull request rows (pingdotgg#46553)
- ae9bc1b fix(server): imported thread titles no longer end in half a flag or joined emoji (pingdotgg#46558)
- 8adc39c fix(server): parse webhook JSON by media type rather than a parameter substring (pingdotgg#46567)
- 3abbeba fix(source-control): route nested GitLab merge requests before GitHub prefix matches (pingdotgg#46560)
- cb92d66 fix(server): do not schedule a fixed-time task twice during fall-back (pingdotgg#46564)
- 4861433 fix(contracts): accept webhook dedupe placeholders for query keys containing spaces (pingdotgg#46569)
- 7b0d949 fix(usage): reparse a grown transcript after atomic file replacement (pingdotgg#46581)
- 48440ca fix(server): preserve the pending run when saving a legacy one-minute interval (pingdotgg#46583)
- 60c4a83 fix(web): holding the settle or pin shortcut no longer toggles it back (pingdotgg#46602)
- ec97f79 fix(server): large voice model downloads resume after connection drops (pingdotgg#46611)
- c246a87 fix(server): distinguish literal brackets from webhook filter wildcards (pingdotgg#46606)
- 85471b3 fix(server): preserve a leading question mark in webhook parameter names (pingdotgg#46598)
- 0d0c744 fix(source-control): preserve mixed line endings when removing merge credits (pingdotgg#46620)
- 81ddaaa fix(contracts): keep preview annotations from pages with long URLs (pingdotgg#46612)
- eec16a0 fix(web): text generation settings skip providers turned off for the project (pingdotgg#46632)
- 14b32cc fix(web): clear unsaved workflow status after undo (pingdotgg#46636)
- 3ed86fd fix(source-control): preserve merge-message code fences with Unicode line separators in their info strings (pingdotgg#46649)
- 9c5fc72 fix(mobile): render inline base64 SVGs with URL fragments (pingdotgg#46658)
- 9485d30 fix(acp): disconnect sessions opened by an in-flight MCP initialize (pingdotgg#46652)
- a2fc74d fix(dev): restart the server when a populated source directory is moved into place (pingdotgg#46670)
- eca5cb0 fix(opencode): republish models when a catalog change only affects legacy flags (pingdotgg#46677)
- 72d1b52 fix(web): do not throttle Changes revalidation after a skipped read (pingdotgg#46685)
- 2e42465 fix(web): keep preview annotations from pages with very long titles (pingdotgg#46678)
- 6c0cd0b fix(shared): keep backticks literal in sent file mention labels (pingdotgg#46706)
- fafe64b fix(web): ignore insight openers inside Markdown comments (pingdotgg#46710)
- ed721f7 fix(web): terminal excerpts number the rows that hold the selected text (pingdotgg#46703)
- af4760c fix(server): remove retained partial voice downloads when deleting a model (pingdotgg#46715)
- ec128fa fix(server): fall back to JS realpath when Windows native realpath fails on FUSE drives (pingdotgg#46695)
- 894696d fix(server): follow a retargeted keybindings symlink without restarting (pingdotgg#46726)
- 5c5dfbd fix(server): Send now on a provider disabled for the project reports why instead of doing nothing (pingdotgg#46734)
- facc02e fix(web): browser tests no longer reach the live server through T3CODE_PORT (pingdotgg#46738)
- 1636cca fix(web): let Enter exit code blocks with CRLF blank lines (pingdotgg#46747)
- 47e9e6b fix(shared): render insight callouts after a leading byte-order mark (pingdotgg#46748)
- 3249d18 fix(shared): preserve dot-segment IDs in assistant citations (pingdotgg#46749)
- 60aff83 fix(web): Escape dismisses the keyboard-focused timeline minimap preview card (pingdotgg#46762)
- 63c11ea fix(web): preserve wrapped reference labels in quoted PR definitions (pingdotgg#46772)
- 89ba000 fix(mobile): show the correct unit for a single cache-write token (pingdotgg#46787)
- e1fe44d fix(shared): palette search finds stroke letters by their plain look-alike (pingdotgg#46811)
- 8a69a83 fix(server): a failed Claude workspace probe keeps the machine's slash commands (pingdotgg#46795)
- 4c32975 test(web): clear storage before each browser test file (pingdotgg#46820)
- 86d1ea6 fix(web): say one rotated log when cleanup removes one file (pingdotgg#46822)
- 5aa4fb6 fix(web): dismissing a focused toast with Escape no longer triggers lower layers (pingdotgg#46810)
- 76f5300 test(web): fake environment answers the app's first discovery (pingdotgg#46858)
- 8a165fa fix(server): follow an intermediate link retargeted behind the keybindings symlink (pingdotgg#46851)
- 6043feb fix(web): keep typed double underscores literal in the rich text composer (pingdotgg#46863)
- efff167 fix(shared): pasted links to same-id threads on two machines each keep their machine (pingdotgg#46856)
- f2d53fd fix(i18n): give labels that share one key across meanings their own context (pingdotgg#46875)
- 3c7ca38 chore(evals): mcp-tool-use can send Claude calls to another endpoint (pingdotgg#46628)
- b5c30ad fix(web): closing an editor during a failing autosave retries the draft (pingdotgg#46896)
- ac11549 fix(web): keep IME Enter from committing a snooze duration (pingdotgg#46939)
- 43061f4 fix(web): keep terminal selections of the same rows that hold different text (pingdotgg#46945)
- f039a7b fix(desktop): Linux .deb updates no longer freeze the window while installing (pingdotgg#46949)
- f068ca4 fix(web): show an attached image whose file name starts with preview-annotation- (pingdotgg#46938)
- 2e0b779 fix(server): long commands typed into a starting terminal are no longer cut off (pingdotgg#46948)
- d5ebed7 fix(web): terminal chip points at the held excerpt when the same rows are re-imported (pingdotgg#46959)
- 4abc904 fix(web): thread shortcuts no longer act behind open menus or dialogs (pingdotgg#46993)
- 23fad95 fix(web): project picker tooltips fade where they opened when the list scrolls (pingdotgg#47040)
- ff26e6a fix(server): snoozed threads settle when their pull request merges (pingdotgg#46857)
- 3f2afb0 fix(web): new drafts take the workspace default from a refreshing t3.json (pingdotgg#47044)
- e7204fd fix(web): editing an attached image cancels a message waiting to send (pingdotgg#47054)
- 7e2b094 fix(web): inline math in right-to-left paragraphs no longer renders garbled (pingdotgg#47066)
- 4ce0193 fix(server): over-limit messages from workflows are refused before they are stored (pingdotgg#47087)
- aa75b46 fix(web): reloaded drafts keep typed underscores (pingdotgg#47082)
- 68abffd fix(web): an upload named preview-annotation- no longer shows as an annotation's screenshot (pingdotgg#47081)
- 74a0ccb fix(server): find unaccented messages with accented queries in scan mode (pingdotgg#47091)
- 11193d8 fix(shared): detect model option changes when repeated IDs change precedence (pingdotgg#47083)
- aa6c98f fix(web): assemble multi-segment JPEG ICC profiles by sequence number when detecting Display P3 (pingdotgg#47086)
- 63f7006 fix(server): clip workflow source without adding a broken character (pingdotgg#47104)
- 8aa5803 fix(server): preserve literal replacement characters in clipped tool diffs (pingdotgg#47108)
- 2b2bc06 fix(desktop): SnapShot setup ignores slash-dashed Niri include paths (pingdotgg#47117)
- 3c17dbf fix(web): the Voice language filter focuses its search field when opened from the keyboard (pingdotgg#47130)
- 3f6d0dd fix(desktop): capture inline favicons with percent-encoded base64 (pingdotgg#47137)
- 0b591c7 fix(web): Alt-click and Shift-click on issue links in chat act like ordinary links (pingdotgg#47144)
- cd9cda5 feat(web): add arrows and text to image annotations (pingdotgg#45251)
- 90e07c6 fix(mobile): stop large reviews freezing when a file is folded (pingdotgg#47128)
- c27ae19 fix(mobile): keep image filenames when Android shares a photo with another file (pingdotgg#47147)
- fb9f6d0 fix(web): accept HEIC attachments with metadata after a large padding box (pingdotgg#47150)
- 4453c5a fix(desktop): removing a SnapShot shortcut leaves compact Niri configs valid (pingdotgg#47134)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
size:S10-29 changed lines (additions + deletions).vouch:trustedAuthor is trusted by repo permissions or the VOUCHED list.
2 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When a transcript that was already scanned is replaced by a larger file (written elsewhere and renamed over the path, as rsync and sync tools do), Usage can keep stale token counts.
UsageServiceresumes any file that grew.readTranscriptRecordschecks only the 64 bytes before the saved offset, and those bytes can match while earlier records differ. The resumed parse is then appended to the cached records from the old file (UsageService.ts,dedupeWithinFile([...cached.records, ...parsed.records])), and the stale counts stay in the warm and persisted cache. Claude dedupe keys aremessageId:requestId, so the olda(5), the oldb(7) and the newc(13) are three distinct keys. They survivededupeWithinFileand the aggregator's key check, and the aggregator adds their output tokens to the buckets returned byserver.getUsageSummaryfor any window that covers their timestamps: 25 on base, 29 on head.Deterministic repro on
origin/main(42f4bcf63fdf): write two newline-terminated Claude assistant records,awith 5 output tokens andbwith 7 output tokens and 100 bytes of padding. Scan the file and keepposition. Write a separate file withachanged to 9,bunchanged byte-for-byte, and a new recordcwith 13 tokens.fs.renameit over the original path and callreadTranscriptRecords(path, claudeUsageFormat, position).resumed=trueand the reader returns only[13], so the warm total is 5+7+13 = 25. A cold scan of the same file returns[9,7,13]= 29.Change
Each parse position now stores the opened file's
dev:ino, read withstat({ bigint: true })so 64-bit NTFS file IDs are not rounded. Resume requires that ID to match before the existing guard-bytes check runs. The scan cache saves the ID as an optionalfifield. Entries saved before this change have no ID, so a grown file reparses once in full. No cache version bump is needed, and an older server ignores the field. The fix is in the server's shared usage scan, so web, desktop, and mobile Usage views all get the corrected totals.Scope
Small fix for an obvious bug; no issue needed under CONTRIBUTING.md.
Verification
usageTranscriptReader.test.tscase "re-parses a grown replacement file even when its guard bytes match": on base it fails withAssertionError: expected true to be falseatassert.isFalse(second.resumed). On head it passes and returns[9, 7, 13].usageScanCache.test.tsround trip now includes afileId, which shows the ID survives save and load.scenarios:provescenario or a captured RPC run) with the real reader andclaudeUsageFormat: https://gist.github.com/saphid/892bbdb2e48ce2dd2194a88e0f3f8c6d (before-after-transcript.md). Base: warm total 25, cold 29. Head: warm 29, cold 29.vp run check:changedexit 0 on head91908d7d5dc9(format, lint, knip, typecheck, tests in the 3 affected files). The log ischeck-changed-91908d7.mdin the same gist.Not shown: a captured
server.getUsageSummaryRPC run orscenarios:provescenario against isolated T3 state (the path to the RPC is traced in Problem above). Not run on Windows (the bigint read keeps NTFS file IDs exact) or on filesystems that reportino0. On those, the ID check passes and the existing guard check still applies.Authored by Claude Opus 5.5 (Model Hub); reviewed by GPT-6.2 Sol (Codex).
Not shown