Skip to content

Contain Codex interleaved overcount and add fork provenance fixtures (#2037)#2082

Merged
steipete merged 12 commits into
steipete:mainfrom
Zihao-Qi:codex/fix-2037-fork-family-provenance
Jul 13, 2026
Merged

Contain Codex interleaved overcount and add fork provenance fixtures (#2037)#2082
steipete merged 12 commits into
steipete:mainfrom
Zihao-Qi:codex/fix-2037-fork-family-provenance

Conversation

@Zihao-Qi

@Zihao-Qi Zihao-Qi commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Missing-parent safety decision

  • Runtime token-only sibling-prefix suppression was removed in 5441ff75.
  • Distinct sibling events can have identical last_token_usage / total_token_usage vectors at the same ordinal. Treating those counters as event identity can silently undercount legitimate work.
  • Envelope timestamps are rewritten across copied prefixes, model is not reliably present on token_count, and adding more token fields only reduces collision probability. Therefore missing-parent siblings fail open: retain possible copied-prefix overcount rather than destructively suppress ambiguous rows.
  • A focused equal-counter sibling regression asserts both distinct events remain billable.

Deferred provenance work

  • Prove a copy-stable event identity stronger than token values.
  • Build cross-window family closure, collision handling, ownership migration, and the incomplete/contained quality path.
  • Add redacted initial and cached repeat-scan output from an affected real Codex setup. Sanitized fixtures and tests are supplemental evidence, not that live proof.

Relationship to #2066

  • This branch contains the Contain Ultra interleaved token overcounting (#2037) #2066 file-local containment commit; the two PRs should not be merged independently as separate implementations.
  • The provenance fixtures/specs in this PR are design evidence for the later family-ledger work, not a claim that token-only cross-file dedupe is safe.
  • Neither PR uses Fixes #2037.

Test plan

  • swift test --filter Issue2037
  • swift test --filter 'codex interleaved'
  • swift test --filter 'codex forked child'
  • make check
  • make test — 618 selections, 52/52 groups passed
  • Redacted initial + cached repeat-scan output from an affected real setup

@Zihao-Qi Zihao-Qi marked this pull request as ready for review July 12, 2026 03:14

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2433b97a36

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1121 to +1122
billingSuppressedTokenOrdinals: context.resources
.billingSuppressedTokenOrdinalsByFilePath[input.fileURL.path] ?? [],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Rescan cached files when suppressing prefixes

Because scanCodexFile tries the fresh-cache path before this rescan path, an unchanged sibling that was already cached never sees billingSuppressedTokenOrdinalsByFilePath when a new earlier sibling for the same missing parent appears. In that scenario the old file keeps its cached full-prefix rows while the new owner also bills the shared prefix, so the copied prefix is double-counted until a force rescan or cache bust; files with newly computed suppressions need to bypass the fresh-cache path or persist the suppression state in the cache.

Useful? React with 👍 / 👎.

// Match inheritance discovery against cache + in-scan files only. Avoid `indexRoots()`
// crawls on every refresh for confirmed-missing parents; previously scanned parents are
// already seeded into `fileIndex` via `cachedCodexSessionIndex`.
if Self.codexCacheContainsSession(cache, sessionId: parentId) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Ignore stale parent cache entries when deduping siblings

When a parent session is still in cache.files but its JSONL has since been deleted or moved out of the active roots, this raw cache lookup still returns true before stale entries are pruned later in loadCodexDaily. The resolver/index will not be able to read that parent, so the children are parsed as unresolved while this block has skipped missing-parent prefix suppression, billing the siblings' copied prefix more than once for that refresh and saving the overcount; validate the cached parent's path exists under the roots or rely on the file index instead of the raw cache.

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Jul 12, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 12, 2026, 7:42 PM ET / 23:42 UTC.

Summary
The branch adds bounded containment for interleaved Codex cumulative counters, persists and invalidates the corresponding cache state, and adds sanitized fork-family fixtures, scanner oracles, regression tests, and provenance design documentation.

Reproducibility: yes. at high confidence from source and fixtures: sanitized interleaved and fork-family inputs have hand-calculated scanner oracles, and the repository owner reports exact after-fix results from the signed application and bundled CLI. The original private Ultra corpus itself is not committed, so the classification remains source-reproducible rather than a direct current-main live reproduction.

Review metrics: 3 noteworthy metrics.

  • Patch surface: 29 files, +4,333/-382. Most of the large surface is sanitized fixture, oracle, test, and design material supporting a focused scanner change.
  • Fixture families: 3 provenance families plus 1 harness smoke family. The corpus covers parent-present forks, a live-derived fork, ambiguous missing-parent siblings, and installation behavior.
  • Maintainer validation: 8 Issue2037 tests, 80 scanner tests, full suite passed. Focused and broad validation accompany the signed-bundle runtime proof.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #2037
Summary: This PR is the current partial fix candidate for the canonical Ultra/fork overcount issue and incorporates the earlier containment branch without claiming to complete cross-file provenance.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • none.

Risk before merge

  • [P1] Post-latch containment intentionally favors never inflating usage and can undercount genuine smaller-lineage totals-only work until the cross-file provenance design is implemented.
  • [P1] The parser-key invalidation rebuilds existing Codex cost caches, so reported historical totals may change after upgrade; this is intentional but user-visible compatibility behavior.

Maintainer options:

  1. Land the bounded containment (recommended)
    Merge the proven head after required checks, accepting conservative undercount in ambiguous interleaved cases while preventing extreme inflation.
  2. Wait for exact provenance
    Pause this PR until the complete cross-file family ledger can avoid both inflation and smaller-lineage undercount, leaving affected users exposed longer.

Next step before merge

  • [P2] No narrow automated repair remains; normal maintainer merge handling should wait for required checks on the exact proven head and then reconcile the overlapping older PR.

Security
Cleared: The diff adds no dependency, workflow, permission, secret-handling, downloaded-code, or package-resolution change, and the sanitized fixtures contain no evident credentials or message content.

Review details

Best possible solution:

Land the exact proven head after required checks pass, close the incorporated and independently unmergeable #2066 path, and keep #2037 open for the fixture-gated cross-file provenance ledger and exact smaller-lineage accounting.

Do we have a high-confidence way to reproduce the issue?

Yes at high confidence from source and fixtures: sanitized interleaved and fork-family inputs have hand-calculated scanner oracles, and the repository owner reports exact after-fix results from the signed application and bundled CLI. The original private Ultra corpus itself is not committed, so the classification remains source-reproducible rather than a direct current-main live reproduction.

Is this the best way to solve the issue?

Yes for the scoped Phase 1 objective. The bounded replay and watermark policy prevents multiplicative overcount without relying on unsafe token-value identity, while explicitly leaving exact cross-file provenance to the canonical follow-up.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 7465c6a11674.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. A repository-owner comment documents after-fix signed-app and bundled-CLI scans on Parallels macOS, deep signature validation, host/guest agreement, and exact expected scanner totals; this supersedes the earlier missing-proof gate.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): A repository-owner comment documents after-fix signed-app and bundled-CLI scans on Parallels macOS, deep signature validation, host/guest agreement, and exact expected scanner totals; this supersedes the earlier missing-proof gate.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: The PR fixes materially inflated Codex cost history but is limited to the local usage scanner rather than core app availability.
  • merge-risk: 🚨 compatibility: Merging deliberately changes cached and post-latch accounting semantics, rebuilding prior caches and conservatively undercounting some ambiguous smaller-lineage work.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): A repository-owner comment documents after-fix signed-app and bundled-CLI scans on Parallels macOS, deep signature validation, host/guest agreement, and exact expected scanner totals; this supersedes the earlier missing-proof gate.
  • proof: sufficient: Contributor real behavior proof is sufficient. A repository-owner comment documents after-fix signed-app and bundled-CLI scans on Parallels macOS, deep signature validation, host/guest agreement, and exact expected scanner totals; this supersedes the earlier missing-proof gate.
Evidence reviewed

What I checked:

  • Containment implementation: The final tree adds watermark-based interleaved-counter containment, bounded replay tracking, cache state, and conservative handling of ambiguous missing-parent siblings. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift, be56cc9aff5e)
  • Cache compatibility: Earlier Codex parser producer keys are deliberately rejected because the changed delta semantics require rebuilding old cost caches. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageCache.swift, be56cc9aff5e)
  • Regression coverage: The branch adds replay, divergent-snapshot, interleaved-counter, fork inheritance, missing-parent, cache, fixture-harness, and scanner-oracle coverage. (Tests/CodexBarTests/CostUsageScannerBreakdownTests.swift, be56cc9aff5e)
  • Prior finding resolved: The unsafe token-value-only sibling suppression was removed, and equal-counter sibling coverage now verifies that ambiguous distinct events remain billable rather than being destructively deduplicated. (Tests/CodexBarTests/Issue2037ScannerIntegrationTests.swift, be56cc9aff5e)
  • Real behavior proof: The repository owner reports testing a Developer ID-signed app and bundled CLI on Parallels macOS, with deep signature validation and exact oracle matches for archived, live-fork, and missing-parent scans on both host and guest. (be56cc9aff5e)
  • Validation evidence: The maintainer pass reports Issue2037 tests at 8/8, scanner breakdown tests at 80/80, make check passing, the full test suite passing, and final production and harness diffs receiving a clean autoreview. (be56cc9aff5e)

