Repository navigation
fix(insights): aggregate session_profiles tokens from canonical usage substrate - #3174
Conversation
… substrate Problem: session_profiles.total_input_tokens (and sibling token/cost columns) were computed by build_session_profile walking session.messages per-message input_tokens/output_tokens fields. For Codex sessions those fields are almost always zero -- Codex's real usage arrives as periodic cumulative token_count session events, which are deliberately excluded from session_events as redundant with session_model_usage (_SESSION_EVENTS_REDUNDANT_TYPES) and folded into session_model_usage by _aggregate_provider_usage_into_model_usage instead. The profile builder never read that table, producing a three-orders-of-magnitude split-brain: 6.43M profile input tokens vs 6.74B session_model_usage input tokens across the same 3,134 Codex sessions (polylogue-r7p6), 1,250 profiles reading exactly zero. claude-code profiles were unaffected because per-message token fields are populated there. Solution: compute_session_cost (archive/semantic/cost_compute.py) now accepts an optional model_usage: Sequence[ModelUsageTotals] parameter -- one row per model from session_model_usage, the same substrate table the archive's own cost/usage rollups are built from. When supplied it is the sole, provider-neutral source of per-model token counts for every origin, not just Codex; the message-walk path survives only as a fallback for callers building an ad hoc profile with no materialized rollup to hand (query_stats.py's no-persisted-profile-row branch). build_session_profile / build_session_insight_records / build_session_insight_record_bundles thread the parameter through; both session-insight materializer twins (rebuild_session_insights_sync and rebuild_session_insights_async, plus refresh.py's single-session and bulk incremental-refresh paths) now batch-load session_model_usage via the new polylogue/storage/sqlite/queries/model_usage.py (get_model_usage_batch / sync_model_usage_batch) and pass it in. docs/cost-model.md names session_model_usage as the single authority for per-session token totals. No schema change: session_profiles' existing token/cost columns are computed differently, not added to. Existing archives self-heal via the standard session-insight rebuild path (same materializer-version-stamped mechanism that already repairs session_profiles/session_model_usage) -- no `polylogue ops reset --index` required, though a full rebuild also picks up the fix. Verification: - devtools test tests/unit/storage/test_session_profile_model_usage_consistency.py tests/unit/storage/test_session_insight_profiles.py tests/unit/storage/test_pricing_chain_roundtrip.py tests/unit/storage/test_provider_usage_report.py tests/unit/storage/test_incremental_rebuild_equivalence.py tests/unit/storage/test_session_insight_rebuild_progress.py tests/unit/storage/test_session_insight_parallel_fanout.py tests/unit/storage/test_session_insight_refresh.py tests/unit/cli/test_query_support_runtime.py -> 95 passed - devtools verify --quick -> ruff format/check, mypy, render all --check, topology, layering, closure-matrix, manifests, docs-coverage all ok Ref polylogue-r7p6 Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 35 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 Run ID: 📒 Files selected for processing (10)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
Merging with coordinator (Fable) review standing in: both automated reviewers rate-limited without reviewing; diff reviewed manually — canonical-rollup-as-sole-source design, twin wiring, disjoint-lane fixture arithmetic, and empty-fallback semantics all verified. Ref polylogue-r7p6. |
…profiles (#3344) ## Summary `session_profiles.terminal_state_method` has existed in the canonical `index.db` DDL for a while but was never written by any code path, so it read NULL for every labeled session (8,507 of them as of the 2026-07-17 audit). This wires the field end-to-end so it's actually populated going forward. ## Problem Live-archive finding 2026-07-17 (polylogue-vhjs): `terminal_state_method` is NULL for 100% of labeled sessions (4,371 `error_left` + 4,136 `clean_finish`, v14 materialization). Root cause traced to `archive/session/runtime.py::_terminal_state`, which only ever returned `(state, confidence, evidence)` — there was never a method value computed anywhere, so the `SessionProfile` domain model, `SessionProfileRecord`, the `_SESSION_PROFILE_BASE_COLUMNS` write list, and the explicit-column `SELECT`s in `archive_tiers/archive.py` had nothing to carry. This blocks the D3 mass-annotation campaign (tracked on polylogue-rxdo), which deliberately withholds terminal-state annotation until structural-outcome provenance is auditable — without `terminal_state_method` there's no way to tell whether a label rests on the now-deleted prose-keyword heuristic or genuine structural evidence. ## Solution - `_terminal_state` now returns a 4-tuple including `method`, drawn from a closed vocabulary (`TERMINAL_STATE_METHODS` in `runtime.py`): `pending_tool_blocks`, `pending_tool_events`, `action_outcome`, `event_status`, `last_message_role`, `no_signal`, plus `bounded_materialization` for the `rebuild.py` large-session degraded fallback path. - Threaded `terminal_state_method` through every hop: `SessionProfile` -> `SessionProfileRecord` -> `_SESSION_PROFILE_BASE_COLUMNS` write list -> `SessionInferencePayload` (public payload) -> the two native-column reconciliation sites (`SessionProfileInsight.from_record` and `_session_profile_components_from_archive_row`) -> the explicit-column `SELECT`s in `archive_tiers/archive.py` -> `hydrate_session_profile`. Added it to `_INFERENCE_NATIVE_MIRRORED_FIELDS` (alongside `terminal_state`) so it isn't double-persisted inside `inference_payload_json`. - Derived-tier fix only — no schema bump, no migration. Existing NULL rows self-heal via the standard rebuild path (`polylogue ops reset --index && polylogued run`), the same framing as the `session_profiles` token-column fix earlier this session (#3174). No manual backfill script was written or is needed. ## Verification ``` devtools test tests/unit/core/test_semantic_facts.py \ tests/unit/storage/test_session_insight_refresh.py \ tests/unit/storage/test_session_insight_profiles.py \ tests/unit/sources/test_compaction.py \ tests/unit/insights/test_objective_posture.py \ tests/unit/insights/test_archive_rollups.py \ tests/unit/storage/test_session_profile_model_usage_consistency.py \ tests/unit/storage/test_session_insight_timeline_rows.py # -> 168 passed mypy --strict polylogue # -> Success: no issues found in 1086 source files ruff check / ruff format --check # -> all checks passed devtools verify --quick # -> all 17 steps ok devtools render all / render all --check # -> in sync ``` Extended the existing per-branch `terminal_state` unit tests in `test_semantic_facts.py` with a `terminal_state_method` assertion each (one per structural detection rule), and added two new end-to-end DB-materialization regression tests in `test_session_insight_refresh.py` that read the persisted `session_profiles.terminal_state_method` column back after a real ingest+materialize pass. **Pre-existing, unrelated failure noted:** `tests/unit/storage/test_delegations_view.py` (3 tests) fails on this checkout with `unknown database user_tier` both before and after this change (verified via `git stash`) — not touched by this PR. ## Acceptance criteria (polylogue-vhjs) 1. **Satisfied** — every `_terminal_state` return path now carries a method token from the closed vocabulary, wired through to the persisted `terminal_state_method` column. 2. **Satisfied** — `test_semantic_facts.py` asserts a distinct method per structural rule; `test_session_insight_refresh.py` adds two DB-level regression tests reading the native column back after real materialization. 3. **Deferred** — no rigor-matrix doc currently references `terminal_state_method` by name; `docs/library-api.md` (the doc that enumerates `SessionProfileInsight` fields) was updated instead. A dedicated rigor-matrix entry can follow if the annotation program (polylogue-rxdo) wants one. Ref polylogue-vhjs Co-authored-by: Claude <[email protected]>
Summary
session_profilestoken/cost columns (total_input_tokens,total_output_tokens,total_cache_read_tokens,total_cache_write_tokens,total_cost_usd, ...)now aggregate from
session_model_usage-- the same canonical usage substratethe archive's own cost/usage rollups are built from -- instead of independently
recomputing an estimate from per-message token fields.
Problem
Live-archive finding (polylogue-r7p6): for
codex-session,session_profilestoken columns summed to 6.43M input tokens across 3,134 sessions (1,250 of
them exactly zero), while
session_model_usagefor the same sessions summedto 6.74B input + 0.59B output tokens -- a three-orders-of-magnitude split-brain
between two read models that are both supposed to describe the same usage.
claude-code-sessionprofiles were fine (27.7B cache-read tokens visible).Root cause:
build_session_profile->compute_session_cost(
polylogue/archive/semantic/cost_compute.py) walkedsession.messages,reading each message's
input_tokens/output_tokens/cache_read_tokens/cache_write_tokensfields. Those fields are populated by the Codex parser(
sources/parsers/codex.py:_token_usage) only when a message record embeds ausageblock directly, which is rare -- Codex's real usage arrives asperiodic cumulative
token_countsession events instead (last_token_usagetotal_token_usage). Thosetoken_countevents aredeliberately excluded from the
session_eventstable as redundant withsession_model_usage(_SESSION_EVENTS_REDUNDANT_TYPESinstorage/sqlite/archive_tiers/write.py), and folded intosession_model_usageby_aggregate_provider_usage_into_model_usage(withCodex's disjoint-lane mapping: input excludes cached, output includes
reasoning) instead.
session_profilesnever read that table at all, so forsessions whose only usage evidence is the cumulative event stream, the profile
recomputation saw nothing but a crude word-count fallback -- explaining the
~1000x gap and the 1,250 exact zeros.
Solution
compute_session_cost(polylogue/archive/semantic/cost_compute.py) gainsan optional
model_usage: Sequence[ModelUsageTotals]parameter (new type inarchive/semantic/cost_records.py). When supplied and non-empty, it is thesole, provider-neutral source of per-model token counts for every
origin (not just Codex) -- the existing pricing/credit-cost loop underneath
is unchanged, only the token-count source moved. The message-walk path
(
_per_model_from_messages) survives only as a fallback for callers thatbuild an ad hoc profile with no materialized rollup to hand.
build_session_profile(archive/session/runtime.py) andbuild_session_insight_records/build_session_insight_record_bundles(
storage/insights/session/rebuild.py) threadmodel_usagethrough.polylogue/storage/sqlite/queries/model_usage.py(
get_model_usage_batchasync /sync_model_usage_batchsync) batch-readssession_model_usagerows per session, mirroring the existingattachments/session-events batch-read pattern.
SessionInsightArchiveBatchgains amodel_usage_by_sessionfield,populated in both
load_sync_batchandload_async_batch-- wired intoboth materializer twins:
rebuild_session_insights_syncandrebuild_session_insights_async(full rebuild), plusrefresh.py'ssingle-session and bulk incremental-refresh paths (
storage/insights/session/refresh.py).docs/cost-model.mdgets a new "Single authority for per-session tokentotals" section naming
session_model_usageas that authority.Known related gap, left out of scope: the "large/degraded session" bounded
materialization path (
_large_session_profile_record[_from_row]inrebuild.py, sessions above_SESSION_INSIGHT_DEGRADED_MESSAGE_THRESHOLD=10,000 messages) never populates token columns at all -- it explicitly writes
cost_provenance="unknown"and leaves totals at their 0 default, by design("unknown, not fabricated"). That's a distinct, already-honest gap (it never
claims a wrong nonzero value), not the split-brain this bead reports, and
isn't what drives the reported 1000x/1,250-zero numbers (that threshold is
very high; the bug reproduces on ordinary small sessions). Not touched here.
No schema change.
session_profiles' existing token/cost columns arecomputed differently, not added to -- no migration, no index-tier bump.
Existing archives self-heal.
session_profilesalready carries amaterializer-version-stamped
insight_materializationrow and re-derivesautomatically via the standard session-insight rebuild path (daemon's periodic
drain, hot-source convergence, convergence-debt retry) -- the same mechanism
that already repairs
session_model_usageitself perdocs/cost-model.md.No
polylogue ops reset --indexis required, though a full rebuild also picksup the fix immediately for anyone who wants it sooner.
Verification
New test file
tests/unit/storage/test_session_profile_model_usage_consistency.py:a cumulative
token_countevent with realistic input/cached/output/reasoningnumbers) through the real
write_parsed_session_to_archivewrite path, thenasserts
session_profilestoken columns equalsession_model_usage'saggregate and the concrete expected disjoint-lane numbers, after both
rebuild_session_insights_syncandrebuild_session_insights_async.regression for the origin that was already correct.
Sessionwithoutmodel_usagereproduces the undercount (a few tokensfrom the word-count fallback vs the real ~4,000), and passing
model_usagein corrects it -- so the fix, not a fixture artifact, is what makes the
other tests pass.
Not run: the full non-focused test suite / integration tier (out of scope for
this change's blast radius; the affected-area focused set above covers every
call site touched).
Ref polylogue-r7p6