Skip to content

Align cost cache save overshoot with documented load cap - #2703

Merged
steipete merged 4 commits into
steipete:mainfrom
Yuxin-Qiao:codex/fix-2646-review-followups
Aug 6, 2026
Merged

Align cost cache save overshoot with documented load cap#2703
steipete merged 4 commits into
steipete:mainfrom
Yuxin-Qiao:codex/fix-2646-review-followups

Conversation

@Yuxin-Qiao

@Yuxin-Qiao Yuxin-Qiao commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Summary

Follow-up to the review on #2637's merged fix (#2646, commit 90c6faed0). Addresses all points raised in the review comment and in the ClawSweeper re-review:

  1. dayDate duplicated parseDayKey and skipped calendar normalization — removed the private dayDate helper; previousReportForCatchUp now calls the existing CostUsageScanner.parseDayKey, which normalizes via localGregorianCalendar(matching:) and anchors at noon. A day key like "2026-06-01" now parses to 2026 even when Calendar.current is non-Gregorian (e.g. Buddhist calendar would previously resolve to 1483).
  2. save overshoot invariant now matches the documented load cap — updated the maxCacheLoadBytes doc comment and the guard-fail comment so the behavior matches the contract: save bounds artifacts to maxCacheFileBytes, and when protected entries (resuming sessions, fork parents) cannot be trimmed further it may overshoot only up to the load cap. Anything above the cap is dropped as legacy/foreign.
  3. Weak constant-only test replaced with a real round tripcodex load cap keeps headroom over the save budget with a real save load round trip now exercises save/load and asserts the overshoot artifact is written and readable within the load cap. Also added catch up report honors a non-gregorian system calendar as a regression guard for the parseDayKey fix.
  4. Preserve the preceding producer keys (ClawSweeper P2) — the generated parser hash rotated to d3df003a9bff32af, so both the current-main key (codex:cu:p1cd29792d9ca2b11) and the prior bounded-cache key (codex:cu:p37aedd661c4272a8) were added to compatibleCodexProducerKeys. Upgrading from either preceding build no longer rejects valid local caches or forces a rebuild. current codex cache accepts calendar normalization predecessors covers both keys through default load and loadCodexForMigration with a real save/load round trip.

Also regenerated CodexParserHash.generated.swift (repo requires it after touching Vendored/CostUsage) and updated the hardcoded line anchors in ProviderArchitectureGatekeeperTests for the shifted source.

Real behavior proof (existing local cache upgrade)

Ran an after-fix upgrade check against the existing local Codex cost cache (11.7 MB artifact, 304 session files, 23 days of usage data). The artifact was stamped with the current-main producer key (codex:cu:p1cd29792d9ca2b11) to model the upgrade source, then loaded with this head's default load and loadCodexForMigration:

[UPGRADE-PROOF] sourceArtifactBytes=11665828 sourceFiles=304 sourceDays=23
  loadedFiles=304 loadedDays=23 lastScanUnixMsPreserved=true
  migrationFiles=304 migrationIncompatibleCache=nil
  foreignKeyRefused=true
  • Default load reuses the full artifact: all 304 files and 23 days survive, lastScanUnixMs is preserved — no rebuild.
  • Migration load also reuses it (incompatibleCache == nil).
  • Control: an artifact stamped with a producer key outside the compatibility set is still refused (foreignKeyRefused=true), confirming the allowlist is what grants reuse rather than unconditional acceptance.

Commands run

  • swift test --filter CostUsageCacheTests — 39/39 pass
  • swift test --filter ProviderArchitectureGatekeeperTests — 38/38 pass
  • make test — full suite passes
  • make check — SwiftFormat/SwiftLint clean (0 violations)
  • Scripts/regenerate-codex-parser-hash.sh

Notes

Branch rebased onto current origin/main (005a71f55); PR is mergeable. The calendar reachability for dayDate in the original review was upstream-normalized in the app path (saveCodexCache passes range.calendar, already Gregorian); this change removes the latent bug at the API level anyway, matching the review's recommendation. No behavior change for Gregorian-calendar users.

@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: 8563c2b313

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


