Skip to content

fix(codex-usage): deduplicate fork-copied token events across timestamp rewrites - #19152

Closed
MeroZemory wants to merge 3 commits into
stablyai:mainfrom
MeroZemory:fix/codex-fork-timestamp-dedupe
Closed

MeroZemory wants to merge 3 commits into
stablyai:mainfrom
MeroZemory:fix/codex-fork-timestamp-dedupe

Conversation

@MeroZemory

@MeroZemory MeroZemory commented Sep 6, 2026 •

Copy link
Copy Markdown

ELI5

Forking a Codex conversation can copy its token events with new timestamps. Count copied history once while keeping unrelated conversations and independent turns separate.

What Changed

Use the recorded shared root and turn identity with the cumulative/last usage tuples, without the rewritten event timestamp. Fall back to an explicit parent ID or the session's own ID for older logs. Last-only records receive an occurrence identity so equal successive deltas remain countable. Invalidate the old usage cache (schema 6).

Why

The original tuple-only fix could undercount independent sessions. This follow-up addresses that review finding and adds scanner and parser regression coverage. Logs with neither stable lineage nor turn identity cannot prove that two histories are copies; legacy histories without that evidence may remain counted separately.

Linked Issue

Fixes #19139

Visual Proof

N/A — this changes usage event ownership and cache invalidation, not rendered layout. Synthetic scanner fixtures assert exact totals before and after fork copying.

Testing

  • Automated tests added/updated: 33 passed across scanner-paths, scanner, store-persistence and record-identity tests on Windows.
  • Targeted oxlint and oxfmt checks passed.
  • Manual provider-billing reconciliation (not performed; these are local transcript estimates).

AI Disclosure

Developed and reviewed with Codex (GPT-6).

Review

Follow-up isolates unrelated roots, legacy session IDs, independent turns, and repeated last-only events. Cache ownership/deletion regression tests also pass.

Agent skill upstream boundary

  • Not applicable; no skill-installer code or material changed.

…mp rewrites

Codex rewrites copied token_count timestamps to the fork creation time when sessions are forked, causing timestamp-based deduplication keys to treat copied turns as new unique usage events.

Drop the raw timestamp from buildCodexUsageEventKey and key deduplication on monotonic token usage tuples. Bump CODEX_USAGE_SCHEMA_VERSION to 6 to invalidate cached v5 entries.

Fixes stablyai#19139
@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

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: 871efe34-a687-408b-b6e5-6c9c1dbc27c7

📥 Commits

Reviewing files that changed from the base of the PR and between 06c5e91 and 5e75af6.

📒 Files selected for processing (5)
  • src/main/codex-usage/codex-usage-record-identity.test.ts
  • src/main/codex-usage/codex-usage-record-parser.ts
  • src/main/codex-usage/codex-usage-token-delta.ts
  • src/main/codex-usage/scanner-paths.test.ts
  • src/main/codex-usage/scanner.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/codex-usage/scanner-paths.test.ts
  • src/main/codex-usage/codex-usage-token-delta.ts

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


📝 Walkthrough

Walkthrough

The Codex usage schema version increases from 5 to 6. The parser now tracks root thread and turn identity. Usage event keys use this identity and token usage tuples instead of raw timestamps. Scanner tests cover fork deduplication and unrelated sessions. Persistence tests update schema version expectations.

Priority: ⬆️ High — Impact reflects high issue severity.

Severity of issue fixed: High

Merge Risk: ⚪ Minimal · up to 5e75a

