Repository navigation
fix(cost): price Codex rollups, wire exact cost, fix bounded-profile cost gap - #3446
Conversation
…cost Problem: forensic audit of the live archive found 100% of codex-session session_model_usage rows unpriced (cost_usd/priced_with hardcoded NULL by the provider-usage-event rollup writer, which never attempted catalog pricing), plus 5,016 rows self-contradicting cost_provenance='priced' with NULL cost_usd/priced_with (the message-token aggregator wrote that literal unconditionally). Separately, provider-reported exact session cost (_exact_estimate in pricing.py) had zero production callers -- its only would-be caller was a two-line stub -- while two test suites asserted against hand-built CostEstimatePayload literals that verified nothing but pydantic field assignment. What changed: - write.py: _upsert_provider_usage_model_rollup/_increment_provider_usage_ model_rollup now catalog-price the disjoint-lane token totals via a new _price_provider_usage_tokens helper, writing cost_provenance='priced' (with real cost_usd/priced_with) when the catalog covers the model, or NULL (no claim) otherwise. cost_provenance='origin_reported' is now reserved for a genuine provider-reported dollar figure -- these rows never had one (only provider-reported tokens), so relabeling them fixes a real downstream bug: archive.py's list_cost_rollup_insights read 'origin_reported' as provider_reported_usd, so the old mislabeling made a catalog estimate look like OpenAI itself reported that dollar figure. - _aggregate_message_tokens_into_model_usage now writes cost_provenance conditionally (NULL when unpriced) instead of the unconditional 'priced' literal, and its ON-CONFLICT guard is now monotonic (never overwrite a richer token total with a smaller one) instead of keying off the now-repurposed 'origin_reported' label. - _clear_stale_cumulative_rollups and _reextract_provider_usage_tail_db's stale-rollup cleanup now scope by "no genuine per-message token evidence" (a direct check) instead of the same repurposed label. - New session_model_usage CHECK constraints (index.db v49, SEMANTIC_ REPARSE) enforce the invariant going forward: 'priced' requires cost_usd AND priced_with; 'origin_reported' requires cost_usd. - sessions.reported_cost_usd (v49) persists ParsedSession.reported_cost_usd (already parsed for claude-code-session/hermes-session, previously discarded at write time) and is threaded through the read path (ArchiveSessionEnvelope -> Session domain model) to pricing.py's _session_level_estimate, which now builds a real CostEstimatePayload instead of the dead stub. Real production caller: insights/cost_enrichment.py's enrich_session_cost_insight (the `insights costs` / SessionCostInsight surface, reachable via api/insights.py). - Rewired tests/unit/cost/test_contract_suite.py and tests/unit/insights/test_cost_basis_split.py's exact-cost tests to build a real Session with reported_cost_usd set and call estimate_session_cost() on it, instead of hand-building the payload the production function would have produced. Verification: devtools test tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_provider_usage_report.py tests/unit/storage/test_cost_queries.py tests/unit/cost/ tests/unit/insights/test_cost_basis_split.py tests/unit/insights/test_cost_rollup_summary_path.py -- all pass. devtools verify --quick green (ruff, mypy --strict, render, layering, schema-versioning policy). Ref polylogue-shnc, polylogue-gt1z Co-Authored-By: Claude <[email protected]>
Problem: a surface-coherence audit found a probe session costing $9.88 via session_model_usage but $0.00/"unknown" via session_profiles (the API profile reader), because sessions above the bounded-materialization message threshold take a fast path that hardcoded total_cost_usd=0.0 and cost_provenance="unknown" unconditionally, ignoring session_model_usage entirely even when it already had real priced data. Both target sessions in this audit (38baa1de.../53e64853..., 1,861/1,493 messages) hit this exact path on the live archive. What changed: _large_session_profile_record_from_row now reads session_model_usage (a new model_usage parameter, threaded through both the sync and async large-session-bundle builders via sync_model_usage_ batch/get_model_usage_batch) and computes cost the same way ordinary sessions do -- compute_session_cost(dummy_session, estimate_if_missing= False, model_usage=model_usage). This is O(few rows) keyed by (session_id, model_name), not O(message_count), so it does not reintroduce the per-message walk the bounded path exists to avoid. When no session_model_usage rows exist at all, the profile now carries an explicit cost_provenance="unknown_bounded_no_usage_rollup" instead of a bare "unknown" that reads identically to every other missing-cost case. Real production surface: build_large_session_insight_record_bundle_sync/ _async, which every bounded-session materialization path (periodic convergence, hot-source rebuild, heavy-session refresh) calls to populate session_profiles -- the same table session_commit_json/insights costs/ `polylogue read` summaries read from. Known residual (this session's target sessions specifically): claude- opus-5 has no vendored LiteLLM catalog entry, so the corrected cost is honestly NULL/unpriced rather than a specific dollar figure -- a genuine catalog gap, not something this fix can manufacture a price for. Deferred (follow-up beads filed): polylogue-qwgi (no CLI read/MCP get surface exposes per-session cost at all yet -- this fix corrects the materialized number, not surface exposure); polylogue-iuyr (compute_ session_cost's per-model catalog-gap handling silently reports $0.00 with confidence="reported" instead of an honest unknown -- pre-existing, affects bounded and non-bounded paths equally); polylogue-yhgc (archive/ query/ session hydration doesn't carry reported_cost_usd -- explicitly out of scope, that lane belongs to another owner). Verification: devtools test tests/unit/storage/test_session_insight_refresh.py -- 30/30 pass (existing bounded-profile tests don't set model_usage, so they exercise the unchanged empty-model_usage branch; no regression). devtools verify --quick green. Ref polylogue-umfp Co-Authored-By: Claude <[email protected]>
…riant Companion to the previous two commits: several tests hand-insert rows into session_model_usage directly (bypassing the writer) using the old, now- invalid shape -- cost_provenance='priced'/'origin_reported' with a NULL cost_usd or missing priced_with. The new CHECK constraints (index.db v49) reject that shape, which is precisely what they're for (the same contradiction the forensic audit found live: 'priced' rows with no cost, 'origin_reported' rows with no cost). Fixed per-fixture: - Rows with real, catalog-covered tokens (gpt-5-codex, gpt-4o) now assert cost_provenance='priced' with a real computed cost_usd, matching what the writer now actually produces. - Rows modeling "provider gave us tokens but we have no catalog price" now use cost_provenance=NULL (grouped under the "unknown" pricing lane by provider_usage_report_from_connection's COALESCE(cost_provenance, 'unknown')) instead of a mislabeled 'origin_reported' -- renamed test_provider_usage_report_separates_priced_and_origin_reported_ repricing to ...unpriced_repricing to match. - Fixtures that assert cost_provenance='priced' now also insert a matching price_catalogs row so priced_with's foreign key resolves. - tests/unit/devtools/test_claim_vs_evidence.py builds its own bespoke minimal schema (no priced_with column, no CHECK) -- left unchanged, the invariant does not apply there. Verification: devtools test tests/unit/cli/test_insights.py tests/unit/insights/test_cost_rollup_summary_path.py tests/unit/devtools/test_claim_vs_evidence.py tests/unit/devtools/test_cost_reconciliation_probe.py tests/unit/storage/test_lineage_normalization.py -- 76/76 pass. Ref polylogue-shnc Co-Authored-By: Claude <[email protected]>
polylogue-qwgi: no CLI/MCP surface exposes per-session cost yet. polylogue-iuyr: catalog-gap models report a fabricated $0.00 reported cost. polylogue-yhgc: archive/query/ session hydration doesn't carry reported_cost_usd. Co-Authored-By: Claude <[email protected]>
…commit Completes the polylogue-gt1z test rewiring committed in 709b4d1 -- these two files' edits were made in the same working session but missed staging in that commit. Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 41 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (22)
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. Comment |
Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4ec601b5ec
ℹ️ 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".
| provider_project_ref = excluded.provider_project_ref, | ||
| instructions_text = COALESCE(excluded.instructions_text, sessions.instructions_text), | ||
| reported_duration_ms = excluded.reported_duration_ms, | ||
| reported_cost_usd = excluded.reported_cost_usd, |
There was a problem hiding this comment.
Update reported cost on otherwise unchanged reparses
When a Claude or Hermes reparse changes only reported_cost_usd, none of the title/timestamp/message/attachment/event fields in session_content_hash changes, so the unchanged-content path—and the append path when there are no new messages—returns before this assignment executes. The stored value and exact-cost insights therefore remain stale; make reported cost participate in the write decision or refresh it explicitly in the skip paths.
AGENTS.md reference: AGENTS.md:L114-L120
Useful? React with 👍 / 👎.
# Conflicts: # .beads/issues.jsonl
Problem: polylogue-gt1z (false-green audit finding) was dispatched as if it still needed code changes to wire provider-reported session cost through _session_level_estimate and rewrite the two fossilized tests. Re-reading the bead's own reconciliation notes and the current worktree source shows PR #3446 (ed17421) already landed that fix on master and this worktree's HEAD sits on top of it. What changed: no production code -- this is a verification-only commit. Confirmed sessions.reported_cost_usd exists in the index DDL, _session_level_estimate wires _exact_estimate for real, and both test_contract_suite.py and test_cost_basis_split.py build real Session objects and call estimate_session_cost() (no hand-built CostEstimatePayload literals remain). Ran the touched tests (26 passed) and an anti-vacuity check: doubling provider_reported_usd inside _exact_estimate() broke 3 tests through the real production path, confirming genuine coverage. Audited the rest of tests/unit/cost/ plus adjacent cost test files per the bead's own AC and found one unrelated fossilized-payload test (test_cost_basis_split.py::test_cost_rollup_aggregates_basis_and_per_model_breakdown), filed as polylogue-c2qsm rather than folded into this bead's scope. Verification: devtools test tests/unit/cost/test_contract_suite.py tests/unit/insights/test_cost_basis_split.py -> 26 passed. bd export -o .beads/issues.jsonl, JSON-validated all 1540 lines. Co-Authored-By: Claude <[email protected]>
Independently re-confirmed on current HEAD that PR #3446's fix for polylogue-gt1z (provider-reported cost preservation) remains landed: _session_level_estimate wires the real _exact_estimate, and both tests/unit/cost/test_contract_suite.py and tests/unit/insights/test_cost_basis_split.py exercise estimate_session_cost() via a real Session with reported_cost_usd set, not hand-built payloads. Ran the 26 affected tests (all pass) and an anti-vacuity mutation of _exact_estimate's provider_reported_usd assignment, which broke 3 tests through the real path before being reverted, confirming the tests are not tautological. No code changes ship in this commit. The bead stays open pending the operational index v49 reindex (sessions.reported_cost_usd population on the live archive), which is out of scope for a code-lane task. Co-Authored-By: Claude <[email protected]>
Corrections from operator review of the first pass: - polylogue-6e7m dropped entirely: it's a titles/identity architecture question explicitly redirected away from materialization-time storage (operator ruling 2026-07-29), so it never interacts with what a reindex bakes into index.db. - polylogue-shnc, polylogue-6j9c reclassified from "blocks a7gmk" to "resolved by 818fy": both have their code fix already merged (PR #3446, PR #3511 respectively), confirmed by repeated reconciliation notes; the only remaining work is the SEMANTIC_REPARSE reindex itself. - polylogue-zqph reclassified the same way: its own 2026-08-02 note concludes the reindex naturally satisfies its repair goal since the underlying classifier fix is already deployed. - polylogue-5fh4/o56w/623q (rebuild-index performance) reclassified from "blocks a7gmk" to "resolved by 818fy": their own exit criteria are literally a measured receipt from a real rebuild -- they can't close before the reindex runs, only after it. - polylogue-t93b, polylogue-x1gd added as resolved-by-818fy (mechanism/fix already landed, blocked purely on the rebuild). New blockers on a7gmk: polylogue-9kc0 (cgroup MemoryHigh>MemoryMax incoherence, OOM-risk sibling of e98k), polylogue-aex0 (unresolved cursor-durability architecture decision -- ops.db resets, including index rebuilds, already wipe append-delta cursor state per its own root-cause notes), polylogue-cijx.2 (repo-identity materialization-time bug, still unfixed), polylogue-6krh (convergence-debt deferrals mislabeled 'failed', would misreport as alarms during the reindex's own convergence wave). New blocker on f1vg: polylogue-4zqh3 (hermes/chatgpt capture gaps feeding f1vg's own absence/attachment-fidelity measures). Ref polylogue-818fy Co-Authored-By: Claude <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Three related cost-accounting bugs, found by a forensic audit of the live
archive and fixed together because they share one root file
(
storage/sqlite/archive_tiers/write.py) and one schema bump (index.db v49):session_model_usagerows werehardcoded unpriced, and 5,055 live rows asserted
cost_provenance='priced'with NULL cost/catalog — a label that lies.
(
_exact_estimate) had zero production callers; two test suites verifiedonly that pydantic returns fields it was just assigned.
total_cost_usd=0.0/cost_provenance="unknown", ignoringsession_model_usageeven when it had real priced data.Problem (evidence)
Live archive (
index.db, read-only, 2026-07-31):codex-session: 3,153/3,153 rows unpriced (100%), confirmingpolylogue-shnc's forensics. Root cause traced to
_upsert_provider_usage_model_rollup/_increment_provider_usage_model_rollup(the Codex cumulative-
token_count-event rollup writer) hardcodingcost_usd=NULL/priced_with=NULLunconditionally — pricing was neverattempted on that path.
gpt-5-codex/gpt-5.4/gpt-4oetc. are in thevendored LiteLLM catalog; this was a writer bug, not a catalog gap.
_aggregate_message_tokens_into_model_usage(the message-token-walk pricer)separately wrote the literal
'priced'unconditionally, even when the modelhad no catalog price — the source of the 5,055 self-contradictory rows.
For polylogue-gt1z:
pricing.py:_session_level_estimatewasdef _session_level_estimate(session): del session; return None—estimate_session_cost'sstatus == "exact"branch was structurallyunreachable.
tests/unit/cost/test_contract_suite.py:109-125andtests/unit/insights/test_cost_basis_split.py:56-71both hand-built aCostEstimatePayloadwithprovenance=("archive_session_reported_cost",)—a string that appeared nowhere in
polylogue/outside those two tests.For polylogue-umfp: both target sessions in this batch
(
claude-code-session:38baa1de-9715-48fa-8175-f2a29d92800e,claude-code-session:53e64853-1793-43d2-80ac-a41a8c5a56a2, 1,861/1,493messages) hit the bounded-materialization fast path
(
workflow_shape='bounded_large_session') and their profiles carriedtotal_cost_usd=0.0/cost_provenance='unknown'despitesession_model_usagealready holding real token totals(claude-opus-5, ~1.8M output tokens on one of them).
Solution
_price_provider_usage_tokenshelper catalog-pricesCodex rollup token totals;
cost_provenance='priced'(with realcost_usd/priced_with) when the catalog covers the model,NULL(noclaim) otherwise.
cost_provenance='origin_reported'is now reserved for agenuine provider-reported dollar figure — these rows never had one
(only provider-reported tokens), and the old mislabeling made
archive.py:list_cost_rollup_insightsread a catalog estimate as if theprovider itself had reported that dollar figure.
_aggregate_message_tokens_into_model_usagenow writescost_provenanceconditionally instead of the unconditional
'priced'literal; itsON-CONFLICT guard is now monotonic (never overwrite a richer token total
with a smaller one) instead of keying off the now-repurposed
'origin_reported'label._clear_stale_cumulative_rollupsand_reextract_provider_usage_tail_db's cleanup now scope by "no genuineper-message token evidence" (a direct check) for the same reason.
priced ⇒ cost_usd AND priced_with NOT NULL;origin_reported ⇒ cost_usd NOT NULL. Enforces theinvariant going forward; several test fixtures that hand-inserted the old
self-contradictory shape needed updating to stay valid.
sessions.reported_cost_usd(v49) persistsParsedSession.reported_cost_usd(already parsed forclaude-code-session/hermes-session, previously discarded — the DB mirror
table was dropped in polylogue-v2mg as zero-consumer) and is threaded
through the read path (
ArchiveSessionEnvelope→Sessiondomain model)to
_session_level_estimate, which now returns a realCostEstimatePayload. Real caller:insights/cost_enrichment.py:enrich_session_cost_insight, reachable viaapi/insights.py(theinsights costs/SessionCostInsightsurface).Rewrote both phantom tests to build a real
Sessionwithreported_cost_usdset and callestimate_session_cost()on it._large_session_profile_record_from_rownow readssession_model_usage(O(few rows), not O(message_count) — doesn'treintroduce the walk bounded-mode exists to avoid) and computes cost the
same way ordinary sessions do. No usage rows → explicit
cost_provenance="unknown_bounded_no_usage_rollup"instead of a bare"unknown"indistinguishable from every other missing-cost case.Both schema deltas are batched into one
INDEX_SCHEMA_VERSION = 49(
SEMANTIC_REPARSE, declared inlifecycle.py), matching the v46 "one bumpcovering every field" precedent. Not executed against the live archive
by this PR — that requires
polylogue ops reset --index && polylogued run,which per
index.py's own v48 precedent an agent must not trigger withoutexplicit operator scheduling.
AC disposition
polylogue-shnc
entries, writer bug fixed) + surfaces claude-sonnet-5 as an honest
catalog gap (not in the vendored LiteLLM snapshot — genuinely too new,
not fabricated).
priced/origin_reportedkeep their names,origin_reported's meaningis now precisely "genuine provider-reported dollar figure").
polylogue ops reset --index && polylogued run, not run by this PR(operator-scheduled per project policy).
polylogue-gt1z
implemented for real (operator's explicit steering: "prefer implementing
it: provider-reported cost IS available in the raw for several origins").
_exact_estimatewired into_session_level_estimatewith a namedproduction caller (
cost_enrichment.py).estimate_session_cost()on a realSession._exact_estimate's body is broken (it now runsthrough the real function, not a hand-built literal).
archive/query/session hydration doesn't carryreported_cost_usdyet (explicit AVOID-list scope, filed aspolylogue-yhgc).
polylogue-umfp
session_model_usageauthority ordinary profiles do.read --json) or MCP (get) surface exposes theper-session cost number yet — filed as polylogue-qwgi (this PR fixes the
materialized number; surface exposure is a separate, real scope item).
Follow-ups filed
compute_session_costsilently reports$0.00/confidence=reportedfor catalog-gap models (pre-existing, affects bounded and non-bounded paths equally).
reported_cost_usdthrougharchive/query/session hydration.Verification
→ 606/608 pass (2 pre-existing, unrelated failures confirmed via
git stashagainst the same baseline: a hardcoded-timestamp clock-hygiene test and an
evidence-preview title-string test, neither touching cost/pricing code).
devtools verify --quickgreen: ruff format/lint,mypy --strict,render all --check, layering, closure-matrix,lab policy schema-versioning,schema promotion audit.
Not run:
devtools verify --all(full non-integration suite) orintegration tests — narrower targeted selection above covers every touched
file.