Skip to content

#111: Add estimated_recoverable_usd to every savings analyzer - #119

Merged
anilmurty merged 3 commits into
mainfrom
feature/111-recoverable-usd
Jun 18, 2026
Merged

anilmurty merged 3 commits into
mainfrom
feature/111-recoverable-usd

Conversation

@anilmurty

Copy link
Copy Markdown
Contributor

Closes #111.

Every analyzer that produces a usable recommendation now also produces a
consistent, heuristic estimated-recoverable figure, so the Lens Overview can
summarize "recoverable waste" in one band. The honesty discipline carries
forward — every number is "estimated recoverable", never "saves you", and each
analyzer keeps its existing caveat language.

Contract (added to each savings analyzer's result dataclass)

  • estimated_recoverable_usd: float | None — api-billed framing
  • estimated_recoverable_tokens: int | None — subscription / local framing
  • estimate_basis: str — one-line heuristic explanation (the "estimated" tag's hover text)
  • estimate_confidence: str = "heuristic" — named distinctly from the
    pre-existing structural confidence field on the wave-2 findings to avoid a
    semantic clash.

None means "no estimate for this finding state" (e.g. trim with capture off).

Per-analyzer heuristic

  • downsize — aliases the existing monthly_savings_usd; tokens from candidate_tokens.
  • cache — gap to an 80% efficacy ceiling × input tokens × (input − cache-read rate delta), summed across rows. None for models with no cache-read rate.
  • script — full cost (and tokens) of the sessions in each deterministic cluster.
  • trim — low-significance tokens × window-average input rate. None when capture is off or llmlingua is missing.
  • cache-recommend / budget-projection — intentionally emit no figure (not savings analyzers).

Plumbing

  • Fields serialize through report_to_dict (so /api/v1/optimize carries them) and round-trip through report_from_dict.
  • CLI rendering is unchanged — the new fields are read by the API/UI, not the existing render paths.

Tests

tests/unit/test_optimize_recoverable.py: per-analyzer USD within a
hand-calculated bound, None in not-ready states, non-empty estimate_basis,
and a report_to_dict / report_from_dict round-trip. Full suite green; mypy
and ruff clean.

Scope guardrails honoured

No new analyzer; no change to which analyzers run by default; registry pattern
unchanged; CLI output format unchanged.

Give every analyzer that produces a usable recommendation a consistent,
heuristic estimated-recoverable figure so it can be summarized in one place.

New fields on the result dataclasses (downsize/cache/script/trim):
  estimated_recoverable_usd, estimated_recoverable_tokens, estimate_basis,
  estimate_confidence (always "heuristic" in v1; named distinctly from the
  pre-existing structural `confidence` on wave-2 findings to avoid a clash).

Per-analyzer heuristics:
- downsize: aliases the existing monthly_savings_usd; tokens from candidate_tokens.
- cache: gap to an 80% efficacy ceiling × input tokens × (input − cache-read
  rate delta), summed across rows; None for models with no cache-read rate.
- script: full cost (and tokens) of sessions in each deterministic cluster.
- trim: low-significance tokens × window-average input rate; None when capture
  is off or llmlingua is missing.

cache-recommend and budget-projection intentionally do not emit a figure.

Estimates serialize through report_to_dict (so /api/v1/optimize carries them)
and round-trip through report_from_dict. CLI rendering is unchanged — the new
fields are read by the API/UI, not the existing render paths. Every analyzer's
caveat language is preserved.

Tests: per-analyzer USD within a hand-calculated bound, None in not-ready
states, non-empty estimate_basis, and a report_to_dict/from_dict round trip.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@anilmurty anilmurty left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: ✅ Approve with nits

Acceptance criteria — all met:

  1. ✓ confidence → estimate_confidence rename is justified. Wave-2 findings (cache_efficacy.py:71, prompt_bloat.py:102, workflow_restructure.py:102, cache_recommend.py:53) already use confidence: "structural" for a different axis (structural vs replay_validated). The new estimate_confidence: "heuristic" describes a different axis. Collapsing would have been semantic overloading.
  2. ✓ model_downgrade.py:206 is a literal alias — estimated_recoverable_usd and monthly_savings_usd share the same computed value.
  3. ✓ cache_efficacy.py:80-115 formula matches spec: gap = max(0, 0.80 − efficacy) × cacheable input tokens × (input rate − cache-read rate). EFFICACY_CEILING = 0.80 is a module constant (line 63). Skips rows when cache_read_per_mtok <= 0 (line 98) and when rate_delta <= 0 (line 101).
  4. ✓ prompt_bloat.py returns None in both not-ready states (capture off at :287-294, llmlingua missing at :301-306). _window_avg_input_rate is token-weighted across the actual model mix — better than spec.
  5. ✓ cache-recommend and budget-projection untouched (correct — not savings analyzers).
  6. ✓ CLI render paths don't read the new fields. Round-trip works via runner.py:250-380 asdict/constructor paths.
  7. ✓ Tests cover USD bounds, None in not-ready states, non-empty basis, round-trip.

Nits / follow-ups (non-blocking):

  • runner.py:42 — _utcnow() uses datetime.now(tz=timezone.utc) rather than tokenjam.utils.time_parse.utcnow() (CLAUDE.md rule #9). Pre-existing, not introduced by this PR, but the file is touched here — easy to clean up while we're at it.
  • tests/unit/test_optimize_recoverable.py:195 — assert finding.estimate_basis == "" or finding.estimate_basis is not None is a tautology ("" is not None, so the right operand is always true). Likely meant == "" for the not-ready case.
  • prompt_bloat.py:396 — low_sig_tokens = total_bloat / CHARS_PER_TOKEN where CHARS_PER_TOKEN = 4. Reasonable approximation for English prose, but the estimate_basis string doesn't disclose the conversion. Worth surfacing in the UI hover text once Lens lands.
  • workflow_restructure.py:194 — cluster_cost is the full historical cost of clustered sessions, not window-normalized. Basis text is honest, but the figure isn't directly comparable to monthly-projected numbers on other tiles. Follow-up to either window-normalize or annotate the time basis explicitly.

CI green on 3.10 / 3.11 / 3.12 + TS. No blockers. Good to merge.

- runner.py: _utcnow() and report_from_dict fallbacks now use
  tokenjam.utils.time_parse.utcnow() instead of datetime.now(tz=timezone.utc)
  (CLAUDE.md Rule 9).
- test_optimize_recoverable.py: the not-ready trim assertion was a tautology;
  assert estimate_basis == "" for that path.

Addresses PR #119 review nits.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@anilmurty

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review! Addressed in 04f3330:

  1. runner.py Rule 9 — _utcnow() and the report_from_dict fallbacks now use tokenjam.utils.time_parse.utcnow() instead of datetime.now(tz=timezone.utc).
  2. Tautological assert — fixed; the not-ready trim path asserts estimate_basis == "".

For the two follow-ups (script estimate is full-historical vs monthly-projected on other tiles + CHARS_PER_TOKEN disclosure in hover text), filed #122 so they're tracked for when the Overview band lands — kept out of this PR to stay focused.

@anilmurty
anilmurty merged commit 4b18aa5 into main Jun 18, 2026
4 checks passed
@anilmurty
anilmurty deleted the feature/111-recoverable-usd branch June 18, 2026 05:09
anshss added a commit that referenced this pull request Jul 9, 2026
fix: quota-weight quickstart headline, drop named-session reclaim list (#119)
anshss added a commit that referenced this pull request Jul 9, 2026
Combining #437 (ticket-119: aggregate reclaim line, never names a past
session) with #438 (statusline live preview: shows the exact statusline
line one concrete named session would have triggered, by design) broke
CI: test_quickstart_reclaim_section_is_aggregate_not_named_sessions
asserted "sess-heavy" absent from the ENTIRE quickstart output, which
was true when #437 was authored (quickstart never named a session
anywhere) but stopped being true once #438 added a later section that
intentionally names its preview session as a concrete "what you'd have
seen live" example — itself covered by dedicated #438 tests
(`test_quickstart.py` asserts "session sess-recent would have shown
this at turn 3" / "session sess-old ... turn 5").

Both invariants are correct and neither feature should be reverted:
the quota-composition PANEL must never name a session (#119's actual
intent — see the "(#119)" comment at cmd_quickstart.py's aggregate
line), while the separate, later statusline-preview section legitimately
does. Scoped the assertion to the panel's own text (everything before
the preview section's fixed intro, "With the statusline installed")
instead of the whole rendered output.

Co-Authored-By: Claude <[email protected]>
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.

[feature] Add estimated_recoverable_usd to every optimize analyzer

1 participant