CodexBar icon indicating copy to clipboard operation
CodexBar copied to clipboard

Codex local cost scanner assigns resumed-session usage to the original day, leaving Today at $0

Open Pjhhhhh opened this issue 3 months ago • 12 comments

Summary

When a Codex rollout is resumed on a later calendar day, CodexBar can scan the appended file completely but does not create a daily cost row for the later day. The menu therefore shows Today $0.00 despite the active session continuously emitting token_count events.

This is separate from quota fetching: OAuth quota refresh remains exact and current.

Environment

  • CodexBar 0.56.1 (132), official Homebrew cask
  • macOS
  • Codex CLI resumed long-running rollouts

Reproduction

  1. Start a Codex rollout on day A.
  2. Resume that rollout on day B and continue using it.
  3. Confirm that the rollout file grows and includes current-day token_count events with input, cached-input, output, and reasoning token fields.
  4. Run CodexBarCLI cost --provider codex --format json --refresh.
  5. Open the CodexBar menu.

Actual behavior

  • The scanner records the file as fully parsed (parsed_bytes == file size, scan_complete = 1).
  • The local coverage for that rollout remains bounded by day A, and the daily aggregate has no row for day B.
  • The forced CLI cost report and the menu snapshot both show zero tokens and $0.00 for day B.
  • Updating from 0.56.0 to 0.56.1 did not change this behavior.

Expected behavior

New token_count events appended after resuming a rollout should be attributed to their event timestamp in the current local day. A forced cost scan should produce a non-zero day-B report and the menu should publish that result.

Notes

  • No account data, session content, paths, identifiers, token totals, or cost values are included here.
  • This looks adjacent to cost catch-up/snapshot publication, but the persisted daily aggregation itself is already missing the current day before the menu renders it.

Pjhhhhh avatar Aug 31 '26 01:08 Pjhhhhh

Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed August 30, 2026, 9:37 PM ET / August 31, 2026, 01:37 UTC.

Summary Keep open: the report is a concrete local-cost accounting bug, but current source already attributes token events by their own timestamps; the missing cross-calendar same-file regression leaves the reported persisted-cache path unresolved, and this repository’s generic profile does not permit automatic closure.

Reproducibility: unclear. The supplied scenario is specific, but no sanitized rollout fixture or cache state is available; current source appears to use each event timestamp and lacks an exact cross-day regression.

Ways to help us reproduce this

  • Add a screenshot or short recording showing the behavior.
  • Add expected vs actual behavior.
  • Share version, platform, channel/provider, and relevant config details.

Next step A single fixture-driven investigation can establish whether the released incremental cache path drops a later-day row; no product decision is needed.

Review details

Best possible solution:

Add a cross-calendar regression that scans a day-A rollout, appends day-B token events, and verifies the persisted ledger, CLI snapshot, and menu-facing token snapshot before changing scanner logic.

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

Unclear. The supplied scenario is specific, but no sanitized rollout fixture or cache state is available; current source appears to use each event timestamp and lacks an exact cross-day regression.

Is this the best way to solve the issue?

Unclear. Event-time attribution is already the intended current-source path, so a focused regression should isolate any cache or deduplication failure before modifying behavior.

AGENTS.md: found and applied where relevant.

Remaining risk / open question:

  • The report may expose a cache, row-deduplication, or released-build condition not represented by the current same-day append coverage.

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

Label changes

Label changes:

  • add P2: A detailed report describes incorrect local daily cost reporting with limited blast radius.
  • add impact:data-loss: Current-day local usage and cost aggregation can be silently omitted from the persisted daily ledger.
  • add issue-rating: 🦪 silver shellfish: Current issue advisory state selects this label.

Label justifications:

  • P2: A detailed report describes incorrect local daily cost reporting with limited blast radius.
  • impact:data-loss: Current-day local usage and cost aggregation can be silently omitted from the persisted daily ledger.
Evidence reviewed

Acceptance criteria:

  • swift test --filter CostUsageScannerTests
  • make test
  • make check

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
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 31 '26 01:08 clawsweeper[bot]

Additional sanitized local evidence

I reproduced this after upgrading the official Homebrew cask from 0.56.0 (131) to 0.56.1 (132) on macOS. The provider is Codex, with a resumed long-running Codex CLI rollout.

Expected vs actual

Check Expected Actual
Appended current-day token_count events A new current-day local-cost row No current-day row
CodexBarCLI cost --provider codex --format json --refresh Non-zero current-day tokens/cost Empty current-day result
Menu token snapshot Current-day tokens/cost sessionTokens = 0, sessionCostUSD = 0

Scanner-state evidence

  • The active resumed rollout file grows while the session is used.
  • Its appended events include token_count with input, cached-input, output, and reasoning fields.
  • The persisted scanner record says parsed_bytes == file size and scan_complete = 1 after a forced refresh.
  • Despite that, its coverage range remains on the rollout’s original calendar day; the aggregate ledger has no row for the current calendar day.
  • Historical rows remain present, so this is an omitted later-day row rather than a cleared report.

Controls

  • OAuth quota refresh succeeds with dataConfidence = exact; this is not a connectivity or authentication failure.
  • The menu process has the expected proxy environment.
  • A forced rescan reproduces the omission, so clearing or waiting on the menu snapshot does not explain it.

I cannot share a raw rollout or cache database because they contain private prompts and account telemetry. I can test a small maintainer-provided fixture or diagnostic build and report only the resulting pass/fail/day-row state.

Pjhhhhh avatar Aug 31 '26 01:08 Pjhhhhh

Thanks for the detailed, privacy-conscious report. I tested the ordinary resumed-session path using fabricated data: complete a day-A scan, append day-B events to the same file/inode, reopen the same SQLite store, then read the cached menu-facing snapshot. I covered normal and CLI-style forced refresh in UTC and a local-midnight case where the UTC date itself does not change.

All four cases produced the correct later-day row before any scanner change: the ledger retained the original day, stored the new input/cache/output/reasoning classes, and reported 66 synthetic current-day tokens with a positive unrounded cost. An unchanged repeat did not double-count. This does not reproduce or disprove the omission you observed on 0.56.1, so I am keeping this issue open.

The investigation did expose a separate bug: cached report merging discarded reasoning/model details and coverage metadata even though SQLite retained them. #3307 repairs that shared merge step; it does not claim to repair a missing day-B ledger row. Its synthetic scan/cache fixture is available for inspection. The focused tests passed; the full suite and hosted CI are still running. No new release is being announced.

No raw rollout or database is needed. Could you confirm these shape-only details?

  • Does the event timestamp use a trailing Z or a numeric offset, and which cost-history time zone is selected? A fabricated timestamp with the same format is sufficient.
  • Does the rollout metadata contain forked_from_id or a subagent source marker? Presence/absence is enough; please omit actual identifiers.
  • Across the resume, do cumulative total_token_usage counters continue growing or reset, and is last_token_usage present? No actual totals are needed.

One clarification for the control: CLI --refresh bypasses the scan debounce; it does not discard the existing ledger and rebuild every file. There is no need to clear your history, change account permissions, or share prompts to continue this investigation.

steipete avatar Aug 31 '26 04:08 steipete

Confirmed from the affected resumed rollout on CodexBar 0.56.1 (shape-only, no raw rollout/database data):

  • token_count event timestamps use a trailing Z (UTC). The selected cost-history bucket time zone is Asia/Shanghai.
  • The rollout has no forked_from_id and no per-rollout source marker identifying it as a subagent rollout.
  • Across the resumed period, total_token_usage is not monotonic: it resets rather than continuing to grow. last_token_usage is present on the token_count events checked.

I did not inspect or share prompts, raw identifiers, raw token values, or the cache database.

Pjhhhhh avatar Aug 31 '26 04:08 Pjhhhhh

Thanks — the counter reset is the missing discriminator. I reproduced the reported persisted state on main at 7661b700 using entirely fabricated data: trailing-Z timestamps across midnight in Asia/Shanghai, no fork/subagent metadata, and last_token_usage present.

The temporary diagnostic completed a day-A scan, appended two day-B events to the same file/inode, reopened the SQLite store, and read the cached menu-facing snapshot. It covered both normal and forced refresh:

Synthetic counter sequence Persisted result Today
Cumulative counters keep growing Both days retained; three usage rows; EOF complete 132 tokens, positive unrounded cost
Cumulative counters reset below the previous baseline Original day retained; one usage row; EOF complete; coverage ends on day A 0 tokens, $0

For reproducibility, the fabricated [input, cached input, output, reasoning output] vectors were day A total/last [1000, 200, 100, 40] at 2026-08-29T15:59:00Z; reset totals [60, 20, 6, 3] and [120, 40, 12, 6] at 16:01:00Z and 16:01:05Z, each with last [60, 20, 6, 3]. The growing control instead used totals [1060, 220, 106, 43] and [1120, 240, 112, 46]. Repeated refreshes were stable. All four reset/control cases and the four existing ordinary cross-day cases passed their diagnostic assertions. No real credentials, rollout, or database were accessed; this was a temporary investigation, not a newly committed accounting fix.

