Skip to content

Fix canonical Codex long-context pricing - #2862

Closed
thomaschow19 wants to merge 2 commits into
steipete:mainfrom
thomaschow19:codex/fix-canonical-long-context-cost
Closed

Fix canonical Codex long-context pricing#2862
thomaschow19 wants to merge 2 commits into
steipete:mainfrom
thomaschow19:codex/fix-canonical-long-context-cost

Conversation

@thomaschow19

@thomaschow19 thomaschow19 commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Summary

  • replace cached Codex pricing rows inside a full-rescan window with newly parsed, fork-deduplicated rows
  • preserve exact request-scoped Standard/Fast and base/long-context pricing from canonical rows
  • omit a defensive aggregate estimate when a tiered model's combined input exceeds its threshold and request tiers cannot be recovered
  • propagate that incomplete estimate through day, history, project/source, comparison-window, and CLI aggregates instead of exposing a numeric subtotal
  • regenerate Codex cost-cache fingerprints so existing SQLite and presentation caches rebuild

Root cause

Full rescans replaced canonical day totals but merged stale in-window pricing rows back into file caches. When row totals then exceeded canonical fork-owned totals, the fallback priced the day/model aggregate as one request, incorrectly applying the >272K tier to multiple short requests.

Review follow-up

An unavailable nonzero model cost now invalidates every enclosing Codex aggregate. Known model/day breakdown costs and token totals remain visible, while CLI text renders Unavailable (incomplete pricing data) and JSON omits the ambiguous optional cost field.

Privacy-safe behavioral proof

Validation intentionally uses isolated synthetic rollout and cache data across the production layers from rescan and report construction through snapshot and CLI presentation. It does not read a real Codex home, account, provider session, browser profile, or Keychain.

Scenario Result
Two independent 200K-input requests after stale fork rows are injected A window-expansion rescan replaces the stale rows; both requests retain base-tier pricing; daily, session, and project costs agree.
One 300K-input request plus one 100K-input request Only the genuine long-context request receives the higher tier.
Unreconciled tiered aggregate above 272K plus known priced usage The affected day and history totals are unavailable; known breakdown/day costs and all token totals remain visible.
Codex CLI text and JSON Text labels the aggregate as incomplete; JSON omits the ambiguous aggregate cost while retaining tokens and known daily costs.

Validation

  • focused scanner/merge/snapshot/CLI regressions: 44 tests in 5 suites passed
  • pricing and scanner regressions: 159 tests in 3 suites passed
  • provider architecture gate: 38 tests passed
  • make test: all 840 discovered selections were exercised. The normal runner stopped in group 65/70 on unchanged UsageStoreCodexCostCatchUpTests background-QoS starvation; groups 66–70 then passed separately (439 tests), and the affected suite passed 4/4 with deterministic cooperative scheduling. Its test overrides bypass the changed pricing paths.
  • make check: passed
  • git diff --check: passed

Fixes #2858

Copilot AI lite review requested due to automatic review settings August 11, 2026 13:22
@clawsweeper

clawsweeper Bot commented Aug 11, 2026

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@clawsweeper clawsweeper Bot added 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. 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 Aug 11, 2026
@clawsweeper

clawsweeper Bot commented Aug 11, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed August 11, 2026, 1:41 PM ET / 17:41 UTC.

ClawSweeper review

What this changes

The PR replaces stale in-window Codex pricing rows on rescans, avoids guessing long-context tiers from aggregate tokens, and propagates incomplete Codex costs through reports and CLI output.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

Blocked until real behavior proof from a real setup is added - 4 items remain

Current main still uses aggregate fallback pricing, while this PR introduces the request-tier-safe path and targeted regression coverage. No discrete correctness defect was found in the rebased patch; real after-fix CodexBar proof is still required before merge. Likely related people: Peter Steinberger (high) and Xu Xiang (medium).

