Skip to content

fix: Resolve dated model snapshots from their own catalog row - #5024

Merged
Sinity merged 2 commits into
masterfrom
fix/pricing-dated-model-resolution
Sep 13, 2026
Merged

Sinity merged 2 commits into
masterfrom
fix/pricing-dated-model-resolution

Conversation

@Sinity

@Sinity Sinity commented Sep 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

Split _normalize_model into an exact-first pricing-resolution key and a
separate date-folding cohort key, so a dated model snapshot is priced from its
own catalog row instead of colliding with a same-named bare key owned by an
unrelated router.

Problem

_normalize_model stripped the dated snapshot suffix before consulting the
catalog, discarding an exact hit in favour of a fuzzier bare key. The vendored
LiteLLM catalog carries both forms:

claude-sonnet-4-20250514  source=anthropic  in=3.0  cache_read=0.3  cache_write=3.75
claude-sonnet-4           source=gmi        in=3.0  cache_read=0.0  cache_write=0.0

The gmi row's zero cache rates then trip the deliberate refusal in
archive_tiers/write.py ("a zero cache rate is also the catalog's sentinel for
an omitted rate"), so the row is left entirely unpriced.

13 reachable dated keys resolved to a differently-rated bare key. Eight lost
their cache lane and went unpriced — claude-sonnet-4-20250514,
claude-opus-4-20250514, claude-4-sonnet-20250514, claude-4-opus-20250514,
claude-3-haiku-20240307, claude-3-5-sonnet-20241022,
gpt-realtime-mini-2025-10-06, gpt-realtime-mini-2025-12-15. Five were billed
at the wrong rate — gpt-4o-2024-05-13, gpt-4o-realtime-preview-2024-10-01,
gpt-5.1-chat-2025-11-13, gpt-realtime-1.5-2026-02-23,
o1-preview-2024-09-12.

Honest history: the guard in #4332 only surfaced this; the date strip predates
it (7412b69a9). Before #4332 these rows were priced with their cache lanes
silently billed at $0. Neither behaviour was correct.

The failure is quiet, which is what makes it matter: affected rows materialize
catalog_cost_usd = NULL and rollups report status='unavailable' rather than
reporting a wrong number, so a rebuild would not announce it.

Solution

_normalize_model now tries the final path segment against the catalog
verbatim first and strips a dated suffix only when no exact key exists, so an
unpublished snapshot still falls back to its undated model. The no-prefix-fold
rule from #4927 is untouched: an unknown model still stays unpriced rather than
inheriting a nearby rate.

A new exported model_cohort_key always folds the date away and is used for the
cost-rollup grouping key and the usage-timeline cohort label, so date-preserving
resolution does not re-fragment rollups by release date.
SessionCostInsight.normalized_model deliberately keeps the resolution key — it
reports which catalog row priced that session.

Rejected: relaxing the #4332 guard (restores silent $0 cache billing); pruning
the colliding bare rows from the vendored catalog (mutates vendored data, does
not survive a refresh); ranking catalog rows by source_name at load (invents a
vendor priority and still mis-rates the wrong-rate cases); adding a separate
resolver at each lookup site (the same bug is live in storage/usage.py and
semantic/cost_compute.py, which this seam fixes automatically).

Verification

devtools test <14 pricing/rollup/insight/CLI/daemon files>
  PASSED   receipt 20260913T185326Z-focused-test-1202572-3bff61ad
devtools verify --quick
  exit 0, all 14 gates ok (including schema-manifest and layering)

The #4332 guard is not regressed:
tests/unit/storage/test_usage_projection.py::test_paid_model_with_missing_cache_rate_is_not_persisted_as_priced
and its cache-write sibling monkeypatch a synthetic paid model with genuinely
omitted cache rates, so this resolver change cannot reach them; both pass.
write.py is untouched.

Anti-vacuity conditions:

  • test_dated_snapshot_prices_from_its_own_catalog_row_not_a_bare_collision —
    restoring the unconditional date strip makes the cache-rate assertions zero
    and the $0.30 cache-read cost assertion fall to zero.
  • test_cost_rollup_unions_normalized_model_session_counts_and_separates_basis_lanes
    now uses gpt-5.2 / gpt-5.2-2025-12-11, verified to fold to one cohort
    while resolving to distinct pricing keys. Session s1 carries rows for both
    variants, so summing raw per-model COUNT(DISTINCT) gives 3 for two real
    sessions and is red; splitting them into two cohorts is also red, because the
    test unpacks exactly one rollup and asserts normalized_model == "gpt-5.2".

Residuals

  • Both edited product files are IN the derived schema-identity closure
    (devtools schema closure confirms polylogue/archive/semantic/pricing.py
    and archive_tiers/archive.py). This must land before a fresh rebuild
    starts, never during one.
  • Pre-existing and unrelated: tests/unit/api/test_facade_contracts.py fails 6
    tests identically on clean master (mutation-transaction sealing ×4,
    test_no_undiscovered_async_methods, stale_work_event_inference_count).
    Baselined in a throwaway worktree; tracked under polylogue-7lhl5.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Summary by CodeRabbit

  • Bug Fixes

    • Dated model snapshots now use their exact catalog pricing, improving cache-rate and usage-cost accuracy.
    • Corrected pricing behavior for dated Claude snapshots to prevent billing against an unintended base model.
    • Updated cost calculations to consistently combine dated and undated model variants in usage and cost rollups.
  • Improvements

    • Model cohort reporting now groups release-dated variants under a shared model label while preserving accurate individual pricing.

Sinity and others added 2 commits September 13, 2026 20:42
Problem: `_normalize_model` stripped a dated snapshot suffix BEFORE
consulting the vendored LiteLLM catalog, so an exact catalog hit was
discarded in favour of a bare key that an unrelated router owns. The
catalog holds both `claude-sonnet-4-20250514` (anthropic, cache_read
$0.30, cache_write $3.75) and `claude-sonnet-4` (gmi, cache rates
omitted and therefore zero). The gmi row's zero cache rates then trip
the deliberate refusal in `_price_provider_usage_tokens` (#4332), which
treats a zero cache rate as the catalog's sentinel for an omitted rate,
so cache-bearing rows of these models were left entirely unpriced.

Verified blast radius against the vendored catalog: 13 dated keys
reachable by the last-segment lookup resolve to a bare key with
different rates. Eight of those lose a cache lane outright and are
therefore left unpriced: claude-sonnet-4-20250514, claude-opus-4-20250514,
claude-4-sonnet-20250514, claude-4-opus-20250514, claude-3-haiku-20240307,
claude-3-5-sonnet-20241022, gpt-realtime-mini-2025-10-06 and
gpt-realtime-mini-2025-12-15. The remaining five were simply billed at
the wrong rate: gpt-4o-2024-05-13, gpt-4o-realtime-preview-2024-10-01,
gpt-5.1-chat-2025-11-13, gpt-realtime-1.5-2026-02-23, o1-preview-2024-09-12.

The #4332 guard only surfaced this; the date strip predates it
(7412b69). Before #4332 these rows were priced with their cache lanes
silently billed at $0. Neither behavior was correct, so this does not
restore the old one.

Solution: `_normalize_model` served two roles at once — the pricing
resolution key and the rollup grouping key — and those roles want
opposite answers about a release date. Split them. `_normalize_model`
is now exact-first: the final path segment is tried against the catalog
verbatim, and a dated suffix is removed only when no exact key exists,
so an unpublished snapshot still resolves to its undated model. The
coarse role moves to a new `model_cohort_key`, which always folds the
date away; cost rollups and the usage timeline group and label by that,
so making resolution date-preserving does not re-fragment rollups by
release date.

Rejected: relaxing the #4332 guard (reintroduces silent $0 cache
billing); pruning the colliding bare rows from the vendored catalog
(mutates vendored data and does not survive a refresh); ranking catalog
rows by `source_name` at load time (invents a vendor priority and still
mis-rates the five wrong-rate cases); leaving `_normalize_model` coarse
and adding a separate resolver at each lookup site (the same bug is
live in storage/usage.py and semantic/cost_compute.py, and they would
have to be found one by one).

Both edited files are inside the derived schema-identity closure
(`devtools schema closure`), so derived cost read models must reconverge.

Verification:
  devtools test tests/unit/core/test_pricing.py \
    tests/unit/storage/test_archive_tiers_write.py \
    tests/unit/storage/test_usage_projection.py \
    tests/unit/storage/test_session_usage_reconciliation.py \
    tests/unit/insights/... tests/unit/cli/test_insights.py
  -> PASSED
The #4332 refusal is unchanged and still proven by
tests/unit/storage/test_usage_projection.py::
test_paid_model_with_missing_cache_rate_is_not_persisted_as_priced.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
…pair

Problem: `test_cost_rollup_unions_normalized_model_session_counts_and_
separates_basis_lanes` failed with `ValueError: too many values to
unpack (expected 1, got 2)`. Commit 98235de (#4927) deliberately
removed the prefix-fold from `_normalize_model` so an unknown model
stays unpriced rather than inheriting a nearby rate, which means
`gpt-5-5` and `gpt-5-5-pro` no longer share a cohort and the rollup
yields two rows. That removal is correct and is kept.

Solution: rebuild the fixture on a pair that folds under the resolver
that actually exists — `gpt-5.2` and its dated snapshot
`gpt-5.2-2025-12-11`, which `model_cohort_key` folds into one cohort —
and give session `s1` usage rows for both variants so the cohort really
does contain a shared session.

Anti-vacuity: the raw per-model `COUNT(DISTINCT session_id)` values are
1 + 1 + 1 = 3 for two real sessions, so a rollup that summed them
instead of unioning session ids reports 3 and the test is red. Splitting
the pair into two cohorts to make the assertion pass is also red, since
the test now unpacks exactly one rollup and asserts its cohort label is
`gpt-5.2`. The basis assertions stay red if the API-equivalent or USD
subscription lane is zeroed or left in credit units.

Verification:
  devtools test tests/unit/storage/test_cost_queries.py \
    tests/unit/insights/test_archive_rollups.py \
    tests/unit/cli/test_insights.py
  -> PASSED

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: ecd5a1c0-e815-4248-b58b-a6865a5bc9f0

📥 Commits

Reviewing files that changed from the base of the PR and between 3faacef and 4dd9f32.

📒 Files selected for processing (4)
  • polylogue/archive/semantic/pricing.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/core/test_pricing.py
  • tests/unit/storage/test_cost_queries.py

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.

📜 Recent review details
🧰 Additional context used
📓 Path-based instructions (2)
Classify every schema change first: durable tier means additive numbered migration plus verified backup manifest; derived tier means canonical DDL plus declared lifecycle delta.

📄 CodeRabbit inference engine (CLAUDE.md)

Files:

  • tests/unit/core/test_pricing.py
  • tests/unit/storage/test_cost_queries.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/archive/semantic/pricing.py
Use `devtools`, never bare `pytest`.

📄 CodeRabbit inference engine (CLAUDE.md)

Files:

  • tests/unit/core/test_pricing.py
  • tests/unit/storage/test_cost_queries.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/archive/semantic/pricing.py
🔇 Additional comments (1)
polylogue/storage/sqlite/archive_tiers/archive.py (1)

3315-3316: 🎯 Functional Correctness

The timeline model filter compares the supplied value directly with raw e.model_name and u.model_name, while each result exposes a separate cohort-normalized normalized_model. The available evidence does not define whether callers may pass normalized_model values, so the dated-only filtering defect remains undecidable without the API contract or caller usage.


📝 Walkthrough

Walkthrough

The change separates exact dated model pricing from date-stripped cohort grouping. Archive cost rollups and timelines use cohort keys, while pricing lookup preserves exact catalog entries.

Changes

Model pricing and cohort grouping

Layer / File(s) Summary
Pricing resolution contract
polylogue/archive/semantic/pricing.py
_normalize_model checks exact catalog keys before removing date suffixes. model_cohort_key provides date-stripped grouping keys and is exported.
Archive cohort wiring
polylogue/storage/sqlite/archive_tiers/archive.py
Cost rollups and usage timelines use model_cohort_key for normalized model labels.
Pricing and rollup validation
tests/unit/core/test_pricing.py, tests/unit/storage/test_cost_queries.py
Tests cover dated catalog pricing, cache rates, cohort grouping, session counts, and cost totals.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 4dd9f

The pricing and reporting changes preserve exact snapshot rates while grouping dated variants in cohort labels, with no actionable merge risk identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 76.92% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: resolving dated model snapshots from their exact catalog entries.
Description check ✅ Passed The description includes complete Summary, Problem, Solution, and Verification sections. The Residuals section covers risks and follow-ups, and the omission of a separate Changelog section is reasonab…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/pricing-dated-model-resolution

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

A rabbit checks each dated key
And folds the cohorts carefully
Cache rates bloom from rows precise
Rollups join the matching mice
The ledger hops with totals right

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

@Sinity
Sinity merged commit d4a3e48 into master Sep 13, 2026
3 checks passed
@Sinity
Sinity deleted the fix/pricing-dated-model-resolution branch September 13, 2026 19:08
Sinity added a commit that referenced this pull request Sep 14, 2026
## Summary

`polylogue-7lhl5` reported 33 red tests across `tests/unit/daemon` and
`tests/unit/storage`. **31 of the 33 were already fixed** by PRs
#5024-#5051 that landed between the bead's measurement commit
(`3faacef23`) and current master — verified cluster by cluster in
source, not assumed. Reproducing at head gave **5 failed / 5538
passed**, in two new clusters, both in storage. This fixes both, one of
which is a real product defect.

## Problem

**A durable artifact observation was misreporting supported material as
unsupported.**

PR #5040 made ingest refuse Hermes SQLite *page images*, because replay
already refused them and admitting one would mint a second source
authority for content the archive holds under its logical revision. The
three failing tests still built page images and asserted
`supported_parseable`, so the stale half was straightforward.

Rebuilding them on the current contract exposed the real defect:
`storage/artifacts/inspection.py::_hermes_state_db_schema_version` still
read through `open_readonly_connection`, a plain SQLite open. A logical
export is not a SQLite file, so it returned no version — and **every
retained Hermes state observation resolved to `unsupported_parseable`
with `resolved_package_version=None`**, silently.

`looks_like_state_db_path` and `hermes_state._connect_readonly` were
both moved onto `open_logical_source` by #4798. This one reader was left
behind.

**Second cluster: environment, not product.** Python 3.14 made
`forkserver` the default start method on Linux, so the first
`Process.start()` in a pytest session pays a fresh-interpreter bring-up
— **measured at 4.41 s** with a temporary probe, against a
`ready.wait(5)` deadline. Only whichever of the two lease tests ran
first failed; inserting a throwaway `Process.start()` ahead of them made
both pass untouched. The deadline is a liveness bound, not a latency
assertion, so it is now a named 60 s constant with the cause recorded.
The lease itself is correct and unchanged.

## Solution

Read the Hermes state schema version through `open_logical_source`, the
same seam its siblings already use. Tests rewritten onto the production
acquisition route (`write_logical_export` + `member_export_scope`), plus
two added: a page image is refused
(`recognized_unparsed`/`binary_database`), and inspecting a retained
WAL-mode page image leaves the blob namespace pristine.

## Verification

```
devtools test tests/unit/daemon tests/unit/storage
     tests/unit/sources/test_revision_backfill.py
     tests/unit/pipeline/test_malformed_jsonl_accounting.py
     tests/unit/core/test_verification.py
  -> 5677 passed, 0 failed (33:55)
devtools verify --quick  -> exit 0, 15/15 gates
```

Anti-vacuity verified by reverting, with a receipt for each:

| Test | Mutation | Result |
|---|---|---|
| the two export tests | restore `open_readonly_connection` | red
(`unsupported_parseable`) |
| page-image refusal | drop the `is_declared_logical_export` gate | red
|
| blob-namespace | that gate **and** `sqlite_immutable=False` | red with
`-wal`/`-shm`; either alone stays green |
| `test_rebuild_lease_excludes_competing_process` | `LOCK_EX` ->
`LOCK_SH` | red |

## Landing order

`devtools schema closure polylogue/storage/artifacts/inspection.py` ->
**IN**. Both identities were computed rather than inferred: the index
identity **moves**, `ffced415…` -> `764f42c7…`; ops unchanged. **Must
land before a from-scratch rebuild starts, never during one.**

## Residuals

`devtools gate atlas` is red with **124 BLOCKs — identically at the base
commit and at this tip.** Inherited doc-staleness in
`docs/atlas/storage.md` against `blob_gc.py`, `blob_publication.py`, and
`archive_tiers/{source,bootstrap,archive_tiers_specs}.py`. Nothing in
this branch is among them, and atlas is not part of `verify --quick`, so
it is a separate inherited item — one a full pre-build `devtools verify`
will also surface.

The full corpus was not re-run.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

---------

Co-authored-by: Claude Opus 5 (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