Skip to content

fix(cost): strip aistudio-drive models/ prefix, honest zero-token provenance - #3511

Merged
Sinity merged 3 commits into
masterfrom
feature/fix/aistudio-drive-cost-provenance-bugs
Aug 1, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/fix/aistudio-drive-cost-provenance-bugs

Conversation

@Sinity

@Sinity Sinity commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Summary

Two related cost-accounting bugs from a fresh forensics pass (2026-08-01,
read-only census against index.db):

  1. polylogue-6j9c (P1): aistudio-drive prices at $0.00 for 105.7M real
    tokens because pricing.py's _normalize_model() never stripped the
    models/ resource-path prefix aistudio-drive's own parser writes verbatim.
  2. polylogue-9kjtc (P2): cost_compute.py unconditionally labelled every
    session_model_usage row confidence=reported/provenance=provider_reported
    regardless 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 against
tests/unit/sources/test_gemini_drive_normalization_laws.py and
tests/unit/core/test_schema_generation.py). _normalize_model() stripped
openai//anthropic//google//gemini/ but never models/, so this form
failed both the exact-match catalog lookup and the prefix-fallback lookup.
Measured on the live archive: 239 session_model_usage rows / 17 distinct
model names / 105,687,388 tokens across aistudio-drive, all pricing to
cost_provenance=provider_reported, total_cost_usd=0.0 for all 183
session_profiles rows in that bucket — despite the catalog carrying real
per-token rates for the underlying models (e.g.
PRICING['gemini-2.5-pro'] = 1.25/10.0 USD/M input/output).
Cross-check: gemini-cli-session uses the bare model name for the same
model 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.md declares both "estimate-only"), yet
their session_model_usage rows still carry a real model_name with zero
tokens, and got the same reported/provider_reported stamp as genuine
provider telemetry. Live-archive confirmation: chatgpt-export has 2,264
session_profiles rows with cost_provenance=provider_reported and
total_cost_usd=0.0 for every single one (sum=0.0, avg=0.0); claude-ai-export
had 55 more via a related compute_session_cost aggregation gap — that
origin has zero session_model_usage rows, so its per-model breakdowns
already carried the record default confidence=unknown, but the aggregation
loop's agg_confidence started at "reported" and only ever downgraded to
"estimated", never to "unknown".

Solution

  • pricing.py::_normalize_model(): strip a leading models/ segment
    alongside the existing vendor prefixes, before catalog lookup.
  • cost_compute.py::_per_model_from_model_usage(): after aggregating a
    model's rows, downgrade any breakdown whose total tokens are zero to
    confidence=unknown/provenance=unknown — a model-identity-only fact is
    no longer conflated with real provider-reported usage.
  • cost_compute.py::compute_session_cost(): when every model_usage-derived
    breakdown is zero-token, fall back to the existing text-length heuristic
    (_per_model_from_messages/estimate_tokens_from_words) over the
    session's messages — 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 entirely.
  • compute_session_cost()'s 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 the previous default of "reported".

Verification

devtools test tests/unit/core/test_pricing.py
  → 21 passed (new: test_aistudio_drive_resource_path_model_prices_like_bare_form)

devtools test tests/unit/core/test_cost_compute.py
  → 4 passed (new file)

devtools test 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 (ran twice: once manually, once via the pre-push hook)

Anti-vacuity: every new test calls a real production entry point —
_normalize_model()/estimate_cost() (called by every session/message cost
estimate) and compute_session_cost()/_per_model_from_model_usage() (the
exact functions session_profile.py/rebuild.py invoke to build every
session_profiles cost row). Reverting the models/ removeprefix() line,
the zero-token confidence downgrade, or the has_reported aggregation fix
each makes its corresponding new test fail.

AC matrix

polylogue-6j9c:

  • _normalize_model() strips a leading models/ segment before catalog lookup.
  • Regression test: models/gemini-2.5-pro normalizes to the same catalog key as the bare form and prices identically to gemini-cli-session's equivalent model.
  • Deferred (out of lane scope, ops concern): live archive's aistudio-drive session_profiles still 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 not SEMANTIC_REPARSE) — a follow-up rebuild/reprice pass can run polylogue ops reset --index && polylogued run or 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 to unknown/unknown.
  • For chatgpt-export/claude-ai-export, the text-length heuristic estimate path now runs and materializes cost_confidence=estimated when session_model_usage carries only zero-token rows but message text exists (traced: model_usage rows were short-circuiting the _per_model_from_messages fallback entirely — fixed).
  • Deferred (out of lane scope, ops concern): existing session_profiles rows currently mislabeled $0.0/provider_reported are 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_profiles rows on the live archive.

Ref polylogue-6j9c
Ref polylogue-9kjtc

Sinity added 2 commits August 1, 2026 14:03
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
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 45 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d487dd03-acb9-4eb4-a7f2-d741f001e578

📥 Commits

Reviewing files that changed from the base of the PR and between 62f1d1a and f23dbc6.

📒 Files selected for processing (4)
  • polylogue/archive/semantic/cost_compute.py
  • polylogue/archive/semantic/pricing.py
  • tests/unit/core/test_cost_compute.py
  • tests/unit/core/test_pricing.py

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.

@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

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

Sinity added a commit that referenced this pull request Aug 1, 2026
…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]>
@Sinity
Sinity merged commit 6b59bc5 into master Aug 1, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/aistudio-drive-cost-provenance-bugs branch August 1, 2026 13:00
Sinity added a commit that referenced this pull request Aug 1, 2026
…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.
Sinity added a commit that referenced this pull request Aug 1, 2026
…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]>
Sinity added a commit that referenced this pull request Aug 3, 2026
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]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 58.F032 / P1: fixed-already at the checked revision: polylogue/archive/semantic/cost_compute.py:400 uses the dominant/session model for model-less turns, and lines 415-424 allocate estimated assistant words to output and other turns to input. The zero-token export fallback no longer prices every word as input on its own absent model.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 59.F096 / P2: fixed-already at the checked revision: polylogue/archive/semantic/cost_compute.py:214-215 records unknown model breakdowns, and lines 221-231 downgrade a mixture of unknown and reported/estimated rows to partial. A zero-token model skeleton no longer leaves the mixed aggregate reported.

Only the rows listed above are dispositioned. Held findings remain open.

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