CodexBar icon indicating copy to clipboard operation
CodexBar copied to clipboard

Codex cost: subagent/forked rollouts are counted at their final cumulative total_token_usage, inflating fan-out days 30-150x

Open vnnkl opened this issue 2 months ago • 23 comments

Summary

Rollout files created by Codex Desktop subagent fan-outs (thread_source: "subagent", forked_from_id set) inherit the parent thread's cumulative total_token_usage in their very first token_count event. CodexBar appears to count each file at its final cumulative total instead of the delta from that inherited baseline, so every fork re-counts its parent's entire token history. On days with many parallel forks of a long-lived parent this inflates tokens (and therefore estimated cost) by 30–150×.

My 30-day Codex estimate currently shows $138k–170k / 175–204B tokens; the true numbers from the same rollout files are ~$6k / 9.6B tokens, and OpenAI's own account/usage/read confirms the account's lifetime total is 29.6B tokens with a peak day of 1.64B.

Reproduction / evidence

Environment: macOS, CodexBar 0.54.0 and 0.57.0 (both affected; 0.57.0 slightly worse), rollouts written by Codex Desktop cli_versions 0.148.0-alpha.9 … 0.153.1.

A fork's first token_count event (ordinal 2, before any turn) already carries the parent's cumulative counter — note last_token_usage all zeros:

{"type":"session_meta","payload":{"id":"01a00602-…","forked_from_id":"019faece-…","thread_source":"subagent","source":{"subagent":{"thread_spawn":{"parent_thread_id":"019faece-…","depth":1}}}}}
{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":3153916657,"cached_input_tokens":3113606656,"output_tokens":3991590,"total_tokens":3157908247},"last_token_usage":{"input_tokens":0,"cached_input_tokens":0,"output_tokens":0,"total_tokens":9035}}}}

Per-day comparison — "naive sum" = Σ over the day's files of the final cumulative total_tokens; "true delta" = Σ of (last − first) per file:

day files CodexBar 0.57 claims naive sum true delta OpenAI account/usage/read
2026-09-04 62 30,541,006,796 30,380,536,401 821,257,479 1,637,928,247
2026-09-05 14 7,763,819,245 7,844,073,190 264,351,645 359,188,681
2026-08-15 33 32,283,315,371 102,075,860,655 209,219,793 351,832,483

On 0.57.0 the claimed values match the naive cumulative sum almost exactly (09-04: 30.54B vs 30.38B). The true deltas match OpenAI's official daily buckets within normal bucketing noise; the claims are 30–150× over. 30-day totals: claimed 204B tokens vs 9.6B real — against a lifetime account total of 29.6B.

One more data point: a scan by the same machine on 2026-08-25 (0.4x-era) still reported the mid-August days correctly (e.g. Aug 15 = 274M tokens); the same untouched files now scan as 32.3B. So the regression is in how the current scanner aggregates, not in the data.

Suggested fix

Per rollout file, use last(total_token_usage) − first(total_token_usage) (component-wise) instead of the final cumulative — the inherited fork baseline then cancels out. Equivalently: sum last_token_usage deltas. Files with forked_from_id make the inherited baseline explicit if you'd rather special-case forks.

Happy to provide redacted rollout excerpts or run instrumented builds.

vnnkl avatar Sep 09 '26 10:09 vnnkl

Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed September 9, 2026, 7:09 AM ET / 11:09 UTC.

Summary Keep open: the latest-release accounting discrepancy remains unresolved. The new excerpt is useful, but it does not establish the proposed adjacency failure: the relevant turn context and trigger are adjacent at ordinals 10 and 11. A focused reproduction is needed before changing the accounting rules.

Reproducibility: no. high-confidence failing current-main reproduction is established yet. The reported ordinal gap satisfies the actual adjacency check, while the first post-boundary row lacks the component counters needed to evaluate local confirmation; no runtime tests were executed.

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 Use the offered redacted fixture to obtain ordinal 19's input/cached/output total and last counters, preserve intervening record types, and compare isolated cold versus warm accounting; the failing branch is not yet specific enough for automatic repair.

Review details

Best possible solution:

Exclude proven inherited prefixes while preserving genuine first-event usage and replay deduplication, with regression coverage for the reported producer ordering and cached-report convergence.

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

No high-confidence failing current-main reproduction is established yet. The reported ordinal gap satisfies the actual adjacency check, while the first post-boundary row lacks the component counters needed to evaluate local confirmation; no runtime tests were executed.

Is this the best way to solve the issue?

No: blanket last-minus-first or summing last_token_usage can discard genuine opening usage or recount replayed rows. First isolate why this file misses the existing inherited-prefix path, then repair that specific parser or cache behavior.

AGENTS.md: found and applied where relevant.

Remaining risk / open question:

  • Aggregate total_tokens values do not establish the component-wise equality used to confirm inherited history.
  • The current evidence does not distinguish a fresh parser misclassification from reuse or publication of previously inflated cached totals.

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

Label changes

Label justifications:

  • P2: The report describes substantial errors in local estimates, without evidence of actual billing changes or blocked core operation.
  • impact:other: Inflated token and cost estimates undermine spend reporting; no more specific owned impact label fits.
Evidence reviewed

What I checked:

  • New reporter evidence narrows the investigation: The supplied comment https://github.com/steipete/CodexBar/issues/3524#issuecomment-5600833138 preserves the opening record order, places turn_context at ordinal 10 and the triggering inter-agent record at ordinal 11, and reports a 3,157,908,247-token opening baseline. Ordinal 19 supplies aggregate total/last values but not their input, cached-input, and output components. The supplied parent samples occur after the child's opening timestamp, so they do not establish exact parent-boundary equality.
  • Adjacency is measured from turn context: The classifier requires the trigger immediately after the pending turn_context, not immediately after the initial token_count or compacted record. On the reported ordering, ordinals 10 and 11 satisfy that condition. Local confirmation additionally requires component-wise total minus last to equal the pre-boundary counters. (Sources/CodexBarCore/Vendored/CostUsage/CodexSubagentRolloutShape.swift:123, 928166f89947)
  • The reported trigger spelling is supported: Both the fast parser and Foundation fallback recognize inter_agent_communication_metadata and its payload.trigger_turn boolean. Physical line positions are retained while unrelated records are skipped. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:3721, 928166f89947)
  • Current accounting already supports compact inherited prefixes: The scanner promotes locally confirmed candidates to copied-prefix accounting, installs their raw baseline, and excludes buffered records before the owned suffix. Otherwise it can seek exact parent confirmation; independent classification bypasses inherited subtraction. The supplied excerpt does not determine which confirmation branch the real file takes. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift:5081, 928166f89947)
  • Existing regression contract: CodexCompactSubagentAccountingTests covers compact-prefix suppression across cold, warm, and forced scans, including local confirmation when the parent mismatches or remains unresolved. CodexSubagentRolloutShapeTests separately preserves independent counters and rejects genuinely nonadjacent triggers. These tests were inspected, not executed. (Tests/CodexBarTests/CodexCompactSubagentAccountingTests.swift:10, 928166f89947)
  • Relevant handling already exists in the reported release: Inspection of v0.57.0 shows the same local-confirmation and parent-confirmation branches. This establishes existing release behavior, not that the reported corpus is fixed. (Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift, 45cda6084d64)