enum CodexParserHash {
static let value = "37aedd661c4272a8"
static let value = "c7188afe30460be4"

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 Keep the prior parser hash compatible

When upgrading from the immediately preceding revision, existing Codex caches carry codex:cu:p37aedd661c4272a8, but this generated change makes the expected key codex:cu:pc7188afe30460be4 while compatibleCodexProducerKeys still contains only p843ca061c36bbea1. Consequently both load and loadCodexForMigration reject every cache from the prior version and initiate a potentially lengthy bounded rebuild, even though this commit only changes save-budget documentation and uses the existing Gregorian day-key parser when constructing a catch-up report rather than changing persisted parsing totals or layout. Add the prior producer key to the compatibility set when rotating this hash.

Useful? React with 👍 / 👎.

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

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed August 6, 2026, 5:10 AM ET / 09:10 UTC.

ClawSweeper review

What this changes

This PR corrects Codex cost-cache compatibility and calendar handling, documents allowed save overshoot, and adds focused cache regression tests.

Regression provenance

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

Merge readiness

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

The prior producer-key blocker is resolved and the patch appears correct, but external-PR policy still requires after-fix proof from an existing cache upgrade before merge.

Priority: P2
Reviewed head: fdc02fc8311df05fe986779806fa2cf2472d44ac

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused patch resolves the earlier cache-key finding, but real upgrade behavior remains unproven.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The PR provides focused temporary-cache XCTest output, but not after-fix proof from an existing local cache upgrade; add a redacted terminal transcript before merge. 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 PR provides focused temporary-cache XCTest output, but not after-fix proof from an existing local cache upgrade; add a redacted terminal transcript before merge. 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 4 items Predecessor compatibility: The PR accepts both the current-main and prior bounded-cache producer keys in normal and migration loads.
Calendar normalization: The reused parser normalizes day keys through a Gregorian calendar and anchors them at noon, avoiding non-Gregorian year interpretation.
Focused coverage: New tests round-trip both predecessor keys through normal and migration loading, and cover the overshoot and non-Gregorian paths.
Findings None None.
Security None None.

How this fits together

CodexBar persists parsed Codex session usage in a local cost cache. On refresh, cache size and producer keys determine whether existing usage data is reused or rebuilt.

flowchart LR
A[Codex session files] --> B[Cost usage scanner]
B --> C[Local cost cache]
C --> D[Size and producer checks]
D --> E[Usage refresh]
E --> F[Menu bar usage]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR provides focused temporary-cache XCTest output, but not after-fix proof from an existing local cache upgrade; add a redacted terminal transcript before merge. 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) - The new allowlist governs reuse of existing local caches; the supplied temporary-cache tests do not prove that a real pre-upgrade artifact is reused without a rebuild.
  • Complete next step (P2) - No mechanical repair remains evident; real after-fix upgrade proof is needed from the contributor before merge.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production versus test delta production +16/-24, tests +129/-6 The functional update is small relative to focused regression coverage across the cache contract.

Merge-risk options

Maintainer options:

  1. Add real upgrade evidence (recommended)
    Provide redacted terminal output from an existing local Codex cache upgraded to this revision, showing normal and migration loading reuse it without a rebuild.
  2. Accept test-only evidence
    Merge based on the focused synthetic round trips while accepting that an existing-user artifact was not exercised.

Technical review

Best possible solution:

Preserve the narrow parser reuse and predecessor allowlist, supported by one redacted real upgrade run that shows an existing Codex cache is accepted after installing this revision.

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

Yes, at source level: a persisted predecessor-key cache exercises clear normal and migration load paths, though this read-only review did not run the test.

Is this the best way to solve the issue?

Yes: reusing the existing normalized day-key parser and retaining compatible producer keys is narrower and safer than a cache schema migration.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The PR affects bounded local-cache reuse and upgrade behavior with limited but real user impact.
  • merge-risk: 🚨 compatibility: A parser producer-key change can otherwise cause valid existing Codex caches to be rejected after upgrade.
  • 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 PR provides focused temporary-cache XCTest output, but not after-fix proof from an existing local cache upgrade; add a redacted terminal transcript before merge. 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:

  • Yuxin-Qiao: Authored the merged bounded-cache implementation that introduced this compatibility surface. (role: original cache-bounding contributor; confidence: high; commits: 90c6faed00da; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageCache.swift)
  • steipete: Authored the current-main provider-special-case refactor that touched the same cache implementation and regenerated its parser hash. (role: recent adjacent contributor; confidence: medium; commits: 61fbe9fac507; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageCache.swift, Sources/CodexBarCore/Generated/CodexParserHash.generated.swift)

