CodexBar icon indicating copy to clipboard operation
CodexBar copied to clipboard

Ultra-mode Terra and Sol sessions can overcount forked context

Open iam-brain opened this issue 4 months ago • 10 comments

CodexBar appears to overstate usage for gpt-5.6-terra and especially gpt-5.6-sol when they run in Ultra mode.

The pricing is correct: models.dev reports the correct input, cached-input, output, and long-context rates for these models. The inflation seems to be coming from usage accounting. Ultra sessions can fork multiple agents and replay large portions of the parent context while interleaving cumulative token snapshots.

In one local Sol session, the raw log reached roughly 268M cumulative input tokens, while CodexBar attributed 3.29B input tokens and about $4,000 of standard cost. A single forked turn contributed more than 3B tokens across hundreds of rows. The cache marked the file as having divergent totals, which is consistent with multiple cumulative-token lineages being mixed together.

Potential fixes include:

  • Keep cumulative-token baselines scoped per task/turn or fork lineage.
  • Detect fork/replay boundaries and avoid treating replayed parent context as new usage.
  • Prefer last_token_usage deltas only when cumulative totals are unavailable or trustworthy; otherwise use cumulative deltas per lineage.
  • Add a guardrail that rejects implausibly large deltas relative to the reported per-turn usage.

The goal is to preserve genuine Ultra usage while preventing replayed fork context from being counted repeatedly. This is may be related to #1062 and #1138, but appears to be a distinct current failure involving interleaved Ultra-mode task counters.

iam-brain avatar Jul 10 '26 14:07 iam-brain

Hey @steipete your agent seems caught in a silly loop aside from the main token accounting issue.

iam-brain avatar Jul 10 '26 20:07 iam-brain

Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed July 29, 2026, 7:48 PM ET / 23:48 UTC.

Summary This canonical issue remains necessary: current main contains the Phase 1 interleaving containment and inherited-parent handling, but an open narrower PR demonstrates a remaining nested compact-child attribution case that requires raw cumulative-boundary proof and cache migration work before it can be considered resolved.

Reproducibility: no. high-confidence current-main live reproduction was run in this read-only review, but the source still exposes the Phase 1 containment boundary and the open follow-up supplies a concrete frozen-corpus nested-child case for the remaining behavior.

Root-cause cluster Relationship: canonical Canonical: https://github.com/steipete/codexbar/issues/2037 Summary: This remains the canonical umbrella for Ultra fork-context accounting. The open nested compact-child pull request covers a concrete residual shape but has not yet demonstrated that every remaining fork-family case is resolved.

Members:

  • partial_overlap: https://github.com/steipete/codexbar/pull/2396 - It addresses a nested compact-child raw-boundary and cache-attribution residual within this issue's broader fork-accounting scope, but it is still open and does not establish complete cross-file ownership.
  • same_root_cause: https://github.com/steipete/codexbar/pull/2228 - The merged PR fixed copied-prefix subagent accounting on the reported corpus but expressly left this umbrella issue open for any remaining residual.
  • same_root_cause: https://github.com/steipete/codexbar/issues/2108 - The closed corpus report supplied real fork-prefix evidence for this issue and was resolved by the merged copied-prefix work rather than replacing this canonical tracker.

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

Ways to help us reproduce this

  • Add a screenshot or short recording showing the behavior.
  • Add expected vs actual behavior.
  • Include redacted logs or terminal output.

Next step An open, concrete implementation already owns the immediate residual, while the larger issue should remain canonical until that patch lands and post-merge corpus evidence shows whether any further lineage work is justified.

Review details

Best possible solution:

Review and, if its raw-boundary and cache-migration guarantees hold, land the narrow nested compact-child fix in https://github.com/steipete/CodexBar/pull/2396; then rerun the frozen corpus and reassess whether any broader fork-family work remains.

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

No high-confidence current-main live reproduction was run in this read-only review, but the source still exposes the Phase 1 containment boundary and the open follow-up supplies a concrete frozen-corpus nested-child case for the remaining behavior.

Is this the best way to solve the issue?

Yes for the immediate path: a narrow raw cumulative-boundary proof plus provenance-aware cache migration is safer than global token-vector deduplication, because current and prior work explicitly preserve distinct events with equal counters.

AGENTS.md: found and applied where relevant.

Remaining risk / open question:

  • Closing now would hide an open, narrower residual implementation for nested compact child rollouts; its cache-migration and upgrade behavior still need normal PR review and merge validation.
  • The current containment intentionally favors conservative undercounting after interleaved cumulative counters are detected, so any further change must preserve distinct-event and nonlinear-pricing safeguards.

Codex review notes: model internal, reasoning high; reviewed against 8ef86077e70a.

Label changes