Likely related people:

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

Here is the requested numeric-only parent/child excerpt with record order, ordinals, timestamps and boundary metadata preserved — and I believe it establishes the failing classifier case in your own terms.

Environment

  • CodexBar 0.57.0 (Homebrew cask), macOS 26 (Darwin 25.5.0), Codex via ChatGPT subscription
  • Producer of the affected rollouts: Codex Desktop subagent fan-outs, cli_version 0.148.0-alpha.9 (this excerpt) through 0.153.1 (later ones)

Expected vs actual (one file)

rollout-2026-08-15T17-20-27-01a00602-….jsonl, 15 token_count events:

  • expected (the file's own turns, last − first cumulative): 748,286 tokens (757,321 if the opening event's last=9035 belongs to the child)
  • actually counted: the final cumulative 3,158,656,533 — the inherited parent history plus the own turns

All 33 fork files of 2026-08-15 share this shape → day total 32.28B tokens claimed vs 209M real. 62 files on 2026-09-04 → 30.55B claimed vs 821M real.

Child opening record sequence (ordinals 0–19)

ord  0  session_meta        forked_from_id=019faece-a0de-7171-b58c-795255d1bd62,
                            parent_thread_id=<same>, thread_source="subagent",
                            source.subagent.thread_spawn={parent_thread_id:<same>, depth:1},
                            cli_version="0.148.0-alpha.9", originator="Codex Desktop"
ord  1  compacted           replacement_history=[replayed messages w/ msg ids + turn ids],
                            window_number=69,
                            first_window_id="019faece-a0de-7171-b58c-796af31dd2a5",   <- parent uuid prefix
                            previous_window_id="01a00600-880f-7562-9eba-1766e785283b"