Rank-up moves

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

  • Add redacted terminal output showing an existing pre-upgrade Codex cache loads normally after upgrading to this revision.

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 (4 earlier review cycles)
  • reviewed 2026-08-06T07:55:08.451Z sha 8563c2b :: needs real behavior proof before merge. :: [P2] Preserve the preceding parser hash as compatible
  • reviewed 2026-08-06T08:38:00.580Z sha 8563c2b :: needs real behavior proof before merge. :: [P1] Regenerate the parser hash after rebasing | [P2] Accept the preceding compatible cache key
  • reviewed 2026-08-06T08:52:34.815Z sha 8a24f9f :: needs real behavior proof before merge. :: [P1] Rebase and preserve the current cache producer key
  • reviewed 2026-08-06T08:56:03.480Z sha 8a24f9f :: needs real behavior proof before merge. :: [P1] Preserve the rebased main cache producer key

@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the P2: codex:cu:p37aedd661c4272a8 is now in compatibleCodexProducerKeys and the upgrade-load regression test covers default load plus loadCodexForMigration with a real save/load round trip. PR body now includes the runtime proof.

@clawsweeper

clawsweeper Bot commented Aug 6, 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:

@Yuxin-Qiao
Yuxin-Qiao force-pushed the codex/fix-2646-review-followups branch from 8a24f9f to fdc02fc Compare August 6, 2026 09:06
@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Rebased onto current main (005a71f55) and added both preceding producer keys (p1cd29792d9ca2b11, current main; p37aedd661c4272a8, prior bounded-cache build) to compatibleCodexProducerKeys. The upgrade regression test now round-trips both keys through default load and loadCodexForMigration. PR body has the runtime proof and command outputs.

@clawsweeper

clawsweeper Bot commented Aug 6, 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:

@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added the real upgrade proof: took the existing local Codex cost cache (11.7 MB, 304 session files, 23 days), stamped it with the current-main producer key, and loaded it with this head via default load and loadCodexForMigration. Both reuse the full artifact (loadedFiles=304 loadedDays=23 lastScanUnixMsPreserved=true migrationIncompatibleCache=nil); a foreign-key control artifact is refused. Details in the PR body.

@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@steipete
steipete merged commit 6a91900 into steipete:main Aug 6, 2026
1 check passed
@steipete

steipete commented Aug 6, 2026

Copy link
Copy Markdown
Owner

Landed. Verified before merge: confirmed the (256 MiB, 320 MiB] overshoot band is reachable only via protected entries and that this PR’s alignment is documentary — the never-persist-refusable invariant from #2646 is untouched and now pinned by a real save/load round trip. The calendar fix is a genuine latent bug (day keys misresolved under non-Gregorian system calendars). Maintainer fix pushed before merge (589e89d5a): the producer-compat list was missing two shipped predecessor hashes (6c0f1f…, aa27d2…), which would have forced pointless rebuilds for post-#2646/pre-#2691 builds; added both, regenerated the hash, extended the compat regression to all four keys. CostUsageCacheTests 39/39, gatekeeper 38/38, autoreview clean. Thanks @Yuxin-Qiao!

steipete added a commit that referenced this pull request Aug 8, 2026
…r (refs #2760) (#2767)

* fix: restore JSON-cache retention semantics lost in the SQLite cutover (refs #2760)

Semantics-parity audit of the CostUsageCache -> CostUsageStore migration
found four behaviors the cutover dropped:

- Retention pruned only the typed discovery columns while the scanner
  round-trips discovery through the opaque payload, so deleted files
  resurfaced on the next load; prune now updates both in lockstep and
  resets cursors/isComplete like the old cache did.
- The row budget deleted the oldest files regardless of window; the old
  entry budget never sacrificed in-window or recently active files (the
  byte budget remains the only authority that may).
- Fork-parent protection ignored the lineage-only dependency key and a
  stale parent survived when its only referencing child was pruned in
  the same pass; candidates now honor the dependency key and iterate to
  a fixpoint.
- Out-of-window files with an in-window mtime (active sessions with
  unscanned rows) were deletable; they are protected again.

saveCodexCache budgets are injectable for tests, restoring pins for
previous-report preservation across trims and the non-Gregorian
catch-up report (#2703), plus strip/compaction coverage.

* docs: changelog for the SQLite retention semantics parity fixes (refs #2760)
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.

2 participants