Skip to content

feat(cost): per-basis cost rollup with per-model breakdown (#1136) - #1166

Merged
Sinity merged 2 commits into
masterfrom
feature/feat/cost-basis-split-v2
May 17, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/feat/cost-basis-split-v2

Conversation

@Sinity

@Sinity Sinity commented May 17, 2026

Copy link
Copy Markdown
Owner

Summary

Splits cost rollups across the five basis axes (#803/#870 carry-over) and adds per-model breakdowns to both session-cost and cost-rollup insights. Every unavailable row now carries a discrete reason so consumers can render "why" instead of an opaque zero. Closes #1136.

Problem

Cost rollups today expose a single total_cost_usd per session.

Consumers querying CostRollupInsight.total_usd cannot distinguish "this session billed $1.25 against the API" from "this session would cost $1.25 against the catalog if billed via API" from "this session burned X subscription credits". Mixed-model sessions collapse into one row keyed by the dominant model.

Solution

Typed basis split. CostBasisPayload carries the five basis axes as independent fields. Same usage may be expressed on more than one axis (e.g. a provider-reported total alongside a parallel catalog-priced reconciliation), so basis values do not sum to total_usd. total_usd remains the legacy single-number summary for backwards compatibility — documented as drawing from provider_reported_usd when present, otherwise from catalog_priced_usd.

Per-model breakdown. CostModelBreakdown rows hang off both:

  • CostEstimatePayload.per_model_breakdown (session scope) — built in estimate_conversation_cost by grouping message estimates by (model_name, normalized_model).
  • CostRollupInsight.per_model_breakdown (cross-session scope) — aggregated by aggregate_cost_rollup_insights in insights/archive_rollups.py. Sessions with no breakdown contribute a single synthesized row from the dominant model so provider-reported-only sessions still surface per-model context.

Mixed-model sessions return one row per model, ranked by total_usd desc. Nothing is collapsed.

Unavailable reasons. CostEstimatePayload.unavailable_reason (CostUnavailableReason literal) enumerates no_model, no_price, no_tokens, provider_zero, subscription_unconfigured, no_messages. Rollups carry unavailable_reason_counts so a consumer can see "12 sessions unavailable: 8 no_tokens, 4 no_model".

Surfaces. Existing CLI/MCP envelopes update automatically: cost_rollups registry adds provider_usd/api_usd/sub_usd/catalog_usd columns alongside the existing total; CostRollupInsight.model_dump carries the full basis and per_model_breakdown shapes through JSON.

Refactor. operations/archive.py:list_cost_rollup_insights shrinks to a thin orchestrator over the new aggregate_cost_rollup_insights helper, keeping operations/archive.py under its 1200-line budget.

Files touched:

  • polylogue/archive/semantic/pricing.py — CostBasisPayload, CostModelBreakdown, CostUnavailableReason, CostBasis; _exact_estimate/_estimate_from_usage/estimate_conversation_cost populate basis and breakdown
  • polylogue/insights/archive.py — CostRollupInsight gains basis, unavailable_reason_counts, per_model_breakdown
  • polylogue/insights/archive_rollups.py — new aggregate_cost_rollup_insights + helpers
  • polylogue/insights/registry.py — basis columns in cost_rollups field list
  • polylogue/operations/archive.py — call the new aggregator
  • tests/unit/insights/test_cost_basis_split.py — 7 new contracts

Non-goals: no new pricing catalog sources, no tokenizer changes, no CLI/MCP surface changes beyond the auto-generated registry columns. Surface-facing children land separately.

Verification

  • nix develop -c pytest tests/unit/insights/test_cost_basis_split.py tests/unit/core/test_pricing.py tests/unit/insights/ tests/unit/mcp/ tests/unit/cli/test_insights.py -q → 288 passed
  • nix develop -c devtools verify --quick → exit_code: 0 (mypy --strict, ruff, render-all --check, file budgets all green)
  • nix develop -c mypy polylogue tests devtools → Success: no issues found in 1395 source files

Closes #1136.

🤖 Generated with Claude Code

Sinity and others added 2 commits May 17, 2026 11:30
Cost rollups today expose a single ``total_cost_usd`` per session. #803
explicitly required separating cost bases and #870 AC required
API-equivalent and subscription quota/burn as separate fields. PR #987
closed #870 with lint/type cleanup only; the basis split never landed.

Extend the typed cost read model with a ``CostBasisPayload`` carrying
``provider_reported_usd``, ``api_equivalent_usd``,
``subscription_equivalent_usd``, ``catalog_priced_usd``, and
``tool_surcharge_usd`` as independent axes. Same usage may be expressed
on more than one axis (e.g. a provider-reported total alongside a
parallel catalog-priced reconciliation), so values do not sum to
``total_usd``; ``total_usd`` remains the legacy summary draw for
backwards compatibility and is documented as drawing from
``provider_reported`` when an exact total is present, otherwise from
``catalog_priced``.

Add ``CostModelBreakdown`` and surface a per-model breakdown on both
``CostEstimatePayload.per_model_breakdown`` (session scope) and
``CostRollupInsight.per_model_breakdown`` (cross-session scope). Mixed-
model sessions return one row per model; nothing is collapsed.

``CostEstimatePayload.unavailable_reason`` enumerates ``no_model``,
``no_price``, ``no_tokens``, ``provider_zero``,
``subscription_unconfigured``, and ``no_messages`` so consumers can
render "why" instead of an opaque zero.

Wire ``list_cost_rollup_insights`` to aggregate the basis axes,
accumulate ``unavailable_reason_counts``, and merge per-model rows
across sessions (incrementing ``session_count`` per merged model).
Expose the new basis fields in the ``cost_rollups`` insight registry so
they appear in CLI and MCP envelopes alongside the existing total.

Closes #1136.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Move the per-group basis + per-model breakdown reduction out of
``operations/archive.py:list_cost_rollup_insights`` and into a typed
helper ``aggregate_cost_rollup_insights`` in ``insights/archive_rollups.py``.
Keeps ``operations/archive.py`` under its 1200-line budget and colocates
the rollup logic with the other archive insight aggregators.

No behavior change.

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

coderabbitai Bot commented May 17, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 24 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b0155a53-64e2-4067-8192-58580dd079f1

📥 Commits

Reviewing files that changed from the base of the PR and between c7fc08a and 40f78d8.

📒 Files selected for processing (6)
  • polylogue/archive/semantic/pricing.py
  • polylogue/insights/archive.py
  • polylogue/insights/archive_rollups.py
  • polylogue/insights/registry.py
  • polylogue/operations/archive.py
  • tests/unit/insights/test_cost_basis_split.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/cost-basis-split-v2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit 7261aeb into master May 17, 2026
4 checks passed
@Sinity
Sinity deleted the feature/feat/cost-basis-split-v2 branch May 17, 2026 09:42

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

if conversation_estimate is not None and conversation_estimate.status == "priced":
# Prefer conversation-level usage when present; it avoids double-counting
# per-message fallbacks from providers that report only session totals.
return conversation_estimate

P1 Badge Preserve per-model breakdown for priced conversation estimates

When a session has provider-level usage (conversation_estimate.status == "priced") and also message-level model data, this early return bypasses the newly computed per_model_breakdown and returns the conversation-level estimate as-is. In that case mixed-model sessions are collapsed to a single dominant model row, so downstream rollups lose the per-model split introduced in this change. This is most visible for exports that include both aggregate session usage and per-message model/tokens.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant