Skip to content

fix(cost): reconcile cost outlook with typed/storage contracts (#870) - #987

Closed
Sinity wants to merge 2 commits into
masterfrom
worktree-agent-ad1ebfb0
Closed

Sinity wants to merge 2 commits into
masterfrom
worktree-agent-ad1ebfb0

Conversation

@Sinity

@Sinity Sinity commented May 9, 2026

Copy link
Copy Markdown
Owner

Summary

Fix lint/type errors and contract mismatches in the cost modules. Make
outlook return typed Pydantic models, remove dict hack on frozen model,
add semantic module re-exports, simplify CLI cost wiring, and pin cost
contract validation in tests.

Problem

Per #870 reconciler note: semantic cost files had formatting issues,
outlook.py returned raw dicts instead of typed models, cost_compute.py
used dict.update() on a frozen Pydantic model, session-profile cost
fields were not validated against cost records, and test_cost_queries.py
lacked contract-alignment tests.

Solution

  • outlook.py: compute_usage_outlook now returns UsageOutlookPayload,
    build_subscription_cycle returns SubscriptionCycle, helpers return
    typed models (AnomalyPayload, ModelBreakdownPayload)
  • cost_compute.py: _add_provider_reported_tokens returns a new
    SessionCostBreakdown instead of mutating via dict.update()
  • init.py: re-exports public API from cost_records, pricing,
    subscription_models, subscription_pricing
  • cost.py: removed redundant model_validate after outlook returns
    typed models
  • test_cost_queries.py: added contract-alignment test for
    SessionProfileRecord vs SessionCostSummary field mapping, JSON
    roundtrip test for per_model serialization, and test that
    compute_usage_outlook returns a typed model

Verification

ruff check polylogue/archive/semantic/ tests/unit/storage/test_cost_queries.py  # ok
ruff format --check polylogue/archive/semantic/ tests/unit/storage/test_cost_queries.py  # ok
mypy --strict polylogue/archive/semantic/outlook.py polylogue/archive/semantic/cost_compute.py ...  # ok
pytest -q tests/unit/storage/ -k cost -v  # 7 passed in 14.28s

Cert block

🤖 Generated with Claude Code

Sinity and others added 2 commits May 9, 2026 14:14
Fix lint/type errors in outlook.py, align session-profile cost fields
with storage contracts, and reconcile test_cost_queries.py expectations
with actual cost return types.

Refs #870
Problem: The archive.semantic __init__.py was empty, the CLI cost command
had a redundant model_validate, and test_cost_queries.py lacked contract
validation between SessionCostSummary and SessionProfileRecord.

Solution: Add typed re-exports to __init__.py, simplify CLI cost command
to use the now-typed outlook return, and add contract-alignment tests
that pin field mappings and JSON roundtrip expectations.

Ref #870

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 9, 2026 12:22
@coderabbitai

coderabbitai Bot commented May 9, 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 22 minutes and 43 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: cb344b4a-558c-4d7c-b0dd-2e621b1166e6

📥 Commits

Reviewing files that changed from the base of the PR and between 02f86f8 and c387a4f.

📒 Files selected for processing (5)
  • polylogue/archive/semantic/__init__.py
  • polylogue/archive/semantic/cost_compute.py
  • polylogue/archive/semantic/outlook.py
  • polylogue/cli/commands/cost.py
  • tests/unit/storage/test_cost_queries.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-agent-ad1ebfb0

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 commented May 9, 2026

Copy link
Copy Markdown
Owner Author

Superseded by #984 (merged) — same fix, agent timing artifact. #870 already closed.

@Sinity Sinity closed this May 9, 2026
@Sinity
Sinity removed the request for review from Copilot May 9, 2026 12:43
@Sinity
Sinity deleted the worktree-agent-ad1ebfb0 branch May 11, 2026 07:01
Sinity added a commit that referenced this pull request May 17, 2026
…1166)

## 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.

- #803 explicitly required separating ``provider_reported_usd``,
``api_equivalent_usd``, ``subscription_equivalent_usd``,
``catalog_priced_usd``, and ``tool_surcharge_usd``.
- #870 AC required API-equivalent value and subscription quota/burn as
separate fields.
- PR #987 (which closed #870) was lint/type cleanup only; the basis
split never landed.
- #803 also called out "Per-model breakdown in cost surfaces" as an
explicit carry-over.

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](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[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.

1 participant