Codex usage aggregation now avoids re-counting copied fork history while preserving separate usage for unrelated sessions, and cached aggregates are rebuilt under the updated schema.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy issue #19139. They remove raw timestamps from the primary usage event key, use root and turn identity with usage tuples to deduplicate fork history, isolate unrelated sessions and …
Out of Scope Changes check ✅ Passed All code and test changes support fork-event deduplication, usage ownership, legacy-session handling, or schema-cache invalidation. No unrelated changes are present.
Title check ✅ Passed The title clearly and concisely describes the main change: deduplicating fork-copied Codex token events despite timestamp rewrites.
Description check ✅ Passed The description covers the required core sections, including the problem, changes, rationale, linked issue, visual proof, testing, AI disclosure, and review notes. The Notes and Checklist sections are…
  • Fix all pre-merge checks with AI

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

Run ID: 441d4ab5-2e36-4ed7-9ec1-bedc0cc7765a

📥 Commits

Reviewing files that changed from the base of the PR and between 6fd03a7 and 06c5e91.

📒 Files selected for processing (5)
  • src/main/codex-usage/codex-usage-provider.ts
  • src/main/codex-usage/codex-usage-record-parser.ts
  • src/main/codex-usage/codex-usage-token-delta.ts
  • src/main/codex-usage/scanner-paths.test.ts
  • src/main/codex-usage/store-persistence.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 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.

Important

The dedup key now carries no identity component at all, so identical usage tuples from unrelated sessions will collide and silently undercount — the inverse of the overcount this PR fixes. Details inline.

Reviewed changes — this PR reworks Codex usage-event deduplication so fork-copied records survive timestamp rewrites, plus a schema bump and a regression test.

  • Key change — buildCodexUsageEventKey drops the raw timestamp and keys only on the totalUsage/lastUsage tuples.
  • Schema bump — CODEX_USAGE_SCHEMA_VERSION 5 → 6 invalidates cached v5 aggregates so history re-aggregates.
  • Regression test — scanner-paths.test.ts asserts fork-copied events with rewritten timestamps dedupe to 22 total tokens; the assertion is exact and would fail under the v5 key.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (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 critical issues — the prior identity concern is addressed; one minor naming nit inline.

Reviewed changes — this follow-up threads session and turn identity into the Codex usage-event dedup key so unrelated sessions no longer collide, plus regression coverage.

  • Resolved rootThreadId — the parser now derives a fork-stable id (session_id → forked_from_id → sessionId) and carries it on the parse context.
  • Added turn identity — currentTurnId from turn_context isolates independent fork turns that produce identical usage tuples.
  • Added last-only occurrence identity — records without cumulative totals key on [sessionId, timestamp, usageEventIndex] so equal successive deltas stay countable.
  • Regression tests — new codex-usage-record-identity.test.ts plus three scanner-paths.test.ts cases assert unrelated-session and independent-turn isolation with exact token totals.

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


export function buildCodexUsageEventKey(
timestamp: string,
rootThreadId: string | null | undefined,

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.

The first parameter is named rootThreadId, but the parser now passes a JSON.stringify-ed array of [rootThreadId, currentTurnId, last-only occurrence] (see codex-usage-record-parser.ts:163), not a raw thread id. Rename it (e.g. identity) so the signature no longer misstates what the key is built from.

@nwparker

Copy link
Copy Markdown
Contributor

Thanks @MeroZemory — your diagnosis was right (Codex rewrites copied token_count timestamps on fork). We landed a smaller variant of your turn-identity approach in #33478 that also persists the turn id in the incremental-scan checkpoint added to main since this PR was opened; you're credited as co-author. Closing in favor of that.

nwparker added a commit that referenced this pull request Oct 25, 2026
Codex usage no longer double-counts forked sessions: forks copy the parent's token_count events with fresh timestamps, so cumulative events are now keyed on turn id + totals (timestamp fallback when no turn id); the turn id is kept in the incremental-scan checkpoint and the usage cache is rebuilt once.

Fixes #19139
Supersedes #19152

Co-authored-by: Jio Kim <26668612+MeroZemory@users.noreply.github.com>
@nwparker nwparker closed this Oct 25, 2026
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.

[Bug]: Codex token usage inflated on session forks because Codex rewrites timestamps

2 participants