Repository navigation
perf(storage): index write-path hot stages, memoize pricing catalog hash - #3210
Conversation
… hash
Problem: measured per-page stage timings from a live v42 rebuild (2,000-raw
page) showed clear_projection_rows=11.1s and model_usage_seed=8.5s as two of
the largest write-path stages (Ref polylogue-623q).
- clear_projection_rows deletes 10 projection tables by session_id before a
full-session replace. EXPLAIN QUERY PLAN showed 9 of them hit an index
(mostly their PK), but paste_spans (PK is (message_id, position), no
session_id index) does a full table SCAN -- verified with a synthetic
100K-row table: 2000 session deletes took 10.3s unindexed vs 0.013s with
an index (~800x). Added idx_paste_spans_session both to the canonical DDL
(fresh bootstrap) and to storage/sqlite/runtime_indexes.py's
ensure_runtime_indexes_sync/async (existing archives pick it up on next
connect, no rebuild/version bump needed -- same mechanism already used for
idx_messages_active_leaf etc).
- model_usage_seed calls seed_price_catalog() per session, which recomputed
_catalog_hash() -- a SHA-256 over the ~3.5K-entry in-memory PRICING dict --
every time. PRICING is built once at module import and never mutated in
production (grepped for write sites). Measured: 2000x _catalog_hash() =
6.85s uncached; memoizing with functools.lru_cache(maxsize=1) drops
2000x seed_price_catalog() from 7.1s to 0.25s (~97%).
Both changes are purely mechanical: same rows exist after a write in every
case, verified against the one test that deliberately mutates PRICING
mid-process (test_pricing_chain_roundtrip.py) by having it clear the memo
around its monkeypatch.
Solution:
- polylogue/storage/sqlite/archive_tiers/pricing_seed.py: lru_cache on
_catalog_hash() and _effective_at_ms() (both pure functions of
process-lifetime-constant module data).
- polylogue/storage/sqlite/archive_tiers/index.py: add
idx_paste_spans_session, additive/inert (CREATE INDEX IF NOT EXISTS), no
INDEX_SCHEMA_VERSION bump (precedent: idx_messages_active_leaf).
- polylogue/storage/sqlite/runtime_indexes.py: mirror the index so existing
archives get it without a rebuild.
- tests/unit/storage/test_pricing_chain_roundtrip.py: the one test that
monkeypatches PRICING now clears the _catalog_hash memo before and after
the mutation (request.addfinalizer) so the cache neither misses the
revised catalog during the test nor leaks a stale hash into later tests
in the same worker process.
Rejected candidates (evaluated, not applied):
- executemany for messages/blocks/projection inserts: already executemany
in _write_messages/_write_blocks; the blocks_action_pairs_* triggers that
would otherwise refresh action_pairs per-row are already guarded by
derived_refresh_guard('session-write') during a session write.
- delete_messages (DELETE FROM messages WHERE session_id=?): already hits
idx_messages_session_material_origin; every messages(message_id)-FK child
table with a CASCADE/SET NULL action already has a supporting index
(verified via PRAGMA foreign_key_list + EXPLAIN QUERY PLAN on all 9
referencing tables). No scan found.
session_model_usage: skipping unchanged-model-set reseeds needs a
same-session-token-change signal beyond the model set (aggregated tokens
can change without the model set changing under merge_append), and the
dominant cost (catalog hash recompute) is already fixed above with zero
correctness risk. Left as a follow-up rather than risking a subtly wrong
skip condition.
Verification:
- devtools test tests/unit/storage/test_archive_tiers_write.py
tests/unit/storage/test_archive_tiers_ddl.py
tests/unit/storage/test_revision_replay.py
tests/unit/storage/test_pricing_chain_roundtrip.py -> 132 passed
(tests/unit/storage/test_crud.py named in the task no longer exists under
that path in this checkout; substituted the write/ddl/revision-replay
equivalents that cover the touched surface)
- Micro-benchmarks (ad hoc scripts, numbers quoted in this message and the
PR body): paste_spans DELETE 10.3s -> 0.013s per 2000 sessions over a
100K-row table; seed_price_catalog 7.1s -> 0.25s per 2000 calls.
Ref polylogue-623q
… fix)
Problem (coordinator priority update on polylogue-623q): a live walk over a
whale-dense page (500 raws) showed
revision_replay.index.full_replace.clear_projection_rows=92.7s -- vs 11.1s
per 2,000 NORMAL raws measured earlier. The stage scales pathologically with
whale sessions (huge message/block counts), not just with raw count.
Root cause: action_pairs.tool_result_block_id is `ON DELETE SET NULL`
against blocks(block_id), but had no supporting index. Every deleted block
row requires SQLite to find matching action_pairs rows to null out; without
an index that is a full action_pairs table SCAN *per deleted block row* --
for a whale session's full-replace block DELETE (thousands of blocks)
against an archive-wide action_pairs table, that is
O(deleted_blocks x action_pairs_row_count), not O(deleted_blocks).
Verified end-to-end through the real write path (not just EXPLAIN QUERY
PLAN, which showed the DELETE FROM blocks statement itself as already
correctly indexed -- the cost is hidden inside the FK SET NULL action, not
visible on the parent statement's own plan): built a synthetic whale
session (3,000 tool_use/tool_result pairs = 6,000 blocks) against a
realistic archive-wide action_pairs population (40,000 rows from other
sessions), then called write_parsed_session_to_archive(..., force_replace=
True) twice, comparing this worktree (with the fix) against the unfixed
main checkout via explicit sys.path selection (a stray `python3 <script>.py`
invocation was silently resolving to the unfixed main-checkout install via
cwd-independent sys.path[0] -- corrected before trusting these numbers):
before (no index): full-replace total 31.4s, of which
clear_projection_rows=30.6s
after (idx_action_pairs_tool_result_block): full-replace total 0.86s, of
which clear_projection_rows=0.069s (~445x on the stage, ~36x overall)
The other blocks/messages/delete_messages stages in this benchmark come out
proportional to whale session size and already indexed (blocks=0.40s,
messages=0.21s, delete_messages=0.05s for 6,000 blocks/3,001 messages) --
no further scan found on any FK path off blocks(block_id) or
messages(message_id) (checked all 9 referencing tables via
PRAGMA foreign_key_list + EXPLAIN QUERY PLAN).
Solution:
- polylogue/storage/sqlite/archive_tiers/index.py: add
idx_action_pairs_tool_result_block (partial, excludes NULL -- unpaired
tool_use rows never populate this column and NULL never matches an
equality FK lookup). Additive/inert, no INDEX_SCHEMA_VERSION bump (same
precedent as the paste_spans index in the prior commit).
- polylogue/storage/sqlite/runtime_indexes.py: mirror the index so existing
archives (including the live v42 rebuild in progress) get it on next
connect without a rebuild.
Verification:
- devtools test tests/unit/storage/test_archive_tiers_write.py
tests/unit/storage/test_archive_tiers_ddl.py
tests/unit/storage/test_revision_replay.py
tests/unit/storage/test_pricing_chain_roundtrip.py
tests/unit/storage/test_delegation_facts_bulk_rebuild.py
tests/unit/storage/test_planner_statistics_seed.py
tests/unit/storage/test_schema_policy_contracts.py
tests/unit/storage/test_bulk_build_lifecycle.py -> 159 passed
- mypy --strict on both touched files -> success
- devtools verify --quick -> 16/16 steps ok
- Whale benchmark (ad hoc script, not committed -- .agent/scratch/ is
gitignored): numbers quoted above, reproduced 3x consistently after
isolating the sys.path resolution bug.
Ref polylogue-623q
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThe change adds SQLite indexes for targeted cleanup queries and memoizes pricing catalog helpers. The pricing round-trip test now clears cached catalog hashes before and after mutating pricing data. ChangesSQLite supporting indexes
Pricing helper memoization
Estimated code review effort: 2 (Simple) | ~15 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a1ae19c3b8
ℹ️ 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".
…fix (#3211) ## Summary The census spill's decoded-session RAM layer now budgets by estimated tree bytes (adaptive RAM/16, clamped [256MiB, 2GiB]) instead of a fixed 256MiB of payload bytes, and `estimate_parsed_tree_bytes` moves to `polylogue/pipeline/parsed_tree_size.py` so both the daemon prefetch cache and `sources/` can share it without a layering violation. ## Problem Live whale-page telemetry (post-#3208/#3210): `spill_load` stuck at ~112-124s per page — whale trees exceed the payload-denominated decoded budget and fall through to sqlite+pickle decode every cohort. ## Solution Estimator relocation (verbatim, calibration comment intact; daemon imports from the new home), tree-byte accounting in `_ParsedSessionSpill` with FIFO eviction and whales-never-retained, topology projection regenerated for the new module. ## Verification `devtools test tests/unit/sources/test_revision_backfill.py tests/unit/daemon/test_parse_prefetch.py` → 51 passed; mypy clean; `render topology-projection`/`topology-status` committed. Live page timings from the resumed walk will be posted as the receipt. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Performance** * Improved memory estimation for parsed session data. * Updated decoded-session caching to budget and evict based on estimated in-memory usage. * **Bug Fixes** * Improved archive membership replay handling for equivalent raw revisions, while keeping protections against unrelated revisions. * **Documentation** * Refreshed topology projection outputs and “topology status” summary metrics to match the latest structure. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…k bool env vars (#3340) ## Summary Fresh `devtools verify --all` re-triage of polylogue-p6rz ("pre-existing test failures unrelated to MCP cutover") against current master. Fixes several confirmed real regressions and stale test assertions found during the pass; files properly-scoped follow-up beads for the rest instead of leaving them as anonymous re-discoveries. ## Problem polylogue-p6rz's original list (from 2026-07-18) was stale: a lot has merged since. A fresh `devtools verify --all` run (107 failed, 14 errors on the pre-fix baseline) needed re-triage to separate fixed / persisting / newly introduced failures, and specifically to catch any real regression from this session's merges (query DSL AST schema, browser-capture approval flow, GitHub effect adapters, continuity replay wiring, etc.). ## Solution **Confirmed real regressions, fixed:** - `polylogue/config.py`: PR #3202's strict bool-env coercion rejected a blank `POLYLOGUE_FORCE_PLAIN=""` value with `ConfigError` instead of the old passthrough-as-falsy behavior, breaking a long-standing CLI test convention (and inconsistent with this same module's own NO_COLOR "blank means not requested" convention). Blank bool-key env values now resolve to `False`. - `polylogue/storage/sqlite/queries/mappers_support.py` and `polylogue/storage/blob_integrity.py`: PR #3155's three-tier JSON facade introduced `polylogue.core.json.JSONDecodeError` (a `ValueError` subclass, NOT a stdlib `json.JSONDecodeError` subclass), but two call sites still caught the stdlib type — silently losing `DatabaseError` diagnostic wrapping (field/record id context) and blob-corruption graceful degradation since 2026-07-19. **Stale test assertions / drifted mocks, fixed:** - `tests/unit/cli/test_color_and_layout.py`: tested `no_color_requested()`/ `should_use_plain()` as if they read `NO_COLOR` from the environment directly; PR #3079 made them pure passthroughs (env resolution moved to `config.py`, already covered elsewhere). Rewrote to test the passthrough contract. - `tests/unit/storage/test_durable_migrations.py`: hardcoded `USER_SCHEMA_VERSION == 9` / `applied_versions` tuple; PR #3068 bumped it to 10 without updating these two tests. - `tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr`: stale `index.db` `user_version`/`sqlite_stat1_rows` snapshot from before PR #3235's schema bump 42→43. - `tests/unit/cli/test_diagnostics.py`: `_patch_tool_count_store`'s fake `ArchiveStore.open_existing` lambda didn't accept the `read_timeout` kwarg PR #2964 added, and the fake store was missing `begin_read_snapshot()` (also from #2964's interruptible-read protocol) — 8 tests broken since 2026-07-17. - `tests/unit/devtools/test_mandate_continuity_replay.py` and `tests/unit/operations/test_work_effect_reconciliation.py`: both asserted the real `GitHubPullRequestEffectAdapter` fails against `Sinity/polylogue` — true only in an environment without `gh` auth (e.g. stock CI), false on any dev machine with `gh` authenticated for this repo (confirmed: `gh pr list --repo Sinity/polylogue` succeeds fine here). Forced deterministic unavailability via a nonexistent `gh_path` instead. - `tests/unit/storage/test_delegations_view.py`: 3 tests opened a bare `index.db`-only `ArchiveStore` (no `user.db`); PR #3068's new `archive_snapshot_epoch()` unconditionally requires `user_tier` attached. Added a sibling `user.db` bootstrap to the 3 affected fixtures — matches every other test's full-tier archive construction. - `tests/unit/architecture/test_surface_storage_boundary.py`: allow-listed two CLI commands (`reconcile_work_effects.py`, and `materialize_incident_evidence.py` — the latter landed on master via a concurrent session's PR #3336 mid-rebase) that construct `SessionRepository` directly instead of through `AppEnv.repository`, per the test's own documented remediation path. Filed polylogue-a7uk for the proper fix. **Concurrent-session note:** this branch was rebased onto master mid-flight after another session's PR #3332 landed fixing the exact same `test_timestamp_guards.py` hypothesis-6.161 mypy break I'd independently found and fixed — kept master's version (identical `st.one_of` split approach) rather than duplicating it. **Already tracked, not duplicated:** - `test_execution_control.py` `api.query_units` naming mismatch + `>=50000 VM steps` anti-vacuity mutation tests → polylogue-1ldl (fully root-caused 2026-07-20: PR #3018 made the mutation-under-test no longer expensive at this data scale). - `test_live_batch_support.py` stale `failed=[...]` assertion → polylogue-5202. - `test_archive_maintenance_cli.py` / `test_daemon_cli.py` 6-node cluster → polylogue-p5li. - `tests/infra/surfaces.py` stale `list_sessions`/`search` MCP tool-name lookups (affects `test_retrieval_readiness_laws.py`, `test_cross_surface_agreement.py`) → polylogue-t46.8 (MCP tool-sprawl replacement epic; p6rz's own original text already called this out-of-scope). **New follow-up beads filed (confirmed pre-existing, not this-session regressions, but not safe/minimal to fix inline):** - polylogue-57w4 — repair path still disagrees with converger on NULL-sort-key session-profile staleness (regresses PR #2900's own invariant; root cause not fully diagnosed). - polylogue-lbgc — seeded-archive corpus build hits `database is locked` under xdist parallel first-build (affects `test_plain_cli_snapshots.py`, `test_schema_generation.py`, likely others); confirmed not simple cross-worker contention (the build already holds an exclusive flock across the whole build+integrity-check section) — more likely an unclosed intra-process connection. - polylogue-e6a0 — `test_index_v37_fast_forward.py`'s v36 fixture predates the `action_pairs` runtime index added by PR #3210; attempted fix revealed the fixture's intended "before" shape needs the full same-version benign-DDL-convergence set, not just `ensure_runtime_indexes_sync` — reverted the attempt rather than ship an incomplete fixture. No regression found from this session's headline PRs (query DSL AST schema, browser-capture approval flow, continuity replay wiring) — the two GitHub effect-adapter tests and the `materialize_incident_evidence.py` boundary violation are environment/pattern issues in supporting test/command code, not in the new capability logic itself. ## Verification - `devtools test` on every changed test file individually: all green (see per-file evidence above). - `mypy --strict` on every changed `.py` file: clean. - `ruff format --check` / `ruff check`: clean. - Fresh `devtools verify --all` run against this branch in progress; will update this PR/polylogue-p6rz with the final authoritative count once it completes (~14 min runtime). Ref polylogue-p6rz
|
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
Mechanical (no end-state row changes), zero-migration write-path throughput fixes for the archive
index.dbfull-replace/rebuild path, driven by measured per-page stage timings from live v42 rebuild walks. Three fixes:idx_paste_spans_session— the one projection table_clear_session_projection_rowscleared without an indexed path.functools.lru_cacheon the pricing-catalog identity hash — recomputed a SHA-256 over the ~3.5K-entry in-memoryPRICINGdict on every session write.idx_action_pairs_tool_result_block— the dominant fix, addressing a coordinator-flagged pathological whale-session regression inclear_projection_rows.Problem
Measured per-page stage timings from a live v42 rebuild (2,000-raw page):
membership_replay.index.full_replace=31.8s,.full_replace.clear_projection_rows=11.1s,.index.model_usage_seed=8.5s,.full_replace.messages=7.9s,.full_replace.blocks=6.6s,.full_replace.delete_messages=4.6s.A follow-up live walk over a whale-dense page (500 raws) showed
clear_projection_rowsscaling pathologically with whale-session size, not just raw count:92.7sfor 500 whale raws vs11.1sfor 2,000 normal raws.Solution
paste_spansindex —_clear_session_projection_rowsdeletes 10 projection tables bysession_idbefore a full-session replace.EXPLAIN QUERY PLANshowed 9 of them hit an index (mostly their PK);paste_spans(PK is(message_id, position), nosession_idindex) did a full tableSCAN. Addedidx_paste_spans_sessionto canonical DDL (archive_tiers/index.py) and tostorage/sqlite/runtime_indexes.py'sensure_runtime_indexes_sync/async(existing archives pick it up on next connect — no rebuild orINDEX_SCHEMA_VERSIONbump needed, same mechanism already used foridx_messages_active_leafetc).Pricing catalog hash memoization —
model_usage_seedcallsseed_price_catalog()per session, which recomputed_catalog_hash()(a SHA-256 over the ~3.5K-entry in-memoryPRICINGdict) every time.PRICINGis built once at module import and never mutated in production (grepped for write sites). Memoized_catalog_hash()/_effective_at_ms()withfunctools.lru_cache(maxsize=1); the one test that deliberately mutatesPRICINGmid-process (test_pricing_chain_roundtrip.py) now clears the memo around itsmonkeypatch.setitemcall (and viarequest.addfinalizer, so it doesn't leak a stale hash into later tests in the same worker process).action_pairs.tool_result_block_idindex (primary fix) — this column isON DELETE SET NULLagainstblocks(block_id)but had no supporting index. Every deleted block row requires SQLite to find matchingaction_pairsrows to null out; without an index that's a fullaction_pairstableSCANper deleted block row. For a whale session's full-replace blockDELETE(thousands of blocks) against an archive-wideaction_pairstable, that'sO(deleted_blocks × action_pairs_row_count), notO(deleted_blocks)— exactly the pathological whale-session scaling the coordinator flagged.EXPLAIN QUERY PLANon the parentDELETE FROM blocksstatement doesn't surface this cost (it's hidden inside the FKSET NULLaction), so this required end-to-end profiling viawrite_parsed_session_to_archive's ownstage_timings_sto isolate. Addedidx_action_pairs_tool_result_block(partial, excludesNULL) to bothindex.pyandruntime_indexes.py.Rejected candidates (evaluated, not applied)
executemanyin_write_messages/_write_blocks. Theblocks_action_pairs_*triggers that would otherwise refreshaction_pairsper-row are already guarded byderived_refresh_guard('session-write')during a session write.delete_messages: already hitsidx_messages_session_material_origin; everymessages(message_id)-FK child table with a CASCADE/SET NULL action already has a supporting index (verified viaPRAGMA foreign_key_list+EXPLAIN QUERY PLANon all 9 referencing tables). No scan found.session_model_usageskip-unchanged reseed: skipping reseeds when the model set is unchanged needs a same-session-token-change signal beyond the model set (aggregated tokens can change without the model set changing undermerge_append); the dominant cost there (catalog hash recompute) is already fixed with zero correctness risk, so this was left as a follow-up rather than risking a subtly wrong skip condition.Verification
devtools test tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_archive_tiers_ddl.py tests/unit/storage/test_revision_replay.py tests/unit/storage/test_pricing_chain_roundtrip.py tests/unit/storage/test_delegation_facts_bulk_rebuild.py tests/unit/storage/test_planner_statistics_seed.py tests/unit/storage/test_schema_policy_contracts.py tests/unit/storage/test_bulk_build_lifecycle.py→ 159 passed(
tests/unit/storage/test_crud.py, named in the original task brief, no longer exists under that path in this checkout — substituted the write/ddl/revision-replay/action_pairs-consuming equivalents that cover the touched surface)mypy --stricton all touched files → successdevtools verify --quick→ 16/16 steps ok (ran twice, once per commit)Benchmark receipts (ad hoc scripts, run manually —
.agent/scratch/is gitignored, not committed)paste_spansDELETE, synthetic 100K-row table, 2,000 session deletes:Pricing catalog hash, 2,000x
seed_price_catalog()calls:action_pairs.tool_result_block_id— whale session (3,000 tool_use/tool_result pairs = 6,000 blocks) full-replace rewrite against a realistic archive-wideaction_pairspopulation (40,000 rows from other sessions), through the realwrite_parsed_session_to_archivepath,stage_timings_sbreakdown:(Before/after numbers cross-checked against the actual unfixed main checkout via explicit
sys.pathselection, not just a stashed diff, after discovering and correcting apython3 <script>.pyinvocation quirk wheresys.path[0]resolves to the script's own directory rather than cwd, silently falling through to the main checkout's editable-installpolylogue— this worktree'sbench-whale-full-replace.pyinvoked directly was accidentally measuring the unfixed code the first several times.)Other whale-scale stages in the same benchmark come out proportional to session size and already indexed:
blocks=0.40s,messages=0.21s,delete_messages=0.05sfor 6,000 blocks / 3,001 messages — no further scan found on any FK path offblocks(block_id)ormessages(message_id).Ref polylogue-623q
Summary by CodeRabbit