CodexBar icon indicating copy to clipboard operation
CodexBar copied to clipboard

Codex widget token snapshot can stay stale indefinitely while cost catch-up remains pending

Open zhulijin1991 opened this issue 3 months ago • 5 comments

Summary

On the official signed CodexBar 0.55.1 (130), the Codex widget can keep a fresh outer snapshot timestamp and current quota state while its token/cost rows remain more than an hour old.

This is not the fixed one-hour TTL case from #2103. The persisted cost report can continue advancing, but the running app does not publish a new token snapshot while Codex cost catch-up remains pending.

Sanitized runtime evidence

  • Global refresh frequency: one minute.
  • widget-snapshot.json.generatedAt advances on schedule.
  • The Codex entry's tokenUsage.updatedAt remains more than 60 minutes old.
  • The bundled CLI and persisted report advance while the visible widget remains unchanged.
  • Catch-up remains pending at a normalized N-1/N state while an active session tail continues to change.
  • When a newer widget snapshot is supplied externally, the app rewrites it from its stale in-memory token snapshot during the next persistence cycle.

No account identifiers, usernames, absolute paths, exact usage values, credentials, device identifiers, session IDs, or screenshots are included.

Current source behavior

Verified on current main at e02e78d98274832305a72f4086bf4630edf83f77:

  • runCodexCostCatchUp stays inside while status.pending.
  • publishStableCodexCostCatchUpSnapshot is called only after that loop exits.
  • The regression test explicitly expects bounded catch-up to publish only the final stable snapshot.
  • Widget persistence can continue using lastQueuedWidgetSnapshot, so a fresh outer snapshot does not imply fresh token data.

A minimal source-level reproduction is to keep returning distinct, progressing catch-up status keys with pending: true, return newer token snapshots from the loader, and inspect the publication revision before cancelling the task. The revision does not advance beyond the foreground snapshot because no intermediate catch-up snapshot is published.

Expected behavior

A continuously active Codex session should not prevent today's token/cost rows from being published indefinitely. Historical catch-up may remain incomplete, but recent active-file progress should still become visible with an honest token-specific timestamp.

Suggested direction

  • Separate recent active-file tail refresh from low-duty-cycle historical catch-up.
  • While catch-up remains pending, publish a rate-limited safe checkpoint when the persisted report has advanced.
  • Keep the final stable publication for full reconciliation, including legitimate downward corrections.
  • Add a regression test where active input keeps catch-up pending while checkpoint data advances.

Related

  • #1964 made token-row age visible but did not refresh stale token data.
  • #2103 / #2282 aligned token refresh cadence but did not cover publication starvation while catch-up stays pending.

zhulijin1991 avatar Aug 27 '26 15:08 zhulijin1991

Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed August 27, 2026, 11:06 AM ET / 15:06 UTC.

Summary Keep open: current main has a source-reproducible starvation path where progressing pending catch-up never reaches the sole token-publication call, leaving widget token/cost rows stale despite fresh outer snapshots.

Reproducibility: yes. —current source provides a high-confidence deterministic path: keep returning distinct pending catch-up states while the token loader advances, then observe that no publication occurs before cancellation.

Next step The failure is source-proven, bounded to existing Codex token publication behavior, and has clear seams for one focused regression repair.

Review details

Best possible solution:

Publish a rate-limited active-tail checkpoint with an honest token timestamp while retaining the final stable publication for complete-history reconciliation.

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

Yes—current source provides a high-confidence deterministic path: keep returning distinct pending catch-up states while the token loader advances, then observe that no publication occurs before cancellation.

Is this the best way to solve the issue?

Yes—the narrowest maintainable repair is a bounded checkpoint path that preserves established history, rather than changing the configured refresh cadence or weakening completion reconciliation.

AGENTS.md: found and applied where relevant.

Remaining risk / open question:

  • A checkpoint must not overwrite established historical totals with an incomplete scan or trigger unbounded WidgetKit timeline reloads.

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

Label changes

Label changes:

  • add P2: Stale token and cost rows affect normal widget monitoring but do not block the app or risk user data.
  • add impact:ux-friction: The widget presents fresh quota state alongside stale token/cost information, creating avoidable confusion and a CLI-only workaround.
  • add issue-rating: 🦞 diamond lobster: Current issue advisory state selects this label.
  • add clawsweeper:source-repro: Current issue advisory state selects this label.
  • add clawsweeper:queueable-fix: Current issue advisory state selects this label.
  • add clawsweeper:fix-shape-clear: Current issue advisory state selects this label.

Label justifications:

  • P2: Stale token and cost rows affect normal widget monitoring but do not block the app or risk user data.
  • impact:ux-friction: The widget presents fresh quota state alongside stale token/cost information, creating avoidable confusion and a CLI-only workaround.
Evidence reviewed

Acceptance criteria:

  • swift test --filter UsageStoreCodexCostCatchUpTests
  • make test
  • make check

What I checked:

