Skip to content

fix: reuse/script cost cards no longer double-claim clustered sessions - #695

Merged
anshss merged 2 commits into
mainfrom
recoverable-dedup
Aug 4, 2026
Merged

anshss merged 2 commits into
mainfrom
recoverable-dedup

Conversation

@anshss

@anshss anshss commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Cross-analyzer double counting in the cost-recoverable rollup: reuse and script both cluster on the identical repeated-tool-sequence shape, and neither excluded the other's claim, so the one canonical additive total every surface renders (past_overspend_rollup) could sum both cards' dollars over the same sessions.

Summary

  • reuse (repeated planning skeleton) and script (deterministic tool-call cluster) key off the same shape: a planning call plus a deterministic tool sequence. Neither adapter excluded sessions the other already claimed, so a window where the same 20-session cluster tripped both got the cluster's cost counted twice in the Review inbox / dashboard / CLI headline.
  • Fixed by making each cluster carry its full member session-id population (not just the 3 rendered examples) and netting the lower-priority claim's past_overspend_usd/_tokens down by the proportion of its own sessions the higher-priority analyzer already claimed.
  • Added a generic, registry-driven regression test that seeds a window tripping several cost analyzers on deliberately overlapping spans and asserts the rollup never claims more than the window's real spend, both window-wide and per (provider, model).

Root cause

Two analyzers pricing the same underlying spans from different angles is a known, previously-hit failure mode (a cache-family instance and a downsize/subagent instance were both fixed earlier). Each prior fix was hand-written for its specific pair. reuse×script is a third instance that had no fix: both cluster the identical repeated-tool-sequence shape, reuse pricing the conservative "you already paid for the plan once" premise and script pricing the full-cluster-cost upper bound, and nothing stopped both from firing on the same sessions and both landing in the additive rollup.

Fix

  • ReuseCluster and WorkflowCluster (tokenjam/core/optimize/types.py, tokenjam/core/optimize/analyzers/workflow_restructure.py) now carry a member_session_ids field with every session in the cluster, not just the 3 examples used for rendering.
  • _reuse_to_proposals/_script_to_proposals (tokenjam/core/optimize/cost_proposals.py) pass that full population through as a new CostProposal.claimed_session_ids field. Every other analyzer leaves this empty and is completely unaffected.
  • A new _net_cross_analyzer_session_overlap pass runs once, right after all cost adapters produce their raw proposals: for any two proposals from different analyzers whose claimed_session_ids overlap, the lower-priority one (per a small _SESSION_CLAIM_PRIORITY map — reuse before script, since reuse's figure is already the product's designated conservative number) is netted down by the proportion of its own sessions the winner already claimed. A partial overlap shrinks the card partially rather than zeroing it out or leaving it untouched.
  • This generalizes the same remedy the existing _per_agent_cache_recoverable_by_model cache-family fix and the downsize/subagent sub_agent_id IS NULL fix already use (subtract what a more specific/prior card already claimed), but shares the arithmetic instead of hand-copying it: a future analyzer that wants the same protection just needs to populate claimed_session_ids and register into the priority map.
  • _collect_recoverable in tokenjam/api/routes/cost.py is deliberately not touched. Its total_recoverable_usd is already a documented, non-additive gross ceiling — it ships its own overlap disclosure (recoverable_additive: False, an explicit "these estimates ... do not add up to an amount you could actually recover" note) precisely because summing every analyzer's angle can't be made honest by subtraction alone. The actual additive total every surface treats as an amount a reader can act on is past_overspend_rollup, and that's the one this bug reached.

Tests / Verification

  • New: tests/unit/test_cross_analyzer_recoverable_invariant.py. Two tests, both iterating ANALYZER_REGISTRY rather than a hardcoded analyzer list:
    • test_rollup_never_exceeds_the_windows_real_spend — window-wide invariant.
    • test_rollup_never_exceeds_real_spend_per_provider_model — same invariant scoped to every (provider, model) pair the window mixes, since a window-wide check alone can hide an overlap that happens to net out across models.
    • The seeded window deliberately trips several analyzers on overlapping spans (a subagent Task-dispatch session, a context-heavy session, and a 20-session repeated-skeleton cluster split across two models) so both tests exercise real overlap candidates, not disjoint toy data. Confirmed both tests reproduce the bug before the fix (window-wide rollup claimed $10.57 against $8.32 of real spend) and pass after it.
  • Ran and confirmed green:
    • pytest tests/unit/test_cross_analyzer_recoverable_invariant.py -v — 2 passed
    • pytest tests/unit/test_rollup_subagent_downsize_dedup.py tests/unit/test_optimize_reuse.py tests/unit/test_workflow_restructure.py tests/unit/test_cross_analyzer_recoverable_invariant.py -q — 46 passed
    • pytest tests/unit/test_cost_proposals.py tests/unit/test_reuse_skeleton.py tests/unit/test_single_derivation.py tests/unit/test_write_budget.py tests/unit/test_past_overspend.py tests/integration/test_cost_proposals_api.py -q — 235 passed, 2 xfailed
    • pytest tests/unit -k "reuse or script or workflow_restructure or cost_proposal or rollup or write_budget or overspend or cross_analyzer" -q — 521 passed
    • ruff check / mypy clean on every touched file