The event is suppressed before day attribution: a sufficiently deep cumulative drop activates the interleaved-counter protection, which caps last_token_usage by a zero contained delta below the already-counted baseline. The file cursor still advances. This explains the missing new-day row without requiring a timestamp or SQLite publication bug.

This is a real limitation, but the current containment contract explicitly accepts genuine reset undercounting to prevent replayed/interleaved counters from multiplying costs. Absence of fork metadata, a new turn, or a new calendar day does not by itself establish a safe new accounting epoch. A repair needs a reliable reset/lineage boundary with evidence that it does not re-count replayed usage; simply adding every nonzero last would undo that protection.

Keeping this open with a reproduced reset-path diagnosis. No history clearing, permission changes, or raw private data are needed. The separate report-detail fix #3307 has now landed, but does not fix this omitted-row case.

steipete avatar Aug 31 '26 05:08 steipete

Additional local reproduction on CodexBar 0.56.6 / macOS Apple Silicon, consistent with the counter-reset diagnosis in https://github.com/steipete/CodexBar/issues/3303#issuecomment-5474236381.

This case occurs within a single calendar day, so a day boundary is not required. The rollout has no forked_from_id or subagent source marker. After a continuation boundary, event_msg/token_count.info.total_token_usage restarts from the new request's usage while last_token_usage remains populated. The scanner reaches EOF and reports completion, but accepted usage stops before the reset. CLI --refresh does not recover it; this was not treated as a cold-cache rebuild.

Independent accounting check

For a frozen cutoff in this one local rollout:

Measurement Per-request ledger CodexBar SQLite usage rows
Requests / accepted rows 239 96
Input + output tokens 51,027,984 12,691,110

The difference is 38,336,874 tokens (75.13%). Cached input is included in input, and reasoning output is included in output; neither subset was added again. This is a local token-accounting comparison, not an official billing claim or a cost-percentage estimate.

The same file contains token_usage_record entries with response_id, usage, and thread_token_usage. All 239 response IDs are distinct. Summing each record's usage reconciles exactly with that record's thread_token_usage at every step; this ledger stays monotonic across the point where the older token_count cumulative counters reset. Actual identifiers and conversation content are omitted.

Source-level replay and minimal synthetic case

The unmodified accounting helpers and CodexSnapshotAccumulator were extracted from the v0.56.6 CostUsageScanner.swift, compiled with minimal supporting type definitions, and replayed offline:

  • Original token_count snapshots: 96 accepted events / 12,691,110 tokens, matching all four input/cache/output/reasoning totals in the live SQLite store.
  • The same requests represented by their ledger usage and continuous thread_token_usage: 239 accepted events / 51,027,984 tokens.

This tests the original Swift accounting functions, not a rebuilt full application or an implemented ledger parser.

A three-event synthetic example also reproduces the omission. Vectors are [input, cached input, output, reasoning output]; these represent three distinct new requests, with a cumulative-counter reset before event 2:

Event last_token_usage total_token_usage
1 [1000, 900, 100, 50] [1000, 900, 100, 50]
2 [200, 180, 20, 10] [200, 180, 20, 10]
3 [1500, 1400, 20, 10] [1700, 1580, 40, 20]

Expected input + output: 2840. Original accumulator result: 1100, with only event 1 accepted.

Event 2 is suppressed by post-reset containment. Event 3 exposes an additional detail: although input and cached-input totals exceed the old watermark, output is still below it. codexLooksLikeStaleRegression can consequently classify the whole new snapshot as stale via its aggregate threshold. In the frozen real stream, the replay classified 45 events as zero contained deltas and 100 as stale regressions, plus two ordinary exact-repeat suppressions.

Potential ledger compatibility path

The scanner's branch for lines containing "usage" requires obj["type"] == nil, then returns. A typed token_usage_record therefore is not consumed through this branch. These request records provide additional identity and accounting evidence that the old cumulative snapshots lack.

Supporting this format would still need ownership-aware request deduplication and reconciliation with legacy token_count rows, so the two formats do not double-count the same requests or copied fork history. This is a possible repair direction, not a proposal to disable the existing replay protection or blindly sum all nonzero last_token_usage values.

The complete scanner source was byte-identical between v0.56.6, v0.56.7, and main at 170a4d41c6d69e2bb25daac4fb088a92de2f9bc4 when checked. No application, original rollout, or live database was modified during this investigation. No private rollout, database, prompts, response text, local paths, account details, or real request/session identifiers are attached.

BUKOWSKIREAL avatar Sep 07 '26 14:09 BUKOWSKIREAL

