CodexBar icon indicating copy to clipboard operation
CodexBar copied to clipboard

Bug: Automatic cost refreshes can silently serve a stale scan and pin it for the full token-cost TTL

Open kcharlan opened this issue 4 months ago • 1 comments

Affected version: v0.42.1 (build 103) Component: cost usage scanning (CodexBarCore) Type: correctness / stale data

Summary

CostUsageFetcher.loadDailyReport zeroes the scanner debounce (refreshMinIntervalSeconds) only when forceRefresh is true. Every non-forced fetch — the hourly token-cost timer, the first fetch after app launch, and cost-scope/settings changes — keeps the default 60-second debounce. When such a fetch lands within 60 seconds of any prior scan, the scanner skips file inspection entirely and returns the previous cached report. UsageStore then treats that stale snapshot as fresh for the full tokenFetchTTL (60 minutes), so a single throttled fetch pins out-of-date cost/token totals in the menu bar for up to an hour.

The 60-second debounce is reasonable as a scanner-internal rate limit, but the app-side caller (UsageStore) already rate-limits itself with its own TTL — so at the app layer the debounce never saves work; it only ever manifests as silent staleness that the TTL then amplifies.

Mechanism (code walk, all references at tag v0.42.1)

  1. The force-only gate — Sources/CodexBarCore/CostUsageFetcher.swift:175-184:

    if forceRefresh {
        options.refreshMinIntervalSeconds = 0
    }
    ...
    if forceRefresh {
        resolvedPiOptions.refreshMinIntervalSeconds = 0
    }
    

    The default is refreshMinIntervalSeconds: TimeInterval = 60 (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:29, and identically for the pi-session scanner at Sources/CodexBarCore/PiSessionCostScanner.swift:22).

  2. The throttle skips file inspection entirely — CostUsageScanner.makeCodexRefreshPlan computes (CostUsageScanner.swift:2395-2406):

    let shouldRefresh = options.forceRescan
        || ...
        || refreshMs == 0
        || cache.lastScanUnixMs == 0
        || nowMs - cache.lastScanUnixMs > refreshMs
    

    When shouldRefresh is false, loadCodexDaily bypasses the whole scan block — no directory listing, no file-metadata (size/mtime) checks, no incremental append — and goes straight to buildCodexReportFromCache (CostUsageScanner.swift:2440 and :2590). Rows appended to session JSONL files since the stamped scan are invisible. The Claude scanner has the same gate (CostUsageScanner+Claude.swift:662), as does PiSessionCostScanner (PiSessionCostScanner.swift:103).

  3. The throttle timestamp is cross-process — cache.lastScanUnixMs is persisted in the on-disk cache at ~/Library/Caches/CodexBar/cost-usage/<provider>-v<N>.json (CostUsageCache.swift:20-31). The menu-bar app, the codexbar cost CLI, and any other consumer using the default cache root share it. A scan by another process arms the throttle against the app's next non-forced fetch.

  4. The staleness gets pinned for an hour — UsageStore.refreshTokenUsage (Sources/CodexBar/UsageStore.swift:1508-1517) stamps lastTokenFetchAt[provider] = now before the fetch and gates non-forced refreshes on tokenFetchTTL = 60 * 60 (UsageStore.swift:336). There is no detection that the fetch was served from a throttled cache, and no earlier retry. The hourly timer path is non-forced (UsageStore+TokenRefreshSequence.swift:10-24: startTokenTimer → scheduleTokenRefresh → startTokenRefreshSequence(force: false, scope: .all)), and so is the first post-launch fetch (in-memory lastTokenFetchAt starts empty, but the on-disk lastScanUnixMs survives relaunch).

Reproduction