Label justifications:

  • P2: The issue can materially inflate local token and cost estimates, but known interleaving is already bounded and the remaining work is a normal-priority scanner correctness fix.
  • impact:other: The affected surface is local token and cost estimation, which does not fit the more specific owned impact classes.
Evidence reviewed

What I checked:

  • Current-main Phase 1 containment: The current scanner explicitly retains the issue's Phase 1 post-latch containment: it detects decreasing cumulative components, latches interleaved mode, and caps post-latch usage so a high/low lineage flip cannot recount the gap. The comments also state that smaller-lineage undercount is an accepted Phase 1 trade-off rather than exact lineage accounting. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:2561, 8ef86077e70a)
  • Current-main parent-baseline path: Current main resolves inherited totals from timestamped parent snapshots and treats unavailable or unstable parents as unresolved; this confirms the scanner still has a parent-baseline path rather than an exact raw copied-boundary ownership model. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:3313, 8ef86077e70a)
  • Merged copied-prefix work: Merged pull request https://github.com/steipete/CodexBar/pull/2228 added rollout-shape classification and leaf-owned suffix accounting, but its real-corpus result explicitly retained historical Unknown usage and did not claim to complete this umbrella issue. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:2740, 7143308)
  • Open residual implementation: Open pull request https://github.com/steipete/CodexBar/pull/2396 targets a later nested compact-child failure: it separates raw cumulative fork-boundary proof from owned parent totals and adds cache migration/quarantine for legacy rows. Its reported before/after corpus result is a concrete remaining shape, but it is not merged. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:3313, 766a8d83)
  • Feature-history provenance: The behavior appears to date to the merged containment/provenance work in commit c852c135e10cfdfb047895bd13c1a4425ded4afb, which deliberately deferred exact cross-file ownership. Subsequent merged work and the open residual PR continue in the same scanner and cache paths. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:2639, c852c135e10c)

Likely related people:

  • steipete: The repository owner defined the deferred provenance boundary, merged the Phase 1 containment and copied-prefix work, and explicitly kept this issue open for residual measurement. (role: recent area contributor; confidence: high; commits: c852c135e10c; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift)
  • Zihao-Qi: Authored the merged Phase 1 containment and provenance-fixture implementation that introduced the current interleaved-counter safety boundary. (role: feature introducer; confidence: high; commits: c852c135e10c; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift)
  • hhh2210: Authored merged copied-prefix accounting work and the open nested compact-child attribution follow-up in the same scanner and cache subsystem. (role: recent area contributor; confidence: high; commits: 7143308, 766a8d83; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift, Sources/CodexBarCore/Vendored/CostUsage/CostUsageCache.swift)
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.

clawsweeper[bot] avatar Jul 11 '26 02:07 clawsweeper[bot]

#2037 remains unresolved after #2059 reverted the attempted fix. The reverted implementation reconciled rows within each session file, so copied ancestor events across forked files remained duplicated; it also introduced distinct-event and nonlinear-pricing undercounts. The known released baseline is restored, but a replacement still needs cross-file fork-family/event provenance and proof against a sanitized real fork corpus.

steipete avatar Jul 11 '26 11:07 steipete

#2082 landed the bounded containment and sanitized provenance-fixture phase, but it does not complete exact cross-file fork-family provenance or exact smaller-lineage accounting. Reopening this canonical issue for that remaining Phase 2 scope.

Landed Phase 1: c852c135e10cfdfb047895bd13c1a4425ded4afb.

steipete avatar Jul 13 '26 00:07 steipete

Live affected-machine evidence for the remaining Phase 2 scope is now available in #2108:

https://github.com/steipete/CodexBar/issues/2108#issuecomment-4964735734

This uses released v0.42.1 and includes both a cold-cache initial scan and a cached repeat scan.

Key same-window result:

2026-07-14 through 02:07:30Z
v0.42.1 cold scan:          2,744,340,590 tokens / $338.980055
strict retained upper bound: 479,672,035 tokens / $338.431562
persistent unknown bucket:  2,263,762,472 tokens

For the completed prior day:

v0.42.1 cold scan:         13,147,445,914 tokens / $3,572.669502
strict retained upper bound:1,957,095,204 tokens / $1,510.838495

The strict audit removes only copied child prefixes proven to match a contiguous parent sequence across all five numeric fields in both last_token_usage and total_token_usage, then removes unchanged cumulative snapshots. The cached repeat scan preserved the completed-day inflation exactly, while live known-model usage advanced and the 2.264B unknown bucket remained frozen.

This appears to provide the requested affected real-setup initial-scan and cached repeat-scan evidence for the unresolved cross-file provenance work. The linked comment contains the full numeric-only method and breakdown; no prompts, responses, paths, filenames, account details, or session identifiers are included.

1939869736luosi avatar Jul 14 '26 02:07 1939869736luosi

My PRs, especially paired with the quick fix to align parent-child lineage, should bring overall accuracy down to +/- 5% based on my local testing but requires a large overhaul of the scanner.

When looking at historical usage, you should limit testing to the last complete day (UTC) and compare against the official reporting from your OpenAI account's token usage figures.

From #2158:

Final UTC comparison

Positive percentages are overcounts versus OpenAI; negative percentages are undercounts.

UTC day Live app cache vs OpenAI Partial fix vs OpenAI Reviewed scanner vs OpenAI OpenAI official
2026-07-09 976,079,823 +14.47% 764,026,920 -10.40% 808,692,108 -5.16% 852,682,935
2026-07-10 7,456,347,992 +371.86% 1,438,632,374 -8.96% 1,625,777,248 +2.88% 1,580,199,588
2026-07-11 98,382,045,260 +7,708.15% 846,608,173 -32.81% 1,375,236,113 +9.15% 1,259,990,957
Aggregate 106,814,473,075 +2,792.45% 3,049,267,467 -17.43% 3,809,705,469 +3.16% 3,692,873,480

From #2118: #2118 falls short of #2158's overhaul and improvements (with many more changes, of course):

UTC day OpenAI official #2118 Difference #2158 rerun Difference
Jul 9 852,682,935 764,026,920 -10.40% 764,026,920 -10.40%
Jul 10 1,580,199,588 1,421,124,213 -10.07% 1,498,664,841 -5.16%
Jul 11 1,259,990,957 846,608,173 -32.81% 1,315,404,262 +4.40%
Aggregate 3,692,873,480 3,031,759,306 -17.90% 3,578,096,023 -3.11%

Note: not 100% sure why my values during #2158 PR and #2118 comparison testing varied, CBA to check at the moment but both are within +/- 5% and much closer than legacy.

iam-brain avatar Jul 15 '26 16:07 iam-brain

Bounded follow-up #2228 is now open for the explicit Codex subagent shape.

It removes copied ancestor prefixes from subagent rollouts while preserving genuinely restarted counters, using local rollout structure rather than global token-vector equality. On the frozen affected corpus it removes the Jul 16 regression and its Unknown bucket, with identical cold/warm/forced results.

This is intentionally not presented as the Phase 2 family ledger. The 30-day scan still contains 307,441,975 historical Unknown tokens, and #2228 does not introduce cross-file event ownership, collision policy, or incomplete-result reporting. #2037 should remain open after #2228 for that broader scope.

hhh2210 avatar Jul 16 '26 15:07 hhh2210

The copied-prefix subagent accounting fix has landed via #2228. It removes copied ancestor prefixes from leaf usage while preserving reset-only counters, and adds conservative handling for ambiguous lineage plus stable cache invalidation.

Keeping this issue open until the post-#2228 residual is measured. That result should tell us whether any broader lineage-ledger work is still justified.

steipete avatar Jul 16 '26 23:07 steipete

The requested post-#2228 measurement is complete. The full method and results are in the #2108 follow-up.

The rerun is pinned to d9cae08c, using the same frozen 2,012-file corpus snapshot and a fresh isolated cache. Cold, warm with per-file cache validation, and forced scans produced identical reports.

Measure Result
Jul 16 scanner total 231,475,556 tokens
Jul 16 Unknown 0 tokens
proven copied-prefix residual at or after the owned boundary in the independent rule replay 0 events / 0 tokens
missing or unexpected fork dependency modes 0 files
final forced-cache 30-day Unknown 307,441,975 tokens

The event-level boundary result comes from an independent replay of the current-main rollout-shape rules; the Swift scanner independently produced the matching Jul 16 aggregate. The strict audit retained all 252 unmatched children, whose Jul 16 raw last_token_usage contribution is 2,404,347 tokens. Raw event sums and scanner cumulative/delta totals are structurally different, so this is not a billing correction or a comparison with OpenAI's official usage data.

Among prefixes proven by the strict matcher, this corpus no longer reproduces the copied-prefix ownership failure fixed by #2228. The remaining 30-day Unknown total is an unclassified historical Unknown bucket; it is not, by itself, evidence that a broader lineage ledger is required.

I would not treat this result as justification for a Phase 2 scanner rewrite. If #2037 remains open, it should be an evidence tracker for a separately reproduced cross-file ownership failure, not an implementation mandate.

hhh2210 avatar Jul 17 '26 04:07 hhh2210

Fixed by #2082 (c852c135e1): cumulative token baselines are contained per interleaved fork lineage, so replayed parent context is no longer repeatedly charged. Thanks for the detailed investigation.

steipete avatar Aug 02 '26 20:08 steipete