Follow-up: undercount still present in 0.56.8 after derived-cache rebuild

Read-only follow-up on CodexBar 0.56.8 (139), macOS Apple Silicon, to the September 7 reproduction above.

For a fixed, fully parsed prefix of the same affected single-day rollout, an independent comparison now gives:

Measurement Per-request token_usage_record ledger Current CodexBar SQLite aggregates
Requests / accepted rows 303 143
Input + output tokens 61,956,631 21,881,571
Missing input + output tokens — 40,075,060

All 303 ledger response IDs are unique. Summing each request's usage matches its thread_token_usage at every step. Cached input and reasoning output are subsets, not additional tokens in the totals above. The affected file is marked fully scanned; overall scan metadata also reports 96/96 files complete, processed bytes equal total bytes, and catchUpPending = false. This is not merely unfinished history catch-up.

Important cache-history disclosure

After the earlier diagnosis, I had applied a scoped manual repair to this session's derived SQLite statistics, adding exactly 40,075,060 missing tokens. The source rollout was not changed, and this did not fix the scanner. A retained pre/post-repair backup confirms that correction.

The current deficit is exactly that same amount. macOS unified logs contain three September 8 messages of the form:

cost-usage store rebuilt (count 1): open failed: incompatibleSchema

This supports recurrence of the known undercount after the derived cache was rebuilt. I am not asking CodexBar to preserve manually edited cache rows, nor claiming that every upgrade rebuilds the cache or that the 0.56.7 → 0.56.8 upgrade specifically caused these rebuilds. The underlying issue is that rebuilding from unchanged source data still produces the reset-path undercount.

Release-source check

The complete released CostUsageScanner.swift is byte-identical between v0.56.7 and v0.56.8, with SHA-256:

429a47efdc5ead86ab9ea12e58f5c8404f183f2a1037b87e572ecea504fb345c

This also matches the v0.56.6 scanner checked in the earlier reproduction. The current live cache's parser hash matches the generated v0.56.8 hash (9547dc9d7b7675f6). The earlier synthetic reset fixture and request-ledger reconciliation remain relevant; this follow-up does not claim a new scanner fix or a full-app synthetic reproduction on 0.56.8.

The requested fix remains safe reset/request-ledger accounting with replay/fork deduplication preserved, rather than another cache-only correction. These figures concern local token accounting and API-rate estimates, not provider billing or subscription quota. No private rollout, database, prompts, local paths, account details, or real session/request identifiers are attached.

BUKOWSKIREAL avatar Sep 09 '26 06:09 BUKOWSKIREAL

Reproduction on Linux with CLI 0.57.0: all post-reset usage is dropped

Read-only reproduction on CodexBar CLI 0.57.0 (Linux x86_64, NixOS), Codex OAuth account, plan prolite. Every earlier report in this thread runs on macOS Apple Silicon and stops at 0.56.8, so this adds a second platform and the current release. The counter-reset diagnosis holds, and I can pin the exact cut-off event.

Numbers for 2026-09-08

Source Input Output Cached input Total
codexbar cost --format json --json-only --days 7 73,837,414 247,746 68,190,208 74,085,160
ccusage codex daily --json 7,695,727 631,817 173,154,560 181,482,104
Raw last_token_usage ledger, all entries dated 2026-09-08 180,850,287 631,817 173,154,560 182,779,084

CodexBar reports $25.32 for the day, ccusage reports $209.14. The ledger agrees with ccusage to the token: 7,695,727 + 173,154,560 = 180,850,287, and the output figure matches exactly. The remaining 1,296,980 in my last column is reasoning_output_tokens, which the total_tokens field carries but the other two rows do not break out.

Note that CodexBar folds cached input into its inputTokens, so its non-cached input is 73,837,414 - 68,190,208 = 5,647,206 against 7,695,727 in the ledger.

The cut-off event

1,408 token_count events carry a 2026-09-08 timestamp. They sit in two places:

  • 532 events in files under sessions/2026/09/08/, summing to 65,663,446 tokens
  • 876 events in a single file under sessions/2026/09/07/, summing to 117,115,638 tokens

In that one file, payload.info.total_token_usage.total_tokens drops at 2026-09-08T05:48:24.797Z from 103,992,737 to 109,997. All 876 of its September 8 events fall on or after that drop, none before it. A second drop follows later in the same file.

65,663,446 + 117,115,638 = 182,779,084, which closes against the ledger row above. CodexBar's 74,085,160 covers the day directory plus roughly 8.4M from elsewhere, and none of the 117M behind the reset.