What's NOT in this PR

  • No change to _collect_recoverable / total_recoverable_usd (api/routes/cost.py) — see "Fix" above for why; it's a deliberately non-additive figure with its own caveat, not the additive total this bug reached.
  • The cross-analyzer dedup mechanism is opt-in per pair (_SESSION_CLAIM_PRIORITY), not automatic for every analyzer combination. A brand-new analyzer that overlaps a sibling still needs someone to notice, populate claimed_session_ids, and register the pair — this PR shares the arithmetic, it doesn't remove the need for that judgment call. The new generic test is the safety net that surfaces the next instance in CI instead of a UI investigation.
  • Did not extend claimed_session_ids to any other analyzer pair (e.g. downsize/subagent, the cache family) — those already have working, tested fixes at the source and weren't touched.

🤖 Generated with Claude Code

…ed sessions

`reuse` and `script` both cluster on the identical repeated-tool-sequence
shape (a planning call plus a deterministic tool sequence), and neither
adapter excluded the other's claim. On a real window where the same cluster
tripped both, the Review inbox / dashboard / CLI headline
(`past_overspend_rollup`, the one canonical additive total every surface
renders) summed both cards' dollars over the same sessions, double-counting
the window's real spend.

`ReuseCluster` and `WorkflowCluster` now carry every member session id (not
just the 3 rendered examples), and their cost-proposal adapters pass that
full population through as `CostProposal.claimed_session_ids`. A new
`_net_cross_analyzer_session_overlap` pass in `cost_proposals.py` nets a
lower-priority proposal's `past_overspend_usd`/`_tokens` down by the
proportion of its own sessions a higher-priority analyzer already claimed —
`reuse` wins (its cache-reuse premise is already the product's designated
conservative number; `script`'s figure is explicitly the upper-bound
alternative to that same quantity). This generalizes the same remedy
Critical Rule 27 already documents for the cache family and downsize/
subagent (subtract what a more specific card claimed), but makes the
arithmetic shared rather than hand-copied per pair — any future analyzer
that populates `claimed_session_ids` and opts into the priority map gets the
same protection for free.

Added a generic, registry-driven regression test
(`test_cross_analyzer_recoverable_invariant.py`) that seeds a window
tripping several cost analyzers on overlapping spans (a subagent dispatch,
a context-heavy session, and a 20-session repeated-skeleton cluster across
two models) and asserts the rollup never claims more than the window's real
spend, window-wide and per (provider, model). It iterates
`ANALYZER_REGISTRY` rather than a hardcoded pair list, so a third analyzer
that reaches into another's spans is caught by CI rather than a UI
investigation.

`_collect_recoverable` (api/routes/cost.py) is deliberately untouched — its
`total_recoverable_usd` is a documented, non-additive gross ceiling with its
own overlap caveat (`recoverable_additive: False`), not the additive total
this bug actually reached.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@anshss
anshss requested a review from anilmurty as a code owner August 4, 2026 18:10
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR carries complete cluster membership from the reuse and script analyzers into cost proposals, then nets lower-priority overlapping claims before computing the additive past-overspend rollup.

  • Adds full member-session IDs to reuse and workflow clusters.
  • Introduces registry-prioritized cross-analyzer overlap adjustment.
  • Adds window-wide and per-model rollup invariant tests.

Confidence Score: 4/5

The PR does not yet appear safe to merge because partial reuse/script overlaps with unequal per-session usage can still produce an incorrect additive rollup.

The overlap pass continues to scale aggregate cost and tokens using the fraction of session IDs that overlap, even though script and reuse clusters can contain sessions with different cost and token contributions; the existing invariant fixture exercises uniform full overlap and therefore does not establish that the previously reported failure was fixed.

Files Needing Attention: tokenjam/core/optimize/cost_proposals.py, tests/unit/test_cross_analyzer_recoverable_invariant.py

Important Files Changed

Filename Overview
tokenjam/core/optimize/cost_proposals.py Adds claimed-session metadata to reuse/script proposals and applies priority-based overlap netting before rollup.
tokenjam/core/optimize/analyzers/plan_reuse.py Records the complete member-session population on each reuse cluster.
tokenjam/core/optimize/analyzers/workflow_restructure.py Records the complete member-session population on each deterministic workflow cluster.
tokenjam/core/optimize/types.py Extends serialized reuse clusters with backward-compatible member-session metadata.
tests/unit/test_cross_analyzer_recoverable_invariant.py Adds registry-driven window and provider/model spend-ceiling regression coverage.

Reviews (2): Last reviewed commit: "Merge branch 'main' into recoverable-ded..." | Re-trigger Greptile

@anshss
anshss merged commit 45c95b6 into main Aug 4, 2026
6 checks passed
@anilmurty
anilmurty deleted the recoverable-dedup branch September 18, 2026 21:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant