Skip to content

perf: reuse Codex pricing resolution across reports - #3476

Merged
steipete merged 6 commits into
steipete:mainfrom
brzvsk:perf/codex-report-pricing-context
Sep 7, 2026
Merged

perf: reuse Codex pricing resolution across reports#3476
steipete merged 6 commits into
steipete:mainfrom
brzvsk:perf/codex-report-pricing-context

Conversation

@brzvsk

@brzvsk brzvsk commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Codex cost reports repeatedly normalized and matched the same model even after the pricing catalog was loaded. Reuse bounded model-resolution results within one synchronous daily, project, or session report collection, reducing redundant CPU work without caching final prices or costs.

The resolver retains exact UTF-8 input keys, including positive and negative results, with 1,024 entries per memo and a 512-byte admission check before allocation. Oversized identifiers remain correct and uncached. Historical dates, custom zero/partial overrides, provider-qualified routes, context thresholds, authoritative source costs, and priority multipliers continue through scalar pricing. There is no global cache or cross-refresh invalidation policy.

The separate cleanup #3479 is landed and removes 110 production lines. This integrated fix adds 101 lines relative to that cleanup, leaving the pair net negative by nine lines. Project/session summaries retain their existing field projection. Native cache rows and checkpoints remain compatible with both the released parser identity 9547dc9d7b7675f6 and the cleanup identity ba2eca901de4c53d. Pi/OMP retains its existing parser-key invalidation policy and separate predecessor coverage.

Current integration validation

  • The work-count regression requires one catalog lookup per collection for daily, project, and session reports with both 1 and 16 files. The contributor's baseline made 16,401 lookups for the 16-file / 4,096-row / one-model project fixture.
  • All 267 focused tests across 11 suites pass after integration, including resolver bounds, scalar parity, pricing/overlays, catalog-loading work, project projection, native cache adoption, Pi compatibility, fork accounting, and architecture checks.
  • The full local suite passed all 1,031 selections across 86 groups on the first attempt, without retries or timeouts, in 897.7 seconds.
  • make check passes. Independent review found no actionable P0–P2 findings.
  • Synchronization with the landed cleanup left the tested source tree byte-identical. Exact-head CI 34155321823 passes all macOS tests, Linux builds, lint, and security checks on fa55568.
  • A cold local checkout initially lacked the SwiftPM Sparkle runtime link. The repository's existing test-runtime recovery helper repaired it before the successful test runs; no source or assertion was weakened.

Contributor's real-corpus proof

Nikolai Berezovskii (@brzvsk) measured the original resolver implementation at 35a0de6 against base 170a4d4 using a private frozen backup of an existing cost cache and pricing catalog: 2,169 files and 243,617 exact usage rows. Optimized core harnesses loaded SQLite and built daily, project, and session reports for fixed 30-day and 365-day ranges. The original A/B used three fresh processes per variant, reversing order for the middle pair; the post-review candidate was rebuilt and measured three more times against the same input. No concurrent build ran during those measurements.

Complete measured path Base Original candidate Change
CPU, user + system 13.93 s 5.82 s −58.2%
Wall time 14.03 s 5.84 s −58.4%
Peak RSS 386.3 MB 403.6 MB +4.5%
30-day load + three report builders 4.216 s 2.144 s −49.2%
365-day load + three report builders 9.489 s 3.430 s −63.9%

All six complete structural report receipts were byte-identical, including token/cost/priority fields. Range timings include SQLite loading; process totals also include receipt serialization. Both variants used the same frozen catalog, existing persisted parser identity, and empty custom overlay. Override behavior is covered by scalar-parity tests. These are contributor-recorded measurements of the original implementation, not newly measured percentages for the maintainer integration. Raw cache data, reports, identities, and paths remain private.

This fixes repeated Codex report model resolution, complementing #3297's deferred raw-history decoding and #3319's separate Claude resolver. It does not claim to solve all eager usage-row hydration, scheduling, pending-state transitions, or whole-app battery use. Refs #3247; related follow-up evidence appears in #3411. Changelog credit is retained. Thanks @brzvsk for the root-cause investigation, implementation, memory-bound correction, and detailed proof.

@clawsweeper

clawsweeper Bot commented Sep 7, 2026

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 7, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-07T14:58:20.322434Z 35a0de6 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added 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. labels Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed September 7, 2026, 3:32 PM ET / 19:32 UTC.

ClawSweeper review

What this changes

Reuse bounded model-pricing lookups within each Codex daily, project, or session report collection while preserving individual cost calculations.