Why the file-date bucketing in #3420 is not what I am seeing

I traced the scanner with strace -f -e trace=openat against an empty XDG_CACHE_HOME. For --days 7 it opens every rollout file present on disk for the window, including all 45 files in the 2026/09/07 directory that holds the truncated session:

2026/09/05:  1 of  6 files
2026/09/06: 51 of 57 files
2026/09/07: 45 of 45 files
2026/09/08: 12 of 12 files
2026/09/09: 24 of 24 files

So the file carrying the missing 117M tokens is read. The usage inside it is discarded after the counter reset, and the scan still completes. A warm cache does not change the figure: cached and cold runs both give 74,085,160 for the day. The cold run additionally drops 2026-09-03 and 2026-09-04 from the seven-day window entirely, which the warm run still lists.

Claude cost on the same machine matches ccusage exactly for every closed day, so this is confined to the Codex scanner.

Repro commands

Locate a reset:

cd ~/.codex/sessions/2026/09/07
jq -r 'select(.payload.type=="token_count")
       | "\(.timestamp) \(.payload.info.total_token_usage.total_tokens)"' rollout-*.jsonl \
  | awk 'NR>1 && $2<prev {print "drop at "$1": "prev" -> "$2} {prev=$2}'

Sum the ledger for one day across the whole tree:

cd ~/.codex/sessions
grep -h '"2026-09-08T' 2026/*/*/*.jsonl \
  | jq -c 'select(.payload.type=="token_count") | .payload.info.last_token_usage | select(.!=null)' \
  | jq -s '{n:length, in:(map(.input_tokens)|add), cached:(map(.cached_input_tokens)|add), out:(map(.output_tokens)|add)}'

I can supply a sanitized rollout slice around the reset boundary if that helps, and I am happy to test a patch on Linux.

muhackel avatar Sep 09 '26 12:09 muhackel

The scanner already derives each usage day from the token event's timestamp. The failure is that a cumulative-counter decrease activates the interleaved-counter guard, which suppresses later usage below the previous counted total, even when last_token_usage is present. The file can therefore reach scan-complete without producing a later-day usage row. A fix must distinguish a genuine reset from interleaved/replayed counters; treating every decrease as a reset would reintroduce overcounting protected by #2037. No fix has landed from this investigation. Thanks @Pjhhhhh for the report.

steipete avatar Sep 21 '26 10:09 steipete

Replayed the published synthetic reset vectors against 49e7ff3eca52. Normal and forced scans reach EOF but produce 0 next-day tokens instead of 132; both growing-counter controls produce 132. The same-day fixture produces 1,100 instead of 2,840. This is the existing counter-containment limitation, not evidence of file-date bucketing. A safe repair needs request identity and ownership-aware reconciliation with legacy events and copied history. No accounting change is proposed by this investigation.

steipete avatar Sep 24 '26 12:09 steipete

Additional data point on 0.70.0 (CLI, macOS arm64) — same class of bug, with a large impact on 30-day totals.

Setup: long-lived Codex Desktop threads keep appending to rollout files that sit in older date partitions (e.g. a thread started 2026-08-26 still emitting token_count events on 2026-09-18).

I first forced the scan to completion (codexbar cost --provider codex --format json --days 30 --refresh, repeated until historyCoverageIsEstablished: true), then compared daily totals against an independent recount of token_count events bucketed by event timestamp (deduplicated per file by total_token_usage progression; the sum of last_token_usage equals the total_token_usage deltas exactly).

day codexbar --days 30 codexbar --period all by event timestamp
2026-08-31 (outside window) 685.1M 478.1M
2026-09-03 106.9M — 317.3M
2026-09-17 73.8M 98.3M 436.0M
2026-09-18 41.4M — 151.8M

30-day window total: 9.62B tokens vs 12.28B by event timestamp (~22% under). From 2026-09-20 onward the two agree within 1–3%.

Observations:

  • Usage from resumed/long-lived rollouts appears to be attributed to the rollout's start day, so --period all inflates August days, while with --days 30 that usage drops out of the window entirely.
  • The same day differs between --days 30 and --period all (09-17: 73.8M vs 98.3M), so the result depends on the requested window.

ivkiwi avatar Sep 30 '26 10:09 ivkiwi

Fixed by #4195 (0.71.2): typed token_usage_record entries are read as per-response usage with validated ownership and reconciled with the legacy counters in one place, so a resumed session that resets the legacy watermark no longer leaves the new day at zero. Thanks @Yuxin-Qiao for the implementation and everyone here for the evidence.

steipete avatar Oct 04 '26 02:10 steipete