Repository navigation
perf(storage): scope session-profile backfill UPDATEs to partial indexes - #522
Conversation
Closes #487. The three SchemaBackfillDescriptor entries for session_profiles each ran a full-table UPDATE on every connection bootstrap: UPDATE session_profiles SET evidence_search_text = search_text WHERE TRIM(COALESCE(evidence_search_text, '')) = '' Same shape for inference_search_text and enrichment_search_text. The gating WHERE made each idempotent, but the table scan ran every time — adding measurable startup latency on archives with millions of session profiles. Add a partial index per backfill, scoped to the same WHERE clause: CREATE INDEX idx_session_profiles_<col>_unbackfilled ON session_profiles(conversation_id) WHERE TRIM(COALESCE(<col>, '')) = '' SQLite uses the partial index when the query's WHERE matches the index's WHERE exactly (verified with EXPLAIN QUERY PLAN: "SCAN session_profiles USING INDEX idx_unbackfilled"). On the first run the optimizer hits the partial index instead of the table; on every subsequent run the index is empty (rows leave the index as soon as they're backfilled), so the UPDATE drains an empty index instead of scanning the table. Indexes are placed before the matching backfill descriptors so they exist on the same bootstrap that fires the first UPDATE. Verification: devtools verify --quick green. Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughThe changes add three partial indexes on Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@polylogue/storage/backends/schema_bootstrap.py`:
- Around line 373-405: Add a regression test that verifies SQLite's planner
actually chooses the partial indexes created by the
SchemaIndexExtensionDescriptor entries
(idx_session_profiles_evidence_search_text_unbackfilled,
idx_session_profiles_inference_search_text_unbackfilled,
idx_session_profiles_enrichment_search_text_unbackfilled) by running EXPLAIN
QUERY PLAN for each corresponding UPDATE (e.g., UPDATE session_profiles SET
evidence_search_text = search_text WHERE TRIM(COALESCE(evidence_search_text,
'')) = '') against a freshly bootstrapped DB and asserting the EXPLAIN output
references the expected index name; place the test near existing
bootstrap/schema tests and run the same three variants
(evidence/inference/enrichment) so future edits to the predicate will fail the
test if the planner no longer uses the partial indexes.
- Around line 379-405: The three new partial index descriptors using
SchemaIndexExtensionDescriptor
(idx_session_profiles_evidence_search_text_unbackfilled,
idx_session_profiles_inference_search_text_unbackfilled,
idx_session_profiles_enrichment_search_text_unbackfilled) should set
replace_on_drift=True to ensure future predicate changes rebuild existing
indexes; update each descriptor to include replace_on_drift=True so that the
schema comparison logic will replace stale WHERE clauses on drift (matching the
behavior used by idx_raw_conv_source_mtime).
In `@tests/unit/storage/test_backend.py`:
- Around line 226-230: The test currently finds the UPDATE row using a loose
substring check ("column in s") which can incorrectly match the enrichment
backfill when searching for "inference_search_text"; tighten the UPDATE-matching
predicate in the loop that iterates over statements so update_position is found
by checking both "UPDATE session_profiles" and the explicit SET clause (e.g.
f"SET {column} =" ) in the statement string; keep the existing index_position
lookup using the idx_session_profiles_{column}_unbackfilled pattern and assert
index_position < update_position as before.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 6702d3ba-74d5-471f-b303-23bcf3b6389a
📒 Files selected for processing (2)
polylogue/storage/backends/schema_bootstrap.pytests/unit/storage/test_backend.py
| # Partial indexes scoped to the gating WHERE clause of each backfill below. | ||
| # SQLite uses a partial index when the query's WHERE matches the index's WHERE | ||
| # exactly, so the backfill UPDATE becomes an index lookup. Once a row is | ||
| # backfilled the gating condition no longer holds and the row leaves the | ||
| # index, so subsequent connection bootstraps scan an empty index instead of | ||
| # the full session_profiles table. | ||
| SchemaIndexExtensionDescriptor( | ||
| table_name="session_profiles", | ||
| index_name="idx_session_profiles_evidence_search_text_unbackfilled", | ||
| ddl=( | ||
| "CREATE INDEX IF NOT EXISTS idx_session_profiles_evidence_search_text_unbackfilled " | ||
| "ON session_profiles(conversation_id) " | ||
| "WHERE TRIM(COALESCE(evidence_search_text, '')) = ''" | ||
| ), | ||
| ), | ||
| SchemaIndexExtensionDescriptor( | ||
| table_name="session_profiles", | ||
| index_name="idx_session_profiles_inference_search_text_unbackfilled", | ||
| ddl=( | ||
| "CREATE INDEX IF NOT EXISTS idx_session_profiles_inference_search_text_unbackfilled " | ||
| "ON session_profiles(conversation_id) " | ||
| "WHERE TRIM(COALESCE(inference_search_text, '')) = ''" | ||
| ), | ||
| ), | ||
| SchemaIndexExtensionDescriptor( | ||
| table_name="session_profiles", | ||
| index_name="idx_session_profiles_enrichment_search_text_unbackfilled", | ||
| ddl=( | ||
| "CREATE INDEX IF NOT EXISTS idx_session_profiles_enrichment_search_text_unbackfilled " | ||
| "ON session_profiles(conversation_id) " | ||
| "WHERE TRIM(COALESCE(enrichment_search_text, '')) = ''" | ||
| ), | ||
| ), |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Optional: add an EXPLAIN QUERY PLAN regression test to lock in optimizer use.
The whole optimization hinges on SQLite's planner picking each partial index because the UPDATE's WHERE matches the index predicate byte-for-byte (modulo whitespace). Any future edit that drifts the predicates apart (e.g., changing TRIM(COALESCE(col, '')) to COALESCE(TRIM(col), '') on one side, or replacing '' with '' COLLATE NOCASE) would silently regress to a full scan with no test failure — exactly the bug #487 is closing.
Consider a focused test that bootstraps a fresh DB, then runs EXPLAIN QUERY PLAN UPDATE session_profiles SET evidence_search_text = search_text WHERE TRIM(COALESCE(evidence_search_text, '')) = '' (and the inference/enrichment variants) and asserts the plan output references each idx_session_profiles_*_unbackfilled index. That cheaply guards the invariant that justifies these descriptors existing at all.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/backends/schema_bootstrap.py` around lines 373 - 405, Add a
regression test that verifies SQLite's planner actually chooses the partial
indexes created by the SchemaIndexExtensionDescriptor entries
(idx_session_profiles_evidence_search_text_unbackfilled,
idx_session_profiles_inference_search_text_unbackfilled,
idx_session_profiles_enrichment_search_text_unbackfilled) by running EXPLAIN
QUERY PLAN for each corresponding UPDATE (e.g., UPDATE session_profiles SET
evidence_search_text = search_text WHERE TRIM(COALESCE(evidence_search_text,
'')) = '') against a freshly bootstrapped DB and asserting the EXPLAIN output
references the expected index name; place the test near existing
bootstrap/schema tests and run the same three variants
(evidence/inference/enrichment) so future edits to the predicate will fail the
test if the planner no longer uses the partial indexes.
| SchemaIndexExtensionDescriptor( | ||
| table_name="session_profiles", | ||
| index_name="idx_session_profiles_evidence_search_text_unbackfilled", | ||
| ddl=( | ||
| "CREATE INDEX IF NOT EXISTS idx_session_profiles_evidence_search_text_unbackfilled " | ||
| "ON session_profiles(conversation_id) " | ||
| "WHERE TRIM(COALESCE(evidence_search_text, '')) = ''" | ||
| ), | ||
| ), | ||
| SchemaIndexExtensionDescriptor( | ||
| table_name="session_profiles", | ||
| index_name="idx_session_profiles_inference_search_text_unbackfilled", | ||
| ddl=( | ||
| "CREATE INDEX IF NOT EXISTS idx_session_profiles_inference_search_text_unbackfilled " | ||
| "ON session_profiles(conversation_id) " | ||
| "WHERE TRIM(COALESCE(inference_search_text, '')) = ''" | ||
| ), | ||
| ), | ||
| SchemaIndexExtensionDescriptor( | ||
| table_name="session_profiles", | ||
| index_name="idx_session_profiles_enrichment_search_text_unbackfilled", | ||
| ddl=( | ||
| "CREATE INDEX IF NOT EXISTS idx_session_profiles_enrichment_search_text_unbackfilled " | ||
| "ON session_profiles(conversation_id) " | ||
| "WHERE TRIM(COALESCE(enrichment_search_text, '')) = ''" | ||
| ), | ||
| ), |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider replace_on_drift=True for forward compatibility.
Existing index descriptors that you might want to evolve (e.g., idx_raw_conv_source_mtime on line 190) carry replace_on_drift=True so that a predicate change in code rebuilds the index on existing databases. The three new partial indexes leave it at the default False. That's fine for the initial rollout — if the code never changes the WHERE clause, drift is impossible — but if you ever tweak the predicate (NULL semantics, COLLATE, etc.) without flipping this flag, older archives will silently keep the stale predicate and the UPDATE will fall back to a full scan. Worth flipping to True now to make future predicate edits self-healing, given normalization already strips IF NOT EXISTS for comparison.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/backends/schema_bootstrap.py` around lines 379 - 405, The
three new partial index descriptors using SchemaIndexExtensionDescriptor
(idx_session_profiles_evidence_search_text_unbackfilled,
idx_session_profiles_inference_search_text_unbackfilled,
idx_session_profiles_enrichment_search_text_unbackfilled) should set
replace_on_drift=True to ensure future predicate changes rebuild existing
indexes; update each descriptor to include replace_on_drift=True so that the
schema comparison logic will replace stale WHERE clauses on drift (matching the
behavior used by idx_raw_conv_source_mtime).
| statements = list(plan.statements) | ||
| for column in ("evidence_search_text", "inference_search_text", "enrichment_search_text"): | ||
| index_position = next(i for i, s in enumerate(statements) if f"idx_session_profiles_{column}_unbackfilled" in s) | ||
| update_position = next(i for i, s in enumerate(statements) if "UPDATE session_profiles" in s and column in s) | ||
| assert index_position < update_position, f"{column}: index must be created before its backfill UPDATE" |
There was a problem hiding this comment.
Tighten the UPDATE-matching predicate to the SET <column> = clause.
The column in s substring check is ambiguous for inference_search_text: the enrichment backfill UPDATE (SET enrichment_search_text = inference_search_text WHERE …) also contains the substring inference_search_text. The test currently selects the correct (inference) UPDATE only because next() returns the first hit in descriptor order. If the inference and enrichment backfills were ever reordered — which would be a real correctness regression, since the enrichment UPDATE depends on inference being populated first — this assertion would still pass.
Match against the SET <column> = clause to anchor each UPDATE to the column it actually backfills:
🧪 Proposed tightening
statements = list(plan.statements)
for column in ("evidence_search_text", "inference_search_text", "enrichment_search_text"):
index_position = next(i for i, s in enumerate(statements) if f"idx_session_profiles_{column}_unbackfilled" in s)
- update_position = next(i for i, s in enumerate(statements) if "UPDATE session_profiles" in s and column in s)
+ update_position = next(
+ i for i, s in enumerate(statements)
+ if "UPDATE session_profiles" in s and f"SET {column} =" in s
+ )
assert index_position < update_position, f"{column}: index must be created before its backfill UPDATE"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_backend.py` around lines 226 - 230, The test
currently finds the UPDATE row using a loose substring check ("column in s")
which can incorrectly match the enrichment backfill when searching for
"inference_search_text"; tighten the UPDATE-matching predicate in the loop that
iterates over statements so update_position is found by checking both "UPDATE
session_profiles" and the explicit SET clause (e.g. f"SET {column} =" ) in the
statement string; keep the existing index_position lookup using the
idx_session_profiles_{column}_unbackfilled pattern and assert index_position <
update_position as before.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…xes (#522) ## Summary Scopes the three session_profiles backfill UPDATEs to partial indexes so repeated connection bootstraps drain an empty index instead of scanning the full table. Closes #487. ## Problem `schema_bootstrap.py` runs three `SchemaBackfillDescriptor` entries on every connection bootstrap when the schema is at the current version: \`\`\`sql UPDATE session_profiles SET evidence_search_text = search_text WHERE TRIM(COALESCE(evidence_search_text, '')) = '' \`\`\` Same shape for `inference_search_text` and `enrichment_search_text`. The gating `WHERE TRIM(COALESCE(...)) = ''` made each idempotent, but the table scan ran every time — measurable startup latency on archives with millions of session profiles. ## Solution Add a partial index per backfill, scoped to the exact same WHERE clause: \`\`\`sql CREATE INDEX IF NOT EXISTS idx_session_profiles_<col>_unbackfilled ON session_profiles(conversation_id) WHERE TRIM(COALESCE(<col>, '')) = '' \`\`\` SQLite uses the partial index when the query's WHERE matches the index's WHERE exactly. Verified with `EXPLAIN QUERY PLAN`: \`\`\` (5, 0, 214, 'SCAN session_profiles USING INDEX idx_unbackfilled') \`\`\` On the first bootstrap after this lands the optimizer hits the partial index (still cheaper than a full scan because we only index unbackfilled rows). On every subsequent bootstrap the index is empty (rows leave the partial index as soon as they're backfilled), so the UPDATE drains an empty index instead of touching the table. The index descriptors are placed *before* the matching backfill descriptors in `_SCHEMA_EXTENSION_DESCRIPTORS` so the indexes exist on the same bootstrap that runs the first UPDATE. Test asserts the ordering invariant. Considered but rejected: tracking backfill completion via `PRAGMA user_version` metadata or a status table. Both are more invasive (new persistence path, custom comparison logic) for a problem the existing partial-index machinery solves cleanly. ## Verification \`\`\` $ nix develop -c pytest -q tests/unit/storage/test_backend.py -x 30 passed in 70.28s $ nix develop -c devtools verify --quick verify: all checks passed \`\`\` Three pre-existing flakes in the full pytest run (`test_fts_search_budget`, `test_batch_insert_under_budget`, `test_cli_tail_list_json_exposes_tail_provenance`) all pass when re-run individually — order/budget sensitive, unrelated to this change. EXPLAIN proof: \`\`\`python import sqlite3 con = sqlite3.connect(':memory:') con.executescript(''' CREATE TABLE session_profiles (conversation_id TEXT PRIMARY KEY, search_text TEXT NOT NULL DEFAULT '', evidence_search_text TEXT NOT NULL DEFAULT ''); INSERT INTO session_profiles (conversation_id, search_text) VALUES ('a', 'foo'), ('b', 'bar'), ('c', 'baz'); UPDATE session_profiles SET evidence_search_text = 'done' WHERE conversation_id = 'a'; CREATE INDEX idx_unbackfilled ON session_profiles(conversation_id) WHERE TRIM(COALESCE(evidence_search_text, '')) = ''; ''') for row in con.execute("EXPLAIN QUERY PLAN UPDATE session_profiles SET evidence_search_text = search_text WHERE TRIM(COALESCE(evidence_search_text, '')) = ''"): print(row) # (5, 0, 214, 'SCAN session_profiles USING INDEX idx_unbackfilled') \`\`\` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Added partial database indexes on session search text fields (evidence, inference, enrichment). * Enhanced test coverage for schema extension planning and index statement ordering validation. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude <[email protected]>
Summary
Scopes the three session_profiles backfill UPDATEs to partial indexes so repeated connection bootstraps drain an empty index instead of scanning the full table.
Closes #487.
Problem
schema_bootstrap.pyruns threeSchemaBackfillDescriptorentries on every connection bootstrap when the schema is at the current version:```sql
UPDATE session_profiles SET evidence_search_text = search_text
WHERE TRIM(COALESCE(evidence_search_text, '')) = ''
```
Same shape for
inference_search_textandenrichment_search_text. The gatingWHERE TRIM(COALESCE(...)) = ''made each idempotent, but the table scan ran every time — measurable startup latency on archives with millions of session profiles.Solution
Add a partial index per backfill, scoped to the exact same WHERE clause:
```sql
CREATE INDEX IF NOT EXISTS idx_session_profiles__unbackfilled
ON session_profiles(conversation_id)
WHERE TRIM(COALESCE(, '')) = ''
```
SQLite uses the partial index when the query's WHERE matches the index's WHERE exactly. Verified with
EXPLAIN QUERY PLAN:```
(5, 0, 214, 'SCAN session_profiles USING INDEX idx_unbackfilled')
```
On the first bootstrap after this lands the optimizer hits the partial index (still cheaper than a full scan because we only index unbackfilled rows). On every subsequent bootstrap the index is empty (rows leave the partial index as soon as they're backfilled), so the UPDATE drains an empty index instead of touching the table.
The index descriptors are placed before the matching backfill descriptors in
_SCHEMA_EXTENSION_DESCRIPTORSso the indexes exist on the same bootstrap that runs the first UPDATE. Test asserts the ordering invariant.Considered but rejected: tracking backfill completion via
PRAGMA user_versionmetadata or a status table. Both are more invasive (new persistence path, custom comparison logic) for a problem the existing partial-index machinery solves cleanly.Verification
```
$ nix develop -c pytest -q tests/unit/storage/test_backend.py -x
30 passed in 70.28s
$ nix develop -c devtools verify --quick
verify: all checks passed
```
Three pre-existing flakes in the full pytest run (
test_fts_search_budget,test_batch_insert_under_budget,test_cli_tail_list_json_exposes_tail_provenance) all pass when re-run individually — order/budget sensitive, unrelated to this change.EXPLAIN proof:
```python
import sqlite3
con = sqlite3.connect(':memory:')
con.executescript('''
CREATE TABLE session_profiles (conversation_id TEXT PRIMARY KEY, search_text TEXT NOT NULL DEFAULT '', evidence_search_text TEXT NOT NULL DEFAULT '');
INSERT INTO session_profiles (conversation_id, search_text) VALUES ('a', 'foo'), ('b', 'bar'), ('c', 'baz');
UPDATE session_profiles SET evidence_search_text = 'done' WHERE conversation_id = 'a';
CREATE INDEX idx_unbackfilled ON session_profiles(conversation_id) WHERE TRIM(COALESCE(evidence_search_text, '')) = '';
''')
for row in con.execute("EXPLAIN QUERY PLAN UPDATE session_profiles SET evidence_search_text = search_text WHERE TRIM(COALESCE(evidence_search_text, '')) = ''"):
print(row)
(5, 0, 214, 'SCAN session_profiles USING INDEX idx_unbackfilled')
```
Summary by CodeRabbit