Merge readiness

Ready for maintainer review

This remains a useful, well-supported optimization after the merged cleanup. No actionable defects remain; the disclosed benchmark baseline does not create an additional merge blocker.

Priority: P2
Reviewed head: fa555686e594ae45f7e26986570a46621f04e930

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong real-corpus evidence, bounded memoization, and focused parity and upgrade coverage support the clean patch.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Contributor-recorded real-cache runs exercised SQLite loading and the production daily/project/session builders, showing lower CPU and identical complete reports. The measured resolver is unchanged; integration coverage supplements that proof without claiming new baseline percentages.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Contributor-recorded real-cache runs exercised SQLite loading and the production daily/project/session builders, showing lower CPU and identical complete reports. The measured resolver is unchanged; integration coverage supplements that proof without claiming new baseline percentages.
Evidence reviewed 8 items Repository policy and scope: Read the complete root AGENTS.md; no nested AGENTS.md files or maintainer-notes directory were present. Applied guidance on focused changes, provider isolation, concurrency, and credential-safe validation. Repository origin confirms ownership.
Complete introduced change: Inspected all 16 changed files against the pinned main/merge-base. Main lacks this Codex memoization; the merged cleanup at #3479 consolidates accumulation rather than replacing this optimization.
Prior memory finding resolved: Both memos admit at most 1,024 exact UTF-8 keys and reject inputs above 512 bytes before array allocation. Oversized identifiers retain scalar resolution. The resolver has no differences from the contributor's measured revision.
Findings None None.
Security None None.

How this fits together

CodexBar builds local spend reports from cached session usage and pricing catalogs. These calculations feed daily totals and project/session breakdowns in its spend surfaces.

flowchart LR
  A[Cached session usage] --> C[Report collection]
  B[Pricing catalog] --> D[Bounded model lookup memo]
  C --> D
  D --> E[Per-row cost calculation]
  F[Dates and custom rates] --> E
  E --> G[Daily project and session reports]
Loading

Before merge

None.

Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Net code growth production +101 lines; tests +232 lines Production growth implements bounded lookup reuse, with substantially more regression coverage.
Lookup scaling coverage 3 report types × 2 corpus sizes The regression requires one catalog lookup for a repeated model across both 1-file and 16-file collections.

Technical review

Best possible solution:

Keep lookup reuse scoped to each report collection, with bounded memory and unchanged per-row pricing and cache compatibility.

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

Yes: main repeatedly resolves the same model inside report-row processing, and the contributor's real-cache measurements demonstrate the cost; this review verified the path without executing it.

Is this the best way to solve the issue?

Yes: collection-scoped memoization reuses the existing pricing lookup while leaving request-dependent prices uncached, following the repository's established resolver pattern.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against c526fe71721e.

Labels

Label justifications:

  • P2: A bounded performance improvement reduces repeated cost-report work for large local histories.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Contributor-recorded real-cache runs exercised SQLite loading and the production daily/project/session builders, showing lower CPU and identical complete reports. The measured resolver is unchanged; integration coverage supplements that proof without claiming new baseline percentages.
  • proof: sufficient: Contributor real behavior proof is sufficient. Contributor-recorded real-cache runs exercised SQLite loading and the production daily/project/session builders, showing lower CPU and identical complete reports. The measured resolver is unchanged; integration coverage supplements that proof without claiming new baseline percentages.

Evidence