Likely related people:

  • steipete: Authored the final seven refinement commits, performed the runtime proof pass, and documented the accepted replay-state and fail-open invariants. (role: recent area contributor and reviewer; confidence: high; commits: cb6538b18d09, ab65dd331faf, 6a7c577acf58; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift, Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner+CacheHelpers.swift, Tests/CodexBarTests/CostUsageScannerBreakdownTests.swift)
  • xx205: Authored the merged parent-baseline and replay-accounting work that this PR preserves and extends for interleaved counters. (role: introduced adjacent fork accounting behavior; confidence: high; commits: 45b68c34ec48; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift, Tests/CodexBarTests/CostUsageScannerBreakdownTests.swift)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (5 earlier review cycles)
  • reviewed 2026-07-12T03:17:41.588Z sha 2433b97 :: needs real behavior proof before merge. :: [P2] Propagate cancellation from the fingerprint pre-scan
  • reviewed 2026-07-12T03:37:45.758Z sha 0847c41 :: needs real behavior proof before merge. :: [P2] Deduplicate longer prefixes shared by sibling subsets
  • reviewed 2026-07-12T05:05:41.094Z sha 0847c41 :: needs real behavior proof before merge. :: [P2] Deduplicate longer prefixes shared by sibling subsets
  • reviewed 2026-07-12T05:35:53.962Z sha 1816116 :: needs real behavior proof before merge. :: [P1] Include stable event identity before suppressing a sibling row
  • reviewed 2026-07-12T06:06:40.375Z sha 5441ff7 :: needs real behavior proof before merge. :: none

@Zihao-Qi Zihao-Qi force-pushed the codex/fix-2037-fork-family-provenance branch from 2433b97 to df637ec Compare July 12, 2026 03:20
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. labels Jul 12, 2026
@Zihao-Qi Zihao-Qi marked this pull request as draft July 12, 2026 04:59
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 12, 2026
@Zihao-Qi Zihao-Qi marked this pull request as ready for review July 12, 2026 05:24

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1816116e5d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2889 to +2893
return [
last.input,
last.cached,
last.output,
total.input,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include more than token counts in fork fingerprints

When two children of the same unresolved parent have distinct token events at the same ordinal but coincidentally identical last/total counts (for example different prompts/models or timestamps that produce the same token totals), this fingerprint makes buildProvisionalPrefixBillingSuppressions treat them as a copied prefix and suppress all but the first sibling. Because the key omits copy-stable identity such as timestamp/model/line identity and is only token values, legitimate sibling work can be undercounted; the new provenance spec also calls out that token-value equality alone must not drive dedupe.

Useful? React with 👍 / 👎.

@Zihao-Qi Zihao-Qi changed the title Add Codex fork-family provenance and missing-parent dedupe (#2037) Contain Codex interleaved overcount and add fork provenance fixtures (#2037) Jul 12, 2026
Zihao-Qi and others added 12 commits July 12, 2026 23:12
Stop gap-recount inflation with post-latch watermark containment and a
min(last, containedTotalDelta) cap, while documenting the intentional
smaller-lineage undercount deferred to Phase 2.

Co-authored-by: Cursor <cursoragent@cursor.com>
Lock ordinary Codex fork copy identity with sanitized goldens, suppress
shared missing-parent prefixes once, and keep suppression ordinals aligned
with the scan parser without claiming steipete#2037 closed.

Co-authored-by: Cursor <cursoragent@cursor.com>
Propagate refresh cancellation through fingerprint pre-scans, ignore stale
cached parents, and force-rescan suppressed siblings when the fork family grows.

Co-authored-by: Cursor <cursoragent@cursor.com>
@steipete steipete force-pushed the codex/fix-2037-fork-family-provenance branch from 5441ff7 to be56cc9 Compare July 12, 2026 23:37
@steipete

Copy link
Copy Markdown
Owner

Maintainer pass complete on the rebased head be56cc9af.

Changes from the original PR:

  • retained the bounded 64-snapshot replay state after adversarial review showed a watermark-only simplification could recount older fork snapshots;
  • made ambiguous missing-parent siblings fail open instead of suppressing unrelated equal counters;
  • added replay, divergent-snapshot, missing-parent, provenance, and scanner-oracle coverage;
  • added the maintainer changelog credit.

Proof:

  • swift test --filter Issue2037: 8/8 passed
  • swift test --filter CostUsageScannerBreakdownTests: 80/80 passed
  • make check: passed
  • make test: passed; one unrelated Kiro timing group passed on the harness's built-in retry
  • final production and harness diffs: autoreview clean

Live package proof used the Developer ID-signed CodexBar.app and its bundled CLI on Parallels macOS 26.5 (25F71). The sanitized fixture dates were shifted mechanically into the current seven-day window; token values and event ordering were unchanged. Deep signature validation passed for team Y5PE65HELJ, and isolated CODEX_HOME scans produced:

  • archived fork: 28,858,874 scanner units
  • live fork: 52,185,847 scanner units, exactly matching the golden oracle
  • missing-parent siblings: 54,358,161 scanner units, matching the intended fail-open result after each unresolved child skips only its own first cumulative snapshot

Host and guest results matched.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: be56cc9aff

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +207 to +211
func component(water: Int, counted: Int, current: Int) -> Int {
if current >= water {
return max(0, current - max(water, counted))
}
return max(0, current - counted)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Contain interleaved rows as a single snapshot

When an interleaved row drops in one component but rises in another, this component-wise branch still bills the rising component from the lower lineage. For example, totals-only snapshots (input: 1000, output: 1) followed by (input: 10, output: 1000) latch interleaving because input drops, but then add 999 output tokens, so the file reports 2000 tokens even though no observed cumulative snapshot exceeds 1010. That reintroduces overcounting for mixed input/output lineages; after any component indicates a lineage flip, the event should be contained as a whole rather than combining per-component watermarks from different snapshots.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 12, 2026
@steipete steipete merged commit c852c13 into steipete:main Jul 13, 2026
14 of 15 checks passed
Yuxin-Qiao pushed a commit to Yuxin-Qiao/CodexBar that referenced this pull request Jul 13, 2026
Contain interleaved cumulative counters with bounded replay tracking, retain conservative fail-open behavior for ambiguous missing-parent siblings, and add sanitized fork-family oracles plus regression coverage.

Co-authored-by: Zihaoqi <Zihao-Qi@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ultra-mode Terra and Sol sessions can overcount forked context

2 participants