User-level

  1. Start an active Codex (or Claude Code) session so the session JSONL under ~/.codex/sessions/... is growing.
  2. Run codexbar cost (or otherwise trigger a scan). This stamps lastScanUnixMs in the shared on-disk cache.
  3. Within 60 seconds, launch CodexBar.app (or have a cost-scope/settings change trigger a non-forced fetch).
  4. The app's fetch takes the throttled path and displays totals from step 2's scan. Usage produced after step 2 is missing, and the display does not correct itself until the hourly timer fires again or the user forces a refresh — which is why the symptom presents as "token/cost totals lag until I manually refresh."

Deterministic, test-level

The following test passes with the proposed fix and, by inspection of makeCodexRefreshPlan (both loadTokenSnapshot calls share the same now, so nowMs - cache.lastScanUnixMs = 0 ≤ 60_000 and shouldRefresh is false on the second call), the second assertion fails on stock v0.42.1 with refreshed.daily.first?.totalTokens == 110:

@Test
func `non-forced refresh keeps incremental cost cache current`() async throws {
    // 1. Write a codex session JSONL containing one token_count row (110 total tokens)
    //    into a temp codex home, with a temp cacheRoot.
    // 2. loadTokenSnapshot(provider: .codex, now: day, ...) — non-forced.
    //    #expect(first.daily.first?.totalTokens == 110)   // fresh scan, passes
    // 3. Append a second token_count row to the same file (total becomes 176).
    // 4. loadTokenSnapshot again with the same `now` — non-forced, inside the 60 s window.
    //    #expect(refreshed.daily.first?.totalTokens == 176)
    //    stock v0.42.1: returns 110 (throttled cache); fixed: returns 176
}

(Full runnable version available — it uses only existing test fixtures: a temp CostUsageScanner.Options(codexSessionsRoot:cacheRoot:) and JSONL token_count events.)

Expected vs. actual

  • Expected: a non-forced refresh reflects all usage present in the session logs at fetch time, or at minimum the scanner notices that file metadata changed and performs its (already-implemented) cheap incremental append.
  • Actual: within 60 s of any prior scan by any process, the fetch silently returns the previous report without looking at the filesystem, and the app then displays it as fresh for up to 60 minutes.

Suggested directions (either resolves it)

  1. Zero refreshMinIntervalSeconds for app-driven refreshes (not just forced ones). UsageStore already serializes and TTL-gates its fetches, so the scanner debounce is redundant on this path: set options.refreshMinIntervalSeconds = 0 and resolvedPiOptions.refreshMinIntervalSeconds = 0 unconditionally in CostUsageFetcher.loadDailyReport. The full test suite passes with this change applied to v0.42.1 (634 test selections, 0 failures).
  2. Alternatively, make the throttled path metadata-aware: when within refreshMinIntervalSeconds, still stat the known session files and fall through to the incremental-append path if sizes/mtimes changed. Keeps the debounce for true no-change polls while eliminating the stale window.

Option 1 is a two-line change; the scan itself remains cheap because the incremental cache (keepCachedCodexFileIfFresh / appendCodexFileIncrementIfPossible, CostUsageScanner.swift:2327-2333) already avoids re-reading unchanged files.

kcharlan avatar Jul 12 '26 12:07 kcharlan

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

Summary This is a well-specified current bug: main still allows a non-forced fetch to receive the scanner’s recently cached report and then records that successful result under UsageStore’s one-hour freshness TTL. No current fix or canonical open PR was found, and the bounded source path plus existing temporary-directory fixtures make it suitable for a focused repair.

Reproducibility: yes. The deterministic temporary-session path is high confidence from current source: perform a non-forced snapshot, append a token event, and repeat the same non-forced snapshot inside 60 seconds; the scanner cache gate prevents the second scan. It was not executed because this review must leave the checkout byte-for-byte clean.

Next step The defect is narrowly bounded to the fetcher/scanner freshness contract, has reusable temporary-directory fixtures, and requires no product, configuration, security, or architecture decision.

Review details

Best possible solution:

Give each explicit CostUsageFetcher request a current incremental view of the session files while retaining the scanner’s existing file-level cache optimizations, and lock the contract down with a non-forced append regression test for native and applicable Pi history.

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