Priority: P2
Reviewed head: c7972ecd20b0df050ed06e9c556273658832c7e6

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The targeted implementation and coverage are solid, but real after-fix behavior proof remains the merge gate.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The synthetic production-layer fixtures are useful regression coverage, but they are still test-only evidence and do not show after-fix behavior in a real CodexBar setup; redact private details in a real CLI/rescan transcript. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The synthetic production-layer fixtures are useful regression coverage, but they are still test-only evidence and do not show after-fix behavior in a real CodexBar setup; redact private details in a real CLI/rescan transcript. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current-main behavior remains affected: Current main prices an untrusted day/model fallback through the aggregate pricing helper, which cannot distinguish the requests comprising that aggregate.
Request-tier-safe fallback: The branch returns no aggregate estimate once a thresholded model’s aggregate input exceeds its threshold, rather than applying the long-context rate to all aggregate tokens.
Incomplete-cost propagation: The branch prevents snapshot history totals from falling back to a numeric subtotal when any cost-bearing Codex day is unavailable.
Findings None None.
Security None None.

How this fits together

CodexBar scans local Codex session/cache data, derives API-equivalent prices, then publishes daily, project, snapshot, and CLI summaries. The change is at the reconciliation boundary between cached request rows and those downstream aggregates.

flowchart LR
A[Codex session records] --> B[Rescan and fork reconciliation]
B --> C[Request-level pricing rows]
C --> D[Daily and project reports]
D --> E[Usage snapshots]
E --> F[CLI text and JSON]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The synthetic production-layer fixtures are useful regression coverage, but they are still test-only evidence and do not show after-fix behavior in a real CodexBar setup; redact private details in a real CLI/rescan transcript. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - Merging changes existing Codex cache-rebuild and displayed-cost semantics; users with unreconciled tiered aggregates will now see unavailable totals rather than an inflated numeric estimate.
  • Resolve merge risk (P1) - The PR contains only synthetic fixture/test claims, not redacted after-fix output from a real CodexBar rescan and cost report.
  • Complete next step (P2) - The patch has no identified mechanical defect, but external real-behavior proof must be added by the contributor before human merge review can complete.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production versus test delta production +233, tests +565 The substantial aggregate/cache behavior change is accompanied by focused scanner, merge, snapshot, CLI, and architecture-gate coverage.

Merge-risk options

Maintainer options:

  1. Require redacted runtime proof (recommended)
    Before merge, add after-fix output from a real CodexBar rescan and cost command showing corrected pricing or explicitly unavailable totals, with private values redacted.
  2. Accept synthetic-only validation
    A maintainer may explicitly accept the remaining evidence gap, recognizing that fixture coverage does not establish behavior against a real local cache.

Technical review

Best possible solution:

Retain request-scoped pricing where canonical ownership can be rebuilt, otherwise expose an explicitly unavailable aggregate while preserving known rows and tokens; verify it with a redacted real local rescan/CLI transcript.

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

Yes—source inspection and the added deterministic fixture establish the current-main aggregate-fallback path: multiple short requests can be collapsed above a model threshold and priced as long-context usage.

Is this the best way to solve the issue?

Yes—the branch preserves request-level pricing where available and fails safely when it is not, which is narrower and safer than applying a tier to an aggregate.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The defect can materially misstate a bounded provider-cost reporting workflow, without evidence of data loss, security exposure, or runtime unavailability.
  • merge-risk: 🚨 compatibility: The PR deliberately rebuilds existing local pricing caches and changes what established Codex users see for ambiguous historical aggregates.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The synthetic production-layer fixtures are useful regression coverage, but they are still test-only evidence and do not show after-fix behavior in a real CodexBar setup; redact private details in a real CLI/rescan transcript. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Introduced the adjacent shipped aggregate-cost guard and is the dominant contributor in the scanner and aggregation history. (role: recent area contributor; confidence: high; commits: da6b5aca1d97, 405a2a467867, 61fbe9fac507; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner+CacheHelpers.swift, Sources/CodexBarCore/CostUsageFetcher.swift)
  • Xu Xiang: Authored the recent bounded Codex fork catch-up work that shares the rescan and cached-row boundary touched here. (role: fork-cache contributor; confidence: medium; commits: 4f99e6aba8c3, 2920019bc16d; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner+CacheHelpers.swift)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add a redacted real CodexBar rescan and cost-report transcript for the current head, then update the PR body for automatic re-review or ask a maintainer to comment @clawsweeper re-review.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-11T13:25:07.736Z sha 301f4c2 :: needs real behavior proof before merge. :: none

@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: 301f4c2e20

ℹ️ 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 +805 to +807
let thresholdTokens = self.codex[key]?.thresholdTokens ?? modelsDevLookup?.pricing.thresholdTokens
if let thresholdTokens, max(0, inputTokens) > thresholdTokens {
return nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Propagate ambiguous costs into aggregate totals

When any day/model lacks trusted rows and its aggregate input exceeds this threshold, the helper now returns nil, but buildCodexReportFromCache still sums every other priced model/day and exposes that partial sum as summary.totalCostUSD. Consequently, a 30-day report containing one affected fork-deduplicated day plus any normally priced day displays a numeric “last 30 days” cost that silently excludes the ambiguous usage instead of indicating that the total is unavailable; track the missing cost through the entry and summary aggregation rather than treating the remaining subtotal as complete.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed. The ambiguous model breakdown was omitted, but day, report, merge, snapshot, comparison-window, and CLI layers could still reconstruct a numeric subtotal from the remaining priced rows. The follow-up now propagates incompleteness through every enclosing Codex aggregate while retaining known breakdowns and token totals. Mixed-model, mixed-day, merge, snapshot, comparison-window, and CLI regressions cover the full path.

Copilot AI 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.

Pull request overview

This PR fixes Codex cost inflation during canonical fallback by ensuring request-level pricing metadata (especially long-context tiering) is preserved through fork deduplication and rescan cache rebuilds, and by avoiding unsafe aggregate pricing when request tiers can’t be reconstructed.

Changes:

  • Replace cached Codex pricing rows inside the scan window with newly parsed, fork-deduplicated rows (preventing stale in-window rows from leaking into rebuilt caches).
  • Introduce a Codex-specific aggregate pricing helper that returns nil when an aggregate would cross a long-context threshold (instead of mispricing the entire day/model as one long-context request).
  • Add regression tests covering window-expansion repair, long-context tier isolation, and ambiguous aggregate fallback omission; regenerate the parser fingerprint to force SQLite cache rebuilds.

Reviewed changes

Copilot reviewed 4 out of 5 changed files in this pull request and generated no comments.

Show a summary per file
File Description
Tests/CodexBarTests/CostUsageScannerForkSplitTests.swift Adds regression tests for rescan window row replacement, long-context tiering correctness, and aggregate fallback omission.
Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner+CacheHelpers.swift Ensures cached rows within the scan window are not retained during rescan; switches canonical fallback to aggregate-safe pricing.
Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift Adds codexAggregateCostUSD to avoid applying request-scoped long-context tiers to day/model aggregates.
Sources/CodexBarCore/Generated/CodexParserHash.generated.swift Bumps parser fingerprint to invalidate/rebuild persisted cost caches.
CHANGELOG.md Documents the user-facing Codex pricing fix.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@thomaschow19
thomaschow19 force-pushed the codex/fix-canonical-long-context-cost branch from 301f4c2 to c7972ec Compare August 11, 2026 17:36
@thomaschow19

Copy link
Copy Markdown
Contributor Author

Rebased and addressed the incomplete-total edge case. A missing cost for nonzero Codex usage now propagates through day, history, comparison-window, project/source, and CLI totals instead of exposing a subtotal.

The requested real-account cache/CLI proof is intentionally not included: this contribution's privacy constraints prohibit reading or publishing real account data, provider sessions, browser state, or Keychain material. The revised PR body instead documents deterministic synthetic proof across the production layers from rescan and report construction through snapshot and CLI presentation, including explicit incomplete-pricing text and omitted ambiguous JSON cost fields.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 11, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@thomaschow19

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: c7972ecd20

ℹ️ 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".

@steipete

Copy link
Copy Markdown
Owner

Thanks for the detailed investigation and the strong synthetic coverage, @thomaschow19. This is now superseded by #2863, which landed as 4befde4bbdf0cabc6db048bcc93e9bb28fb2d766 and closed #2858.

The landed repair preserves request-level base/long-context and Standard/Fast tiers, reconciles copied fork prefixes from existing persisted rows, keeps compatible SQLite history without a destructive rescan, and handles concurrent cache writers without rebuilding. It passed all 840 local test selections, exact-head CI, P2 autoreview, and ClawSweeper review.

Your report and fixtures materially shaped the final fix, and the 0.49.3 changelog credits you. Closing this duplicate implementation in favor of the landed version.

@steipete steipete closed this Aug 11, 2026
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. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Codex cost nearly doubles when canonical day/model fallback applies >272K long-context pricing to aggregated tokens

3 participants