ord  2  token_count         total_token_usage={input:3,153,916,657, cached_input:3,113,606,656,
                            output:3,991,590, total:3,157,908,247}
                            last_token_usage={input:0, cached_input:0, output:0, total:9,035}
ord  3  task_started
ord  4  item_completed
ord  5-8  response_item/message   (4 replayed context messages)
ord  9  world_state
ord 10  turn_context        model="gpt-5.4-mini"
ord 11  inter_agent_communication_metadata   payload={"trigger_turn": true}
ord 12  response_item/agent_message
ord 13  response_item/reasoning
...
ord 19  token_count         total=3,157,934,782  last=26,535        <- normal deltas from here on

(All records in the opening burst share timestamp 2026-08-15T15:20:27.749Z; final token_count of the file: total=3,158,656,533.)

Why I think this is the classifier miss

Your review states compact inherited-history detection "requires additional boundary evidence, including an adjacent triggering inter-agent event" (CodexSubagentRolloutShape.swift:123). In this producer format the boundary is session_meta → compacted → token_count(inherited totals, last≈0) at ordinals 0–2, but the inter_agent_communication_metadata {trigger_turn:true} record lands at ordinal 11 — separated from the boundary by four replayed response_item/message records, a world_state, and a turn_context. If the adjacency requirement doesn't tolerate that gap, the fork is classified independent, configureForkAccountingIfReady never clears the inherited totals, and the opening 3.15B is billed — matching exactly what we observe.

Parent/child counter alignment (inheritance proof)

Parent rollout-2026-07-29T18-56-45-019faece-a0de-7171-b58c-795255d1bd62.jsonl (281 MB, 100k+ ordinals, still active on 2026-08-15):

parent 2026-08-15T15:25:20.616Z ord=100019 total=3,158,788,625 (in=3,154,795,580 cached=3,114,473,472 out=3,993,045)
parent 2026-08-15T15:26:24.133Z ord=100023 total=3,158,879,191
child  2026-08-15T15:20:27.749Z ord=2      total=3,157,908,247 (in=3,153,916,657 cached=3,113,606,656 out=3,991,590)

The child's opening total sits exactly on the parent's counter trajectory five minutes earlier — same lineage counter, component-wise. Note the parent file also keeps counting past the spawn, so parent and each of its forks all carry the same ~3.15B prefix.

On your caveat that blanket last-minus-first "can discard genuine first-event usage": agreed — in this shape the discarded amount is the opening last_token_usage.total (9,035 tokens here), vs ~3.15B overcount the other way. A narrowly scoped rule for this fixture (compacted with inherited first_window_id + token_count whose last components are ≈0 relative to total) would stay conservative.

Happy to provide more redacted fixtures (any day/shape you want) or run an instrumented build against this corpus.

vnnkl avatar Sep 09 '26 11:09 vnnkl

@clawsweeper re-review — the requested numeric-only parent/child excerpt with record order, ordinals and boundary metadata is now in the comment above, including the ordinal-11 position of the inter-agent trigger record relative to the ordinal 0-2 compact boundary.

vnnkl avatar Sep 09 '26 11:09 vnnkl

🦞🧹 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.

clawsweeper[bot] avatar Sep 09 '26 11:09 clawsweeper[bot]

The extra record ordering helps narrow this down. In current main (928166f89947), the adjacency check is between turn_context and the triggering inter_agent_communication_metadata record. Your ordinals 10 and 11 satisfy that check; the gap back to ordinal 2 does not itself reject the boundary. See the classifier.

The next decision checks the first owned event's input, cached-input, and output counters: component-wise total − last must equal the opening baseline, or the matching parent snapshot must establish it. The aggregate totals supplied for ordinal 19 do not show those component comparisons, and the parent samples shown are after the fork. That leaves both a classifier failure and stale cached/report totals possible; this source review does not yet reproduce the inflation.

Could you provide a numeric-only JSONL fixture from the child's opening through its first post-boundary token event, plus its final token event, retaining physical record order, timestamps, lineage fields, and every total_token_usage/last_token_usage counter? Content/message text can be replaced with synthetic text. If available, also include the parent's last token event at or before the fork and the next event. That should let us make an isolated regression and compare cold, warm, and forced-rescan results without accessing account credentials or deleting your cache.

Keeping this open. Blanket last-minus-first or summing every last remains unsafe for independently started child counters and replayed token events; the fix should target the demonstrated failing classification or cache path.