Likely related people:

  • steipete: Direct blame of the catch-up worker, widget persistence path, and existing catch-up test attributes the available history boundary to Peter Steinberger; current main is also authored by Peter Steinberger. (role: recent area contributor; confidence: medium; commits: 10587234b54e, e02e78d98274; files: Sources/CodexBar/UsageStore+CodexCostCatchUp.swift, Sources/CodexBar/UsageStore+TokenCost.swift, Sources/CodexBar/UsageStore+WidgetSnapshot.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 Aug 27 '26 15:08 clawsweeper[bot]

The source supports a publication-starvation path, but this needs more than periodically calling the existing cached loader. Both the scanner and cached loader deliberately return the last complete report while catch-up is pending; the foreground publisher also protects established history from incomplete replacement. The background task publishes only after completion. I have reviewed these paths, not yet executed a reproduction of your device's behavior.

There is a narrower direction worth testing before adding partial-history checkpoints: finish a finite captured file prefix, publish that completed result, then scan later growth in the next cycle. Today each resume updates its target to the latest EOF, and even the final publication helper starts another scan. A continuously growing ordinary file can therefore keep moving the completion boundary. Any repair must preserve record/fork boundaries, later tail delivery, account/window isolation, stale-writer protection, and legitimate downward corrections; simply publishing the larger of old and partial totals would be wrong.

One timing clarification: current app code has a 15-minute minimum token-scan interval, independently of faster quota refresh. The documentation's 60-second statement is stale. Automatic catch-up also has deliberately low duty-cycle limits. That can explain long finite delays, though it does not eliminate the progressing-pending publication defect. I am not proposing to undo those energy limits as a side effect.

For the CLI/report observation, could you clarify which report interface/artifact advanced and the CLI flags used, including history days and whether Pi was included? Please report only whether the app and CLI used the same home/cache, timezone and window—not actual paths or identities—and whether catch-up became complete during the CLI read. With the same still-pending native previous report, the CLI loader also selects that old native report; a raw working-store aggregate and a published complete report are different things.

This remains open. The next useful proof is a temporary-file scanner → fetcher → publication/widget regression with a growing tail, followed by final reconciliation; no real account data is needed for that test.

steipete avatar Aug 27 '26 15:08 steipete

I reproduced the finite-prefix failure mode you described on current main (41c53c3) with a temporary Codex home/cache and no account data.

An initial bounded scan left one JSONL file pending. Before each of three 1 KiB resume passes, I appended eight complete token_count records to that same file. The persisted codexScanTargetSize increased to the new EOF on every pass, while the token publication revision stayed unchanged and the captured widget token snapshot remained at its initial timestamp and totals. After I stopped appending, the same scanner → fetcher → UsageStore → widget path drained the file, emitted exactly one new token publication/widget save with higher totals, and ended with codexScanComplete == true and the target equal to the final file size. The focused suite passed 11/11 (swift test --filter UsageStoreCodexCostCatchUpTests). The setup used a 30-day window, the same temporary home/cache throughout, and excluded Pi.

That supports capturing a finite prefix as the publication boundary, then treating later growth as the next cycle, rather than publishing an incomplete-history checkpoint. I left product code untouched because the regression still needs to lock the record/fork boundary, later-tail delivery, scope/stale-writer behavior, and downward corrections you called out.

kiranmagic7 avatar Aug 29 '26 05:08 kiranmagic7

Thanks — clarifying the original CLI/report observation and tightening the wording:

  • The relevant CLI reads were CodexBarCLI cost --provider codex --days 30 --format json --pretty and the same command with --refresh.
  • There was no CODEX_HOME override. The running app and bundled CLI used the same default home/cache, local timezone, and 30-day window.
  • I did not pass --provider-native-only, so the CLI aggregate used its default behavior and could include supported Pi/OMP mirrors.
  • The artifact observed advancing was the SQLite working store (day/file aggregates) while the outer widget snapshot timestamp also refreshed; this was not evidence that the published complete native report advanced.
  • Catch-up did not become complete during the relevant CLI read: historyCoverageIsEstablished remained false and persisted scan metadata remained catchUpPending: true.

So the original CLI/report sentence should be read as working-store progress during a still-pending catch-up, not as the cached loader selecting a newer complete report. The temporary-file finite-prefix reproduction above is the cleaner proof of the publication-starvation path.

zhulijin1991 avatar Aug 29 '26 13:08 zhulijin1991

A bounded follow-up landed in #3279 (b4e670c1059fb8842583000ae6b3560336b4cd85): once catch-up has actually completed, the final publication now reads validated caches rather than starting another scan. It preserves the actual scan timestamps and prior totals when completed native or Pi/OMP history is unavailable.

The new synthetic JSONL → SQLite → store → widget regression reproduced the extra scan, later-tail consumption, and timestamp change before the fix, then passed afterward. All 81 local test groups passed without retries; exact-head CI and all nine PR checks passed.

Keeping this issue open: this does not fix continuously growing logs that never reach completed catch-up. The finite-prefix completion boundary remains separate work; no periodic partial-total publication or scan-budget change was introduced. This change is on main, not in a new release. Thanks for the report and clarification.

steipete avatar Aug 30 '26 07:08 steipete