Repository navigation
fix(cost): strip aistudio-drive models/ prefix, honest zero-token provenance - #3511
Conversation
Problem: aistudio-drive's parser stores the raw Gemini API resource-path model identifier verbatim (e.g. models/gemini-2.5-pro). pricing.py's _normalize_model() stripped openai/, anthropic/, google/, and gemini/ prefixes but never models/, so every aistudio-drive usage row failed both the exact-match catalog lookup and the prefix-fallback lookup and priced at $0.0. Measured on the live archive: 239 session_model_usage rows / 17 distinct model names / 105.7M tokens across aistudio-drive, all priced to cost_provenance=provider_reported, total_cost_usd=0.0, despite the catalog carrying real per-token rates for the underlying models (confirmed by gemini-cli-session, same model family without the prefix, pricing correctly on comparable volumes). Solution: strip a leading models/ segment in _normalize_model() before catalog lookup, alongside the existing vendor prefixes. Verification: devtools test tests/unit/core/test_pricing.py -- 21 passed, including new test_aistudio_drive_resource_path_model_prices_like_bare_form which prices models/gemini-2.5-pro against the bare form and asserts equal, nonzero cost. Anti-vacuity: the test exercises estimate_cost() (the production entry point every session/message cost estimate calls) via _normalize_model(); reverting the models/ removeprefix() line makes it fail. Ref polylogue-6j9c
Problem: cost_compute.py's _per_model_from_model_usage() unconditionally stamped confidence=reported/provenance=provider_reported on every session_model_usage row it built, regardless of whether the row carried real nonzero token counts. Origins whose exports don't carry provider token counters at all (chatgpt-export, claude-ai-export -- both declared "estimate-only" in docs/cost-model.md) still get session_model_usage rows with a real model_name but zero tokens, so every one of those sessions got labelled as if the provider itself reported and billed a zero cost. Measured on the live archive: 2,264 chatgpt-export session_profiles rows with cost_provenance=provider_reported and total_cost_usd=0.0 across the board (sum=0.0, avg=0.0); claude-ai-export had 55 more via a related compute_session_cost aggregation gap (see below). Also: compute_session_cost's aggregation defaulted agg_confidence to "reported" and only ever downgraded it to "estimated", never to "unknown" -- so a session whose only per-model breakdowns already carried the record default confidence="unknown" (e.g. claude-ai-export sessions with no model_usage rows at all and no per-message token/word evidence) still surfaced as cost_provenance=provider_reported. Solution: - _per_model_from_model_usage() now downgrades any row whose aggregated tokens are zero to confidence=unknown/provenance=unknown, so a model-identity-only fact is never conflated with real provider-reported usage. - compute_session_cost() now falls back to the existing text-length heuristic (_per_model_from_messages(), estimate_tokens_from_words) when every model_usage-derived breakdown is zero-token but the session's messages carry real text -- this is the "estimate-only" path docs/cost-model.md already declares for these origins, previously unreachable because model_usage rows short-circuited the fallback. - Aggregation now tracks has_reported alongside has_estimates, so a session with only unknown-confidence breakdowns and no fallback evidence gets cost_confidence=unknown / cost_provenance=unknown instead of defaulting to "reported". Verification: devtools test tests/unit/core/test_cost_compute.py (new, 4 passed) + tests/unit/storage/test_session_profile_model_usage_consistency.py tests/unit/insights/test_cost_basis_split.py tests/unit/storage/test_cost_queries.py tests/unit/cost/test_contract_suite.py tests/unit/daemon/test_cost_panel_endpoint.py tests/unit/daemon/test_provider_usage_endpoint.py tests/unit/storage/test_provider_usage_report.py tests/unit/storage/test_session_usage_reconciliation.py -- 77 passed, no regressions. devtools verify --quick -- all 18 steps exit 0. Anti-vacuity: tests call compute_session_cost() and _per_model_from_model_usage() (the exact production functions session_profile.py/rebuild.py invoke to build every session_profiles cost row). Reverting either the zero-token confidence downgrade or the has_reported aggregation fix makes the corresponding new test fail. Residual: existing live-archive session_profiles rows already written with the old mislabeling are NOT reclassified by this change (code fix + test coverage only, per lane scope) -- a reprice/relabel pass over the live archive is a separate ops concern. Ref polylogue-9kjtc
|
Warning Review limit reached
Next review available in: 45 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 (4)
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a75beb7711
ℹ️ 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".
Co-Authored-By: Claude <[email protected]>
…unknown aggregates Problem: PR #3511's estimate-fallback path (_per_model_from_messages) had two review-confirmed bugs. (1) It grouped every message's word-count estimate into input_tokens regardless of role, and model-less turns (routine for ChatGPT/ Claude-web user turns, which lack per-message model_slug) fell into an unpriced "unknown" bucket while the assistant's own reply text was priced entirely at the model's input rate -- systematically understating cost since output tokens are typically priced higher. (2) compute_session_cost's aggregate confidence/provenance labeling only downgraded away from "reported" when EVERY per-model breakdown was unknown, so a mixed session with one genuine nonzero usage row and one zero-token _seed_session_model_usage_rows skeleton row for a different model kept has_reported=true/has_estimates=false and read as a clean "reported" aggregate despite one breakdown being separately marked unknown. What changed: _per_model_from_messages now (a) computes the session's dominant declared model via the same Counter/most_common pattern pricing.py's _session_level_estimate uses, and falls model-less messages back to it instead of an "unknown" key; (b) classifies each message's word-count estimate by role via estimate_tokens_from_words_split -- user/ human turns become input_tokens, assistant turns become output_tokens. compute_session_cost's aggregate loop now tracks has_unknown and downgrades to the existing "partial" CostConfidence value whenever any breakdown is unknown alongside a reported/estimated one, mapping to the existing "mixed" cost_provenance value. Tests: two focused regression tests in tests/unit/core/test_cost_compute.py. Anti-vacuity: reverting the dominant-model-fallback/role-split change to _per_model_from_messages fails test_per_model_from_messages_splits_estimated_tokens_by_role_with_dominant_model_fallback (verified by stashing the production change and re-running -- the model-less user turn's tokens land in an "unknown" key). Reverting the has_unknown branch in compute_session_cost's aggregate loop fails test_compute_session_cost_downgrades_to_partial_when_one_model_unknown_alongside_reported (aggregate stays "reported" instead of "partial"). Verification: - devtools test tests/unit/core/test_cost_compute.py tests/unit/storage/test_session_profile_model_usage_consistency.py polylogue/archive/semantic/cost_compute.py -> 10 passed - devtools verify --quick -> exit 0 (ruff format/check, mypy --strict, render all --check, layering, closure-matrix, schema policies all ok) Ref polylogue-3b607 Ref polylogue-9kjtc Co-Authored-By: Claude <[email protected]>
…socket and demo-hardening findings Merged PR #3511 (polylogue-3b607) and PR #3512 (polylogue-373yt), closed both. Filed polylogue-kadx3 (P0: daemon UDS socket path not archive-scoped, found live during PR #3517 perf work) and polylogue-dl6af (3 new review findings on PR #3516's demo self-heal guard). Closed PR #3515 as superseded by #3516.
…jtc, bvnz, 5vbs) Reconciliation pass driven by devtools lab probe bead-pr-reconciliation: verified each bead's own acceptance criteria against the actual diff/AC matrix of its referencing merged PR(s), not just the PR's self-description. Closed (AC fully satisfied): - polylogue-bvnz: PR #3504, all 5 AC items satisfied. - polylogue-5vbs: PR #3439, AC's detection/repair branch satisfied via new daemon/fts_orphan_audit.py sweep. Left open with progress notes (partial, residual scope named): - polylogue-layg.1: PR #3486 satisfies 6/8 AC items; scale fixture + coverage manifest update still missing. - polylogue-hjpx: PR #3485 confirms AC1-5 satisfied (mostly by pre-existing landed work whose ancestry the bead's own stale note had missed), but bd close refuses on open child polylogue-yla8 (the live closure-gate audit AC1-5 doesn't substitute for). - polylogue-6j9c, polylogue-9kjtc: PR #3511 satisfies 2/3 AC items each; live-archive reprice pass over existing session_profiles rows still outstanding for both. Ref polylogue-93xe 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. |
|
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
Two related cost-accounting bugs from a fresh forensics pass (2026-08-01,
read-only census against
index.db):tokens because
pricing.py's_normalize_model()never stripped themodels/resource-path prefix aistudio-drive's own parser writes verbatim.cost_compute.pyunconditionally labelled everysession_model_usagerowconfidence=reported/provenance=provider_reportedregardless of whether it carried real nonzero tokens, mislabeling 2,264
chatgpt-export (+55 claude-ai-export) zero-token stub rows as if the
provider itself reported and billed $0.
Problem
#1 (polylogue-6j9c): aistudio-drive's parser (
sources/parsers/drive.py)stores the Gemini API resource-path model identifier verbatim, e.g.
models/gemini-2.5-pro(confirmed againsttests/unit/sources/test_gemini_drive_normalization_laws.pyandtests/unit/core/test_schema_generation.py)._normalize_model()strippedopenai//anthropic//google//gemini/but nevermodels/, so this formfailed both the exact-match catalog lookup and the prefix-fallback lookup.
Measured on the live archive: 239
session_model_usagerows / 17 distinctmodel names / 105,687,388 tokens across
aistudio-drive, all pricing tocost_provenance=provider_reported,total_cost_usd=0.0for all 183session_profilesrows in that bucket — despite the catalog carrying realper-token rates for the underlying models (e.g.
PRICING['gemini-2.5-pro'] = 1.25/10.0USD/M input/output).Cross-check:
gemini-cli-sessionuses the bare model name for the samemodel family and prices correctly on comparable volumes (e.g.
gemini-3.1-pro-preview, 6.3M tokens → $23.68).#2 (polylogue-9kjtc):
_per_model_from_model_usage()'s docstring claimed"every row is provider-reported evidence by construction," which is true of
the row's existence but not of whether it carries real usage counts.
chatgpt-export and claude-ai-export exports don't carry provider token
counters at all (
docs/cost-model.mddeclares both "estimate-only"), yettheir
session_model_usagerows still carry a realmodel_namewith zerotokens, and got the same
reported/provider_reportedstamp as genuineprovider telemetry. Live-archive confirmation: chatgpt-export has 2,264
session_profilesrows withcost_provenance=provider_reportedandtotal_cost_usd=0.0for every single one (sum=0.0, avg=0.0); claude-ai-exporthad 55 more via a related
compute_session_costaggregation gap — thatorigin has zero
session_model_usagerows, so its per-model breakdownsalready carried the record default
confidence=unknown, but the aggregationloop's
agg_confidencestarted at"reported"and only ever downgraded to"estimated", never to"unknown".Solution
pricing.py::_normalize_model(): strip a leadingmodels/segmentalongside the existing vendor prefixes, before catalog lookup.
cost_compute.py::_per_model_from_model_usage(): after aggregating amodel's rows, downgrade any breakdown whose total tokens are zero to
confidence=unknown/provenance=unknown— a model-identity-only fact isno longer conflated with real provider-reported usage.
cost_compute.py::compute_session_cost(): when every model_usage-derivedbreakdown is zero-token, fall back to the existing text-length heuristic
(
_per_model_from_messages/estimate_tokens_from_words) over thesession's messages — this is the "estimate-only" path
docs/cost-model.mdalready declares for these origins, previously unreachable because
model_usage rows short-circuited the fallback entirely.
compute_session_cost()'s aggregation now trackshas_reportedalongsidehas_estimates, so a session with onlyunknown-confidence breakdowns andno fallback evidence gets
cost_confidence=unknown/cost_provenance=unknowninstead of the previous default of
"reported".Verification
Anti-vacuity: every new test calls a real production entry point —
_normalize_model()/estimate_cost()(called by every session/message costestimate) and
compute_session_cost()/_per_model_from_model_usage()(theexact functions
session_profile.py/rebuild.pyinvoke to build everysession_profilescost row). Reverting themodels/removeprefix()line,the zero-token confidence downgrade, or the
has_reportedaggregation fixeach makes its corresponding new test fail.
AC matrix
polylogue-6j9c:
_normalize_model()strips a leadingmodels/segment before catalog lookup.models/gemini-2.5-pronormalizes to the same catalog key as the bare form and prices identically togemini-cli-session's equivalent model.session_profilesstill needs a reprice pass over existing rows — this PR is a code + test fix for new/re-materialized profiles, not a live-archive backfill. Classification: index-only reprice (no parser semantics changed, so notSEMANTIC_REPARSE) — a follow-up rebuild/reprice pass can runpolylogue ops reset --index && polylogued runor a narrower session_profiles rebuild.polylogue-9kjtc:
_per_model_from_model_usage()distinguishes zero-token rows from real nonzero provider-reported usage, routing the former tounknown/unknown.chatgpt-export/claude-ai-export, the text-length heuristic estimate path now runs and materializescost_confidence=estimatedwhen session_model_usage carries only zero-token rows but message text exists (traced: model_usage rows were short-circuiting the_per_model_from_messagesfallback entirely — fixed).session_profilesrows currently mislabeled$0.0/provider_reportedare not repriced/reclassified by this PR — same reprice-pass follow-up as above covers both beads' residual.Residuals
Both beads' third AC item (reprice/reclassify existing live-archive rows)
is explicitly out of scope per lane instructions — this PR ships the code
fix + test coverage only. A follow-up ops pass (index rebuild or a narrower
session_profiles-only rebuild) is needed to correct already-materialized
session_profilesrows on the live archive.Ref polylogue-6j9c
Ref polylogue-9kjtc