Yes. The deterministic temporary-session path is high confidence from current source: perform a non-forced snapshot, append a token event, and repeat the same non-forced snapshot inside 60 seconds; the scanner cache gate prevents the second scan. It was not executed because this review must leave the checkout byte-for-byte clean.

Is this the best way to solve the issue?

Yes, with a boundary check. Updating the existing fetcher/scanner freshness contract and extending the adjacent incremental-cache test is narrower and more maintainable than adding another UsageStore retry or freshness heuristic.

AGENTS.md: found and applied where relevant.

Remaining risk / open question:

  • A blanket removal of scanner debounce affects direct CostUsageFetcher consumers such as CLI cost and serve requests, so the repair should confirm that incremental caching keeps repeated calls acceptably cheap and should avoid changing persisted cache formats or unrelated scheduling.

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

Label changes

Label changes:

  • add P2: The issue can display stale cost and token totals for up to an hour but does not lose source data, crash the app, or block its core runtime.
  • add impact:other: The issue affects correctness and freshness of user-visible usage totals without fitting the owned data-loss, session-state, auth-provider, message, or availability categories.
  • 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: The issue can display stale cost and token totals for up to an hour but does not lose source data, crash the app, or block its core runtime.
  • impact:other: The issue affects correctness and freshness of user-visible usage totals without fitting the owned data-loss, session-state, auth-provider, message, or availability categories.
Evidence reviewed

Acceptance criteria:

  • swift test --filter CostUsageFetcherTests
  • make check
  • make test

What I checked:

  • Force-only debounce bypass remains on main: CostUsageFetcher sets the native and Pi scanner minimum refresh intervals to zero only when forceRefresh is true, leaving every automatic fetch subject to the default debounce. (Sources/CodexBarCore/CostUsageFetcher.swift:175, d57fb5d08696)
  • Scanner can return cached data without file inspection: The Codex refresh plan skips its scan when the persisted last-scan timestamp is within refreshMinIntervalSeconds, after which loadCodexDaily builds the report from the existing cache. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:2396, d57fb5d08696)
  • Successful result receives the one-hour TTL: UsageStore records lastTokenFetchAt before loading, suppresses matching non-forced requests for 60 minutes, and accepts a scanner-cached snapshot as an ordinary successful result. (Sources/CodexBar/UsageStore.swift:1492, d57fb5d08696)
  • Current regression coverage only proves forced refresh: The adjacent incremental-cache test appends a token event but makes the second request with forceRefresh true, so it does not cover the failing automatic path described by this issue. (Tests/CodexBarTests/CostUsageFetcherTests.swift:744, d57fb5d08696)
  • Release and current-main comparison: The force-only CostUsageFetcher gate is unchanged between v0.42.1 and current main; later UsageStore work rejects publication-revision races but cannot distinguish a throttled cache report returned successfully by the scanner. (Sources/CodexBarCore/CostUsageFetcher.swift:175, 3e05988f5c5f)
  • Repository vision supports the repair: VISION.md identifies fast refreshes as a product goal and places clear, bounded bug fixes in the merge-by-default category. (VISION.md:3, d57fb5d08696)

Likely related people:

  • steipete: Recently changed both CostUsageFetcher and UsageStore freshness/publication behavior, and merged the commit containing the current refresh structure. (role: recent area contributor and merger; confidence: high; commits: 917a2165229d, fcac7722c372, e149704a151b; files: Sources/CodexBarCore/CostUsageFetcher.swift, Sources/CodexBar/UsageStore.swift, Sources/CodexBar/UsageStore+TokenRefreshSequence.swift)
  • Yuxin-Qiao: The available history traces the current force-only scanner option handling, token TTL gate, scanner integration, and adjacent tests to the merged change in commit e149704a. (role: introduced current refresh structure; confidence: medium; commits: e149704a151b; files: Sources/CodexBarCore/CostUsageFetcher.swift, Sources/CodexBar/UsageStore.swift, Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.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 12 '26 12:07 clawsweeper[bot]