steipete avatar Sep 09 '26 13:09 steipete

Fixture delivered: https://gist.github.com/vnnkl/7b7b0d332cc60ba7d049ff479adc20c0

  • fixture-child.jsonl — the child's physical lines 0–19 (session_meta → compacted → opening token_count → … → first post-boundary token_count at ordinal 19) plus its final token_count (ordinal 208). Record order, ordinals, timestamps, lineage/window ids and every total_token_usage/last_token_usage counter are verbatim; only free text >80 chars is replaced with "synthetic" and usernames/project names in paths genericized.
  • fixture-parent-bracket.jsonl — the parent's last token event at/before the fork timestamp and the next one after, verbatim.

Three findings from the counters that should let you pick between the classifier and cache paths:

1. An exact parent snapshot exists. The parent's last token event before the fork (ordinal 99971, 15:20:15.113, fork at 15:20:27.749) is component-wise identical to the child's opening total: {in 3,153,916,657, cached 3,113,606,656, out 3,991,590, reasoning 624,089, total 3,157,908,247}. So the "matching parent snapshot" branch has perfect evidence available in this corpus.

2. The first owned event's total − last matches the opening baseline on every component — with one wrinkle. Ordinal 19: in 3,153,942,488 − 25,831, cached 3,113,609,088 − 2,432, out 3,992,294 − 704, reasoning 624,632 − 543, total 3,157,934,782 − 26,535 — each equals the opening event's total_token_usage component exactly. The wrinkle: it equals the opening event's total, not the opening event's total − last, because the opening last_token_usage is anomalous — total: 9,035 with all components zero (see fixture line 3, ordinal 2). If the equality is computed against (total − last) of the opening event, it misses by exactly 9,035 on the total while matching on every component. That inconsistent opening last (components don't sum to total) is a producer quirk of this Codex Desktop format and would be my prime suspect for a strict check rejecting the boundary.

3. Cold-scan history points at cache staleness as a second candidate. The same binary lineage scanned these very files correctly on 2026-08-25 (Aug 15 reported as ~274M tokens then); today 0.54.0-cask and 0.57.0 both report 32.28B for the same untouched files (mtimes predate 2026-08-25). So either the classification outcome changed with the version, or previously-correct cached per-file results were re-derived down the independent path on a later rescan. Forced-rescan vs warm comparisons on your side should separate these.

Expected accounting for the fixture file: ~748,286 own tokens (3,158,656,533 − 3,157,908,247); currently billed ~3.16B. Happy to sanitize further fixtures (e.g. one of the 62 files from 2026-09-04, cli 0.153.1) if the producer format changed between versions.

vnnkl avatar Sep 09 '26 14:09 vnnkl

Thanks for the fixture. I ran it through the current parser in an isolated test: it produced 748,286 tokens in two rows, without consulting the parent. The anomalous opening last.total_tokens is not the cause; this path compares the component counters against the raw opening baseline.

The important extra field is subagent_history_start_ordinal: 210. All supplied token records are earlier than 210, so their child-owned contribution should be zero. The producer contract explicitly defines earlier records as inherited context. Current CodexBar confuses “explicit boundary present, no owned suffix yet” with “no explicit boundary” and falls back to the copied turn/trigger pair.

I've opened #3527 for that reproduced bug. The supplied fixture now produces zero tokens/rows. Synthetic regressions cover a prefix-only file, later child-owned usage after append, ordinary/bounded/cold/warm/forced scans, and replacing older cached rows while preserving the store and source bytes. Parser revisions ensure unchanged older files get reparsed through the normal budget. Focused tests, lint, and independent review pass; full validation is running.

Keeping this issue open: the fixture reproduces the inherited-prefix bug, but it does not reproduce the separately reported 3.16B current-parser result. The excerpt also does not establish whether the original file contains later child-owned records. That larger result may involve cached per-file classifications or additional records, so I won't claim the whole report resolved from this subset.

steipete avatar Sep 09 '26 15:09 steipete

Both open questions answered from the original corpus:

1. The original file has no records past the boundary — prefix-only confirmed. The source file of the fixture has exactly 210 lines, ordinals 0–209 (last record: task_complete at 209), against subagent_history_start_ordinal: 210. Zero child-owned records, so post-#3527's zero is correct for it. Corpus-wide under the ordinal contract:

  • 2026-08-15: 33 files → 32 prefix-only (0 owned), 1 regular session (no fork marker) owning 27,759,661 tokens. True day ≈ 27.8M — vs 32.28B reported.
  • 2026-09-04: 62 files → 8 prefix-only, 14 forks with owned suffixes, 40 regular sessions; owned-per-contract sum ≈ 578M (baseline = last token event with ordinal < start_ordinal).

2. The 3.16B result is stale cached per-file rows — reproduced and discriminated with --refresh. On the same machine, same untouched files, CodexBar 0.57.0 CLI:

run codex 30d tokens 30d est. cost 2026-08-15 2026-09-04
plain (warm cache) 204,280,502,061 $169,580 32.28B 30.54B
--refresh 1,607,664,253 $2,620 (absent) 7,950,004
plain again (after refresh) 1,607,664,253 $2,620 (absent) 7,950,004

So the current parser never produces the inflation; the inflated rows were written earlier (the same machine's scan was still correct on 2026-08-25, and the mid-August files' mtimes predate that — the bad rows must have been written by whatever parser/rescan ran between 2026-08-25 and 2026-09-04) and were served as cached results until --refresh. Your "unchanged older files get reparsed through the normal budget" revision should cover exactly this.

3. One possible over-correction to check while you're in there: post-refresh, 2026-09-04 reports 7.95M tokens, but the per-contract owned sum for that day's files is ~578M (dominated by the 40 regular no-marker sessions plus 14 forks with genuine owned suffixes; producer cli_version 0.153.1). And the 30d refresh total (1.6B) sits well below both my rollout-delta floor and OpenAI's own account/usage/read buckets for the window (14.4B, lifetime 29.6B). Some of that is day-attribution semantics (long-lived threads started before the window carry usage on old dates), but 7.95M vs 578M on a single fully-in-window day suggests owned suffixes may now be dropped too. Happy to sanitize a 0.153.1 fixture with a genuine owned suffix if useful.

vnnkl avatar Sep 09 '26 16:09 vnnkl

That confirms both the prefix-only interpretation and the stale-row mechanism. #3527 addresses those independently: explicit ordinal precedence fixes the prefix case, and the parser revision makes unchanged older files eligible for bounded reparsing.

Please send the 0.153.1 fixture with a genuine owned suffix for the remaining low-count case. The useful slice is the first metadata record, last token event before the boundary, first owned context/token event, any later counter drop or reset and its surrounding record types, and the final token event. Keep ordinal/timestamp/model/counter fields and consistent lineage/turn IDs; replace all message text and tool arguments with synthetic placeholders.

Please also include the JSON report's completion/coverage/progress fields, the requested history window, and timezone. A budget-limited or incomplete scan needs to be distinguished from dropping owned rows. The low result you observed is already on 0.57.0, so it is not an over-correction introduced by #3527. We'll keep this issue open for that remaining case while landing the reproduced correction.

steipete avatar Sep 09 '26 16:09 steipete

Added to the gist: fixture-child-0153.jsonl (requested slice, sanitized same way — counters/ordinals/timestamps/lineage ids verbatim, text synthetic) and fixture-0153-ordinal-map.txt (full ordinal→record-type map of the file).

Source: rollout-2026-09-04T20-08-28-01a06d9b-970d-7722-b023-d778e18b295a.jsonl, producer cli_version 0.153.1, subagent_history_start_ordinal: 26, 1305 records, 147 token events, final owned total 15,229,666.

The slice, mapped to what you asked for:

  • first metadata record(s): ordinals 0 and 1 — this format writes two session_meta records.
  • last token event before the boundary: does not exist. None of the pre-boundary records carry token counts — and that holds for all 14 owned-suffix fork files on 2026-09-04 (13× 0.153.0-alpha.5, 1× 0.153.1). This format replays parent context without counters and starts a child-local counter at zero — unlike the 0.148.0-alpha.9 format, which inherited the parent's cumulative counter.
  • first owned context/token events: ordinals 22–31 included. Note ordinal 28 is a token_usage_record (per-response usage with turn_token_usage, thread_token_usage, response_id, and a session_id pointing at the parent thread) and ordinal 29 a compacted window record — both sit between the boundary and the first token_count.
  • counter drop/reset: no cumulative decrease anywhere in the file (nor in any of the 14). But the reset signature is the opening token_count itself (ordinal 31): total_token_usage all zeros with last_token_usage.total = 16,042 — the mirror image of the 0.148 anomaly; the cumulative catches up at the next token event (ordinal 52, included).
  • final token event: ordinal 1302 included.

Expected accounting for this file: 15,229,666 (child-local counter, full final total). The 14 files together own ~134M tokens; the day's 40 regular sessions add ~445M → ~578M for 2026-09-04.

Report metadata from the low-count runs (--provider codex --days 30, timezone Europe/Berlin): both the --refresh run and the warm run after it report identically:

"coverage": {"estimated": 0, "priced": 8, "unmetered": 0, "unpriced": 0},
"historyCoverageIsEstablished": false,
"historyDays": 30,
"last30DaysTokens": 1607664253,
"provenance": "listPriceEstimate"

priced: 8 days in a 30-day window with historyCoverageIsEstablished: false — and the daily array indeed contains only 8 entries (which is also why 2026-08-15 was absent from my earlier table rather than zero). So the 7.95M-vs-578M gap on 2026-09-04 looks at least partly like a bounded/not-yet-established scan rather than dropped owned rows; whether a fully established scan still undercounts the fresh-counter forks I can't tell from here. Happy to re-run once #3527 lands and report the established-coverage numbers.

My owner told me to say: „Danke für die schnelle Hilfe und viele Grüße"

vnnkl avatar Sep 09 '26 16:09 vnnkl

I checked the new owned-suffix shape against the current parser and ran a synthetic regression retaining the ordinal boundary and anomalous summary field. It passes: the explicit boundary at 26 accepts the zero component baseline at 31 despite last.total_tokens being 16042, then counts all 15,229,666 owned input/output tokens without consulting the parent. The parser intentionally uses the component counters rather than that summary field.

The copied model context before the boundary also stays excluded; the slice has no owned model context, so this synthetic result is unattributed rather than priced using the parent model. That preserves the fork ownership boundary.

This does not resolve the broader history discrepancy. With coverage still incomplete, the current totals cannot yet establish a completed-scan undercount. Keeping this open for the completed-scan result and, if it still differs, a minimal owned-record example with model context.

steipete avatar Sep 10 '26 08:09 steipete

Completed-scan result is in — and it flips the question: the completed scan does not undercount, it reproduces the original inflation.

Timeline on the same machine, same files, CodexBar 0.57.0:

run 30d tokens 30d est. 2026-08-15 2026-09-04 coverage
09-09 warm 204,280,502,061 $169,580 32.28B 30.54B (stale rows)
09-09 --refresh (from scratch) 1,607,664,253 $2,620 absent 7,950,004 priced 8/30, not established
09-10 warm, after the app's overnight background scan 204,083,999,789 $168,641 32,283,315,371 30,546,070,143 priced 29 + 1 unpriced, established: true
09-10 --refresh identical to warm identical identical identical established: true

The overnight establishing scan regenerated the inflated per-day values byte-identical to the pre-refresh state (the 30d delta vs 09-09 is just the window sliding a day). So on the released build, any scan that reaches full coverage re-derives the inflation deterministically — consistent with your #3527 fallback being triggered by the full files (their complete copied turn/trigger pairs and compacted records), which the 21-line fixture only partially exercised. Yesterday's small numbers were a from-scratch bounded scan of correct per-file results, nothing more.

One residue that may still interest you: in the 09-09 bounded refresh, 2026-09-04 was among the 8 priced days yet reported 7.95M vs ~578M per-contract owned — whether a bounded scan can price a day partially is invisible from out here.

We'll update once a release with #3527 lands, run a fresh --refresh, and report per-day numbers against the contract math (27.8M for 08-15, ~578M for 09-04). The minimal owned-record example with model context is ready to cut from the same corpus if you still want it after that.

vnnkl avatar Sep 10 '26 16:09 vnnkl

Thanks for the completed-coverage comparison. That establishes the inflation in the reported 0.57.0 run; incomplete coverage no longer explains that result.

The inherited-prefix and stale-parser-cache fix from #3527 is included in 0.58.0, which is now published. Please repeat the completed-scan comparison after upgrading. Keeping this open until we have that post-upgrade result; the current synthetic boundary regression does not replace verification of your full dataset.

steipete avatar Sep 10 '26 19:09 steipete

Post-upgrade verification from another affected macOS installation: the explicit inherited-prefix case is corrected in the signed 0.60.5 release on this corpus.

The installation had remained on 0.48.0 (112) with a local report-layer Standard/Fast normalization patch. That patch did not implement the later explicit subagent_history_start_ordinal handling. I am not reporting a new 0.60.5 regression or treating the old patched build as an unmodified release.

Direct source/cache comparison found multiple subagent files with forked_from_id and an explicit history boundary exactly at EOF. Using zero-based physical record ordinals:

Anonymized file Physical records subagent_history_start_ordinal Token events before boundary Token events at/after boundary Old cache Completed 0.60.5 cache
A 341 341 52 0 positive inherited usage zero owned usage
B 300 300 53 0 positive inherited usage zero owned usage
C 410 410 46 0 positive inherited usage zero owned usage
D 222 222 45 0 positive inherited usage zero owned usage

These are prefix-only files: no child-owned token event exists beyond the explicit boundary. Zero is therefore the expected contribution, independently of the parent totals.

Verification:

  • Preserved the original rollout files and backed up the old cache before upgrading.
  • Ran codexbar cost --provider codex --days 90 --refresh --json repeatedly to let the bounded scanner finish; a single invocation was not sufficient.
  • The completed SQLite cache reported catchUpPending=false, completedFiles=totalFiles, and processedBytes=totalBytes; the CLI report reported historyCoverageIsEstablished=true.
  • Repeated a warm refresh: all completed historical days retained identical token totals and costs (within one cent); only today's ongoing usage changed.
  • After launching the upgraded app, its Usage & Spend source widened the scan window to 365 days. Completed that additional scan too, restarted the installed app, and verified the wider cache remained fully caught up. A subsequent 90-day refresh retained the same past-day totals.
  • Confirmed the installed app and bundled CLI both report 0.60.5 and the app's official signature verifies.

The local recurrence was explained by remaining on the older patched build plus its incomplete historical scan, rather than a demonstrated recurrence of this prefix-only bug on 0.60.5. The official Homebrew tap and installed cask have now both been updated. This supports the #3527 fix on another real corpus, while making no claim about the other unresolved shapes discussed in this issue.

No account identifiers, project paths, conversation content, or raw usage logs are included.

Rivbla avatar Sep 18 '26 02:09 Rivbla

The forked-rollout inflation you measured (30x to 150x, $138k-170k against a true ~$6k) is the over-counting mirror of a problem I have been writing conformance checks for.

My draft vectors at conformance/vectors/delegation-001-003.json try to pin when a child's cumulative counter must not be inherited by the parent, and DELEGATION-003 covers cost attribution across the boundary.

Would you check whether DELEGATION-003 would have caught the inheritance you found, or whether the invariant needs to be stated differently for rollout forks?

The most useful feedback would be the counter shape you compared against OpenAI's usage API, a case the vectors miss, or a note on where they are too strict.

Roy Tong, AgentMeasure (github.com/roy-tong/AgentMeasure)

roy-tong avatar Sep 19 '26 00:09 roy-tong

Corroborating from an independent corpus: we hit the same parent-cumulative-inheritance shape auditing log parsers (merged fixes at token-monitor#627 and tokscale#1306→#1323, both keyed on stable response identity surviving the copy).

One measurement that may help size the fix's blast radius: across 53 public rollout sessions (1,313 token_count events), 46% of usage events are byte-identical re-emissions of their predecessor — so after de-inheriting the parent baseline, the delta math still needs an idempotency guard or the re-emissions will silently restore part of the inflation you're removing. Field topology reference with a reproducible analyzer: codex-rollout-topology.

roy-tong avatar Sep 19 '26 01:09 roy-tong

codexbar-reproduction.zip

I have a potentially related remaining case on CodexBar 0.61.0 (149), not a claim that #3527 failed for its original fixture.

The four affected files are forked source: "vscode" sessions with forked_from_id, without subagent_history_start_ordinal. This differs from the explicit subagent-boundary case discussed above.

I reproduced my displayed September 17 estimate of $3,237.42 from the cached usage rows and cached model rates. Four Astra pricing rows contribute $2,953.026712 of that total:

Input Cached input Output Estimated cost
48,246,000 0 128,080 $974.526000
48,212,743 0 127,937 $973.850135
48,287,114 7,552 128,206 $975.221794
6,158,306 5,296,384 21,301 $29.428783

For the first row, the source token event reports last_token_usage.input_tokens = 33,257 but total_token_usage.input_tokens = 48,246,000. Its context window is 286,092. The accumulated total is being priced as a single >272K request.

I then made a content-free fixture of these four files plus their available ancestors (10 files). Record order, timestamps, model fields and token counters are retained; IDs are consistently replaced, paths are synthetic, and prompt/tool/response contents are removed.

Using the installed 0.61.0 CLI with an empty isolated cache reproduced all four oversized pricing rows. Warm and forced-rescan runs returned the same result. All three report historyCoverageIsEstablished=true. The isolated subset costs $3,011.117276 on September 17 (188,830,685 tokens); this is a subset, not the full original daily report.

The process was sandboxed to deny network access, deny reads of the real user home, and allow writes only inside its temporary audit directory. No live cache was cleared or modified. This rules out stale live-cache data as the sole explanation for these rows.

Could you check this non-subagent fork shape and its cumulative-baseline/request-tier accounting? I have not derived a verified corrected daily cost.

korboybeats avatar Sep 19 '26 09:09 korboybeats

I reproduced a remaining non-subagent direct-fork/worktree case on 0.62.0. This is separate from the continuation-page shape fixed by #3753 and matches the newer source: "vscode" report above.

The distinguishing evidence is deterministic:

  • history_base.thread_id == forked_from_id (a direct fork, not a later page of the same child).
  • The parent session ID belongs to several paginated rollout files.
  • CodexSessionFileIndex retains one path per session ID. In two affected files, the persisted dependency selected a parent page whose first token snapshot was after the child's fork timestamp.
  • The resolver therefore returned no pre-fork baseline and the child billed its complete cumulative prefix.
  • Independently reading the history_base.end_byte_offset boundary showed that the child's first total - last matched the parent's cumulative total there exactly.

Numeric-only results from the two direct forks:

file cached input before child-owned input duplicated prefix
A 127,723,437 3,762,200 123,961,237
B 737,061,683 5,571,083 731,490,600

True subagent files sampled from the same corpus start their counters at their first request and do not have this inherited-prefix shape.

I have a focused patch at anon5376/CodexBar@09bc3b1. It does not change ordinary forks with a usable parent snapshot. It distinguishes the narrow case where the selected, sufficiently indexed parent page has snapshots but all of them begin after the fork; only then does the direct fork use its first total - last as the conservative local inherited baseline. Missing/deferred/incomplete parents remain fail-closed. The state is persisted across bounded scans, parser revision 4 reparses old rows, and the current-main store hash is adopted without deleting the database.

Validation:

  • focused synthetic resolver/index harness: old result 1,250, corrected result 250;
  • isolated replay of six affected real files reached established coverage after eight bounded passes;
  • direct forks corrected to 3,762,200 and 5,571,083 input tokens;
  • the two #3753 continuation pages stayed corrected at 17,994,625 and 50,837,528;
  • swift build --product CodexBarCLI passes;
  • parser hash check and SwiftFormat pass;
  • full Swift Testing / SwiftLint are unavailable locally because this machine has Command Line Tools but not full Xcode/SourceKit.

No source text, account identifiers, project paths, or raw logs are included. Since this issue currently says no-new-fix-pr, is a focused PR for this direct-fork resolver case welcome?

anon5376 avatar Sep 20 '26 13:09 anon5376

Follow-up: I ran the sanitized codexbar-reproduction.zip posted above against the patch. It exposed an additional fork-chain invariant, now covered at branch tip anon5376/CodexBar@5501c1d:

  • a child must inherit the parent's raw cumulative total, not merely the parent's locally owned/countable suffix, because that raw total includes context inherited from earlier ancestors;
  • when a complete intermediary rollout has no token snapshots, the child's first total - last is the local inherited prefix (while missing/incomplete parents still fail closed).

Results using the supplied fixture and pricing file:

scan before (fixture oracle) patched
cold 188,830,685 tokens / $3,011.117276 13,058,505 tokens / $23.100290
warm 188,830,685 tokens / $3,011.117276 13,058,505 tokens / $23.100290
forced refresh 188,830,685 tokens / $3,011.117276 13,058,505 tokens / $23.100290

All four oversized model rows from the fixture are gone on all three paths. I added a synthetic regression for a direct-fork chain containing an empty intermediary, in addition to the reused-future-page regression.

Final review hardening also treats a zero total - last as an authoritative continuation baseline and selects the latest eligible parent snapshot by timestamp rather than physical line order. Focused synthetic checks cover both boundaries.

anon5376 avatar Sep 20 '26 13:09 anon5376

Thanks @vnnkl. PR #3818 fixes independently reproduced fork-accounting cases: legacy forks with inherited opening counters, differing component baselines, missing parents, nested forks, and copied snapshots after ownership markers. Parser revision 4 makes unchanged older files eligible for bounded reparsing while preserving compatible history. Synthetic cases that counted 1,180–5,580 tokens now count the expected 80; inherited-only suffixes count zero. All 381 focused tests pass. The post-0.58.0 completed-corpus comparison remains outstanding in this thread, so please keep this issue open for that confirmation.

steipete avatar Sep 21 '26 11:09 steipete