Skip to content

fix(insights): aggregate session_profiles tokens from canonical usage substrate - #3174

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/session-profile-model-usage-consistency
Jul 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/session-profile-model-usage-consistency

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

session_profiles token/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 substrate
the 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_profiles
token columns summed to 6.43M input tokens across 3,134 sessions (1,250 of
them exactly zero), while session_model_usage for the same sessions summed
to 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-session profiles were fine (27.7B cache-read tokens visible).

Root cause: build_session_profile -> compute_session_cost
(polylogue/archive/semantic/cost_compute.py) walked session.messages,
reading each message's input_tokens/output_tokens/cache_read_tokens/
cache_write_tokens fields. Those fields are populated by the Codex parser
(sources/parsers/codex.py:_token_usage) only when a message record embeds a
usage block directly, which is rare -- Codex's real usage arrives as
periodic cumulative token_count session events instead (last_token_usage

  • session-global total_token_usage). Those token_count events are
    deliberately excluded from the session_events table as redundant with
    session_model_usage (_SESSION_EVENTS_REDUNDANT_TYPES in
    storage/sqlite/archive_tiers/write.py), and folded into
    session_model_usage by _aggregate_provider_usage_into_model_usage (with
    Codex's disjoint-lane mapping: input excludes cached, output includes
    reasoning) instead. session_profiles never read that table at all, so for
    sessions 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) gains
    an optional model_usage: Sequence[ModelUsageTotals] parameter (new type in
    archive/semantic/cost_records.py). When supplied and non-empty, it is the
    sole, 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 that
    build an ad hoc profile with no materialized rollup to hand.
  • build_session_profile (archive/session/runtime.py) and
    build_session_insight_records / build_session_insight_record_bundles
    (storage/insights/session/rebuild.py) thread model_usage through.
  • New polylogue/storage/sqlite/queries/model_usage.py
    (get_model_usage_batch async / sync_model_usage_batch sync) batch-reads
    session_model_usage rows per session, mirroring the existing
    attachments/session-events batch-read pattern.
  • SessionInsightArchiveBatch gains a model_usage_by_session field,
    populated in both load_sync_batch and load_async_batch -- wired into
    both materializer twins: rebuild_session_insights_sync and
    rebuild_session_insights_async (full rebuild), plus refresh.py's
    single-session and bulk incremental-refresh paths (storage/insights/session/refresh.py).
  • docs/cost-model.md gets a new "Single authority for per-session token
    totals" section naming session_model_usage as that authority.

Known related gap, left out of scope: the "large/degraded session" bounded
materialization path (_large_session_profile_record[_from_row] in
rebuild.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 are
computed differently, not added to -- no migration, no index-tier bump.

Existing archives self-heal. session_profiles already carries a
materializer-version-stamped insight_materialization row and re-derives
automatically 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_usage itself per docs/cost-model.md.
No polylogue ops reset --index is required, though a full rebuild also picks
up the fix immediately for anyone who wants it sooner.

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 --strict, render all --check, topology,
#    layering, closure-matrix, manifests, docs-coverage, degrade-loudly: all ok

New test file tests/unit/storage/test_session_profile_model_usage_consistency.py:

  • seeds a Codex-shaped session (message with zero per-message token fields +
    a cumulative token_count event with realistic input/cached/output/reasoning
    numbers) through the real write_parsed_session_to_archive write path, then
    asserts session_profiles token columns equal session_model_usage's
    aggregate and the concrete expected disjoint-lane numbers, after both
    rebuild_session_insights_sync and rebuild_session_insights_async.
  • seeds an equivalent Claude Code (per-message-token) session proving no
    regression for the origin that was already correct.
  • an explicit anti-vacuity test: building the profile from the same hydrated
    Session without model_usage reproduces the undercount (a few tokens
    from the word-count fallback vs the real ~4,000), and passing model_usage
    in 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

… 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]>
@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.

@coderabbitai

coderabbitai Bot commented Jul 19, 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: 35 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

Run ID: e3693cc5-d555-4ba3-807a-b741a92493fd

📥 Commits

Reviewing files that changed from the base of the PR and between b7384f2 and c270ac9.

📒 Files selected for processing (10)
  • docs/cost-model.md
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/archive/semantic/cost_compute.py
  • polylogue/archive/semantic/cost_records.py
  • polylogue/archive/session/runtime.py
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/insights/session/refresh.py
  • polylogue/storage/sqlite/queries/model_usage.py
  • tests/unit/storage/test_session_profile_model_usage_consistency.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/session-profile-model-usage-consistency

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.

@Sinity

Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Sinity

Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner Author

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.

@Sinity
Sinity merged commit 0f24483 into master Jul 19, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/session-profile-model-usage-consistency branch July 19, 2026 21:16
Sinity added a commit that referenced this pull request Jul 27, 2026
…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]>
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