What I checked:

  • Repository policy and scope: Read the complete root AGENTS.md; no nested AGENTS.md files or maintainer-notes directory were present. Applied guidance on focused changes, provider isolation, concurrency, and credential-safe validation. Repository origin confirms ownership. (AGENTS.md:1, fa555686e594)
  • Complete introduced change: Inspected all 16 changed files against the pinned main/merge-base. Main lacks this Codex memoization; the merged cleanup at Refactor duplicated Codex report accumulation and pricing #3479 consolidates accumulation rather than replacing this optimization. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner+Projects.swift:31, fa555686e594)
  • Prior memory finding resolved: Both memos admit at most 1,024 exact UTF-8 keys and reject inputs above 512 bytes before array allocation. Oversized identifiers retain scalar resolution. The resolver has no differences from the contributor's measured revision. (Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing+CodexResolver.swift:49, fa555686e594)
  • Scalar semantics and collection ownership: Report builders share one immutable catalog-backed resolver synchronously. Historical pricing, custom overlays, thresholds, authoritative row costs, and priority calculations remain outside memoized results; existing scalar callers remain supported. (Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift:589, fa555686e594)
  • Regression and upgrade coverage: Inspected scalar-parity, saturation, Unicode, oversized-key, and collection work-count tests. Native predecessor adoption checks preserve complete snapshots and partial-line checkpoints without rebuilding; Pi/OMP keeps its separate invalidation behavior. The captured body reports 267 focused tests, all 1,031 full-suite selections, and make check passing after integration. This read-only review did not execute tests. (Tests/CodexBarTests/CostUsageStoreTests.swift:1008, fa555686e594)
  • Contributor production-path proof: Captured context sourceRevision a8c40f9947326e37c9df261ba7bb53759d29a493626566ef3a7f04e873efc5cc records optimized core harnesses loading an existing SQLite cache and building all three report types over two ranges: 2,169 files and 243,617 exact rows. Repeated measurements report CPU 13.93s to 5.82s, RSS +4.5%, and six byte-identical complete report receipts. The body explicitly attributes these measurements to the original implementation against its original baseline, not the integrated head. Inspected prepared screenshots belong to the separate dashboard issue and are not performance proof. (35a0de60de52)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • brzvsk: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (5 earlier review cycles)
  • reviewed 2026-09-07T14:34:33.151Z sha 29fd828 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T14:58:52.346Z sha 35a0de6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T15:10:35.340Z sha 35a0de6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T15:41:10.842Z sha 35a0de6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T19:26:18.111Z sha fa55568 :: blocked 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: 29fd82887c

ℹ️ 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 thread Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing+CodexResolver.swift Outdated
@brzvsk

brzvsk commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

Head 35a0de6 addresses the P2 oversized-key finding with a 512-byte UTF-8 admission limit before key allocation in both memos. The red-before-green test covers retained bytes, positive/negative lookup correctness, multibyte inputs, and the exact boundary. 272 focused tests, make check, ordinary release build, and the repeated real-corpus candidate proof pass (CPU -58.2%, byte-identical complete outputs). The post-change full local suite is running alongside exact-head CI; the PR body marks that gate in progress rather than reusing the prior head result.

@brzvsk

brzvsk commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review exact head 35a0de6. The independent P2 retained-memory finding is addressed: both memo admission paths reject identifiers over 512 UTF-8 bytes before array allocation, retaining the uncached scalar behavior. A deterministic regression proves both the byte bound and preserved resolution. The updated real-corpus proof has identical complete outputs, CPU -58.2%, and RSS +4.5%. Focused tests (272), make check, and the ordinary release build pass. The post-change full local suite and exact-head CI are running in parallel; the PR body distinguishes those pending gates from completed evidence. Please call out any concrete remaining patch-quality gap rather than inferring that the pending gates have passed.

@clawsweeper

clawsweeper Bot commented Sep 7, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 35a0de60de

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

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 7, 2026
steipete added a commit that referenced this pull request Sep 7, 2026
Codex report construction duplicates model-cost accumulation and scalar/aggregate pricing, and wraps a single catalog load in a stateful resolver. Share those paths while preserving their existing behavior.

Project/session model summaries retain exactly their six cost/token fields, including nil-versus-zero semantics; activity detail remains omitted. Traversal, addition order, and caller sorting stay unchanged. Aggregate pricing still applies custom overlays before rejecting unresolved long-context aggregates. Catalog loading stays at the same point with the same supplied/loaded/empty precedence. The single-use project accumulator method becomes its two existing assignments.

This removes 110 production lines and funds the separate report-pricing CPU fix in #3476. The generated parser identity changes mechanically, so the released 9547dc9d7b7675f6 identity is explicitly adopted without rebuilding native rows or checkpoints. Pi's force-rescan fixture uses the current parser identity; independent predecessor-invalidation coverage remains.

The focused run passed 287 tests across 11 suites covering pricing, overlays, catalog-loading work, model projection, cache adoption, Pi compatibility, fork accounting, project/session behavior and architecture. The final patch additionally checks that a custom zero-price overlay remains authoritative above the aggregate context threshold. `make check` passes and independent review found no actionable P0–P2 findings. The full local suite passed all 1,029 selections across 86 groups on the first attempt, with no retries or timeouts, in 1,276.5 seconds. Exact-head CI run 34148708994 passed both macOS shards and all Linux builds. No live accounts, credentials or user preferences were accessed by these tests. Production output is unchanged, so no user-facing changelog entry is needed for this cleanup.
@steipete
steipete merged commit d85ef49 into steipete:main Sep 7, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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.

2 participants