Repository navigation
perf(storage): guard-gate messages_fts triggers for prefix-tail bulk delete - #3152
Conversation
…delete
Problem: whale prefix-sharing lineage sessions (fork/resume/auto-compaction)
can carry 10K+ tool blocks in an inherited prefix. write_parsed_session_to_archive
-> _resolve_session_graph -> _reextract_prefix_tail_db deletes that prefix's
blocks one row at a time once the parent is known, and messages_fts_ad fires
per deleted row (contentless-FTS posting-list maintenance) with no bulk
fallback on this path -- measured as a 25+ minute single-DELETE stall on the
live rebuild (bead polylogue-crd8). A prior attempt to suspend the trigger by
raw DROP TRIGGER across the whole write broke assert_session_fts_exact_sync's
trigger-presence check and was reverted; that postmortem designed the
guard-row approach implemented here.
Solution: messages_fts_{ai,ad,au} (polylogue/storage/fts/sql.py) gain a
`WHEN NOT EXISTS (SELECT 1 FROM derived_refresh_guard WHERE guard_name =
'fts-bulk-session-write')` clause -- a *dedicated* guard name, deliberately
not the existing 'session-write' guard (that guard is set for every write;
reusing it would silently stop FTS indexing for ordinary daemon ingest, not
just whale replays). Triggers stay structurally present in sqlite_master at
all times; only their bodies short-circuit, so assert_session_fts_exact_sync's
trigger-presence check needs no change.
write.py's new `_bulk_fts_session_guard` context manager sets the guard row,
does one explicit session-scoped FTS delete (delete_session_rows_sql) before
the caller's block mutation and one explicit re-insert (insert_session_rows_sql)
in the `finally`, mirroring the same delete-then-insert shape
`_replace_full_session_messages_and_blocks` already uses for a session's own
full replace. `_reextract_prefix_tail_db` wraps both dependent-delete branches
(`_delete_prefix_message_dependents` and `_delete_all_session_message_dependents`)
in this guard when `bulk_fts=True`. The flag threads default-`False` through
`write_parsed_session_to_archive` -> `_resolve_session_graph` ->
`_reextract_prefix_tail_db`, and through archive.py's `apply_raw_revision_replay`
/ `apply_raw_membership_classification` -> `_index_parsed_for_retained_raw` ->
`_write_parsed_precedence_result` (only its `revision_authoritative` branch),
and `sources/revision_backfill.py`'s `backfill_historical_revision_evidence`.
Only `maintenance/rebuild_index.py`'s offline rebuild call (an owned inactive
generation, never live daemon ingest) passes `bulk_fts=True`; ordinary daemon
writes are byte-for-byte unchanged.
Deviation from the bead's literal design text: the design named
`_replace_full_session_messages_and_blocks`/`_clear_session_projection_rows`
as the guard locus, but source tracing showed those already have their own
(separate, always-on, DROP/CREATE-based) FTS optimization for a session's own
replace and are not on the measured whale call path.
`_reextract_prefix_tail_db` (via `_resolve_session_graph`, called from inside
the SAME 'session-write'-guarded transaction) is the actual site deleting a
cascading child's inherited-prefix blocks, so the new guard targets that
instead.
No INDEX_SCHEMA_VERSION bump: the trigger DDL change is additive/inert on an
existing archive (CREATE TRIGGER IF NOT EXISTS keeps the old trigger body
until a rebuild; the guard row is simply never present on old archives, so
they behave exactly as before -- no correctness change, only forgone perf
until rebuilt). test_fresh_init_creates_canonical_fts_trigger_set
(test_schema_policy_contracts.py, #3144) compares trigger NAMES via an
INSERT/DELETE-INTO-fts-table substring match, not bodies, so it is unaffected.
Verification:
- devtools test tests/unit/storage/test_bulk_fts_prefix_reextract.py
tests/unit/storage/test_lineage_normalization.py
tests/unit/storage/test_revision_application.py
tests/unit/storage/test_schema_policy_contracts.py
tests/unit/storage/test_archive_tiers_write.py
tests/unit/storage/test_prefix_dependent_delete_indexes.py
tests/unit/sources/test_live_cursor_persistence.py
tests/unit/sources/test_revision_backfill.py
tests/unit/storage/test_repair.py
-> 214 passed
- devtools verify --quick -> exit 0
- Confirmed via git diff/checkout/apply revert-and-rerun (no stash, per
worktree policy) that 5 pre-existing failures in test_live_batch_support.py
and 14 pre-existing failures across test_retrieval_readiness_laws.py /
test_dangling_fts_derived_surfaces.py / test_embedding_freshness_invariant.py
/ test_durable_migrations.py / test_index_fast_forward_lifecycle.py /
test_delegations_view.py / test_archive_tiers_archive.py reproduce
identically without this change -- unrelated pre-existing drift, not caused
here.
Ref polylogue-crd8
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. |
📝 WalkthroughWalkthroughOffline rebuild and revision backfill now propagate ChangesBulk FTS replay
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant OfflineRebuild
participant RevisionBackfill
participant ArchiveStore
participant SessionWriter
participant MessagesFTS
OfflineRebuild->>RevisionBackfill: backfill_historical_revision_evidence(bulk_fts=True)
RevisionBackfill->>ArchiveStore: apply_raw_revision_replay(bulk_fts=True)
ArchiveStore->>SessionWriter: write_parsed_session_to_archive(bulk_fts=True)
SessionWriter->>MessagesFTS: guarded delete and explicit session reinsertion
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
polylogue/storage/sqlite/archive_tiers/archive.py (1)
1693-1704: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
bulk_ftsnot forwarded on thiswrite_parsed_session_to_archivecall site.
_write_parsed_precedence_resultacceptsbulk_fts(line 1553) and forwards it in therevision_authoritativebranch (line 1584), but this second call (content-changed, non-revision-authoritative branch) drops it, silently falling back to the defaultFalse. Today this is unreachable — every caller that setsbulk_fts=True(apply_raw_revision_replay/apply_raw_membership_classification) always passesrevision_authoritative=True— but the parameter should still be threaded consistently so a future caller can't silently lose the optimization.🔧 Proposed fix
write_parsed_session_to_archive( self._conn, session, content_hash=content_hash, raw_id=raw_id, merge_append=source_index < 0, force_replace=browser_precedence == "replace", stage_timings_s=stage_timings_s, stage_timing_prefix=stage_timing_prefix, preacquired_attachment_blobs=preacquired_attachment_blobs, manage_transaction=manage_transaction, + bulk_fts=bulk_fts, )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@polylogue/storage/sqlite/archive_tiers/archive.py` around lines 1693 - 1704, Update the write_parsed_session_to_archive call in _write_parsed_precedence_result’s content-changed, non-revision-authoritative branch to forward the method’s bulk_fts parameter. Keep the existing behavior and argument handling unchanged while ensuring bulk_fts is not lost and does not fall back to its default.polylogue/maintenance/rebuild_index.py (1)
271-286: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftGate
bulk_fts=Trueon the generation schema version
generation_store.load(...)can resume a preexisting candidate, andinitialize_archive_database()only applies the FTS trigger DDL on freshuser_version == 0initialization. A paused rebuild resumed after an upgrade can still carry oldermessages_fts_*trigger bodies, so force a rebootstrap or skip bulk FTS unless the generation is known to have the current DDL.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@polylogue/maintenance/rebuild_index.py` around lines 271 - 286, The offline rebuild call to replay_source currently enables bulk_fts unconditionally, which can use stale FTS trigger DDL in resumed generations. Gate bulk_fts on the generation’s schema version/current DDL compatibility, and ensure older generations are reinitialized or use the non-bulk path; preserve bulk FTS for generations confirmed to have the current schema.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@polylogue/maintenance/rebuild_index.py`:
- Around line 271-286: The offline rebuild call to replay_source currently
enables bulk_fts unconditionally, which can use stale FTS trigger DDL in resumed
generations. Gate bulk_fts on the generation’s schema version/current DDL
compatibility, and ensure older generations are reinitialized or use the
non-bulk path; preserve bulk FTS for generations confirmed to have the current
schema.
In `@polylogue/storage/sqlite/archive_tiers/archive.py`:
- Around line 1693-1704: Update the write_parsed_session_to_archive call in
_write_parsed_precedence_result’s content-changed, non-revision-authoritative
branch to forward the method’s bulk_fts parameter. Keep the existing behavior
and argument handling unchanged while ensuring bulk_fts is not lost and does not
fall back to its default.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: d23007ba-643d-485b-8342-382a1c60955b
📒 Files selected for processing (9)
polylogue/maintenance/rebuild_index.pypolylogue/maintenance/replay.pypolylogue/sources/revision_backfill.pypolylogue/storage/fts/sql.pypolylogue/storage/sqlite/archive_tiers/archive.pypolylogue/storage/sqlite/archive_tiers/write.pytests/unit/sources/test_live_cursor_persistence.pytests/unit/storage/test_bulk_fts_prefix_reextract.pytests/unit/storage/test_lineage_normalization.py
…3165) ## Summary Extends the offline rebuild path (`maintenance/rebuild_index.py`) so a bulk generation build keeps `messages_fts`, `blocks_command_trigram`, `action_pairs`, and `delegation_facts` empty for every session throughout replay, then repopulates all four archive-wide exactly once at readiness — replacing per-session maintenance that a full rebuild pays for and then immediately discards. ## Problem A live whale offline rebuild (bead polylogue-v6i3) stalled for 3+ hours doing per-session FTS/trigram maintenance one session at a time. During the same incident, an archive-wide `messages_fts` + `blocks_command_trigram` delete-all measured **28.7s** — evidence that the correct bulk-build lifecycle is "empty once, repopulate once," not per-session upkeep. The operator manually intervened mid-rebuild with a one-off script (`/realm/tmp/trigram-restore-pre-promote.py`) to clear and repopulate both surfaces between rebuild pages. #3152 already made the offline replay path avoid per-row trigger storms for one whale prefix-reextraction cascade (a guard-gated bulk delete+insert), but every session write still did its own `action_pairs`/`delegation_facts` refresh, and a full-session replace still did its own `messages_fts` delete/suspend-trigger/insert/restore dance — real, avoidable per-session work when a single archive-wide repopulate happens anyway at the end. ## Solution - `write_parsed_session_to_archive` gains `bulk_build` (alongside the existing `bulk_fts`), threaded through the same call chain #3152 built: `archive.py`'s `_write_parsed_precedence_result` / `apply_raw_revision_replay` / `apply_raw_membership_classification`, `sources/revision_backfill.py`, `maintenance/replay.py`. When `True`: - The whole-transaction `FTS_BULK_SESSION_WRITE_GUARD` row is set once per session write, gating **both** `messages_fts` and (newly) `blocks_command_trigram` trigger bodies for every block mutation in that write — not just the prefix-reextract cascade #3152 already guarded. - `_replace_full_session_messages_and_blocks` skips its own scoped FTS dance and `action_pairs` refresh entirely. - The merge-append path skips its `action_pairs` refresh. - `refresh_delegation_facts_for_session` is skipped. - `_bulk_fts_session_guard` becomes a no-op (the outer guard already covers it; no redundant per-session delete+insert). - `assert_session_fts_exact_sync` gains `bulk_build=False`: when `True` it skips the per-session row-count parity check (expected to be empty mid-build) but still enforces trigger presence — an explicit mode per the bead's requirement, not a weakened default. - New bulk repopulate primitives: - `rebuild_command_trigram_index_sync` (`storage/fts/fts_lifecycle.py`) — uses the FTS5 `'delete-all'` command required for this external-content table, then one bulk insert from `blocks`. - `action_pairs_refresh_all_sql` / `rebuild_all_action_pairs_sync` — a set-based, archive-wide variant with the per-session predicate simply removed. - `rebuild_all_delegation_facts_sync` — populates `delegation_refresh_scope` with every session id, reusing the existing view/insert SQL unmodified (that table already scopes `delegation_facts_source` by an allow-list, not an inline predicate, so no new SQL shape was needed). - `maintenance/rebuild_index.py` orchestrates the lifecycle: - `_clear_bulk_build_derived_stores` runs once per **resumed** operation, guarded by a new `IndexRebuildTransaction.derived_stores_cleared` marker (default `False`, persisted through `checkpoint_transaction`) so it never re-fires on a later page of the same operation. A fresh generation starts empty by construction and never needs this. - `_repopulate_bulk_build_derived_state` runs once at readiness (before `_archive_readiness_status`), followed by `verify_archive(checks=["fts-parity"])` — failing the operation loudly on any mismatch before promotion can ever see it. - `blocks_command_trigram`'s three triggers gain the same guard-row `WHEN` clause `messages_fts`'s triggers already had. No `INDEX_SCHEMA_VERSION` bump: additive/inert via `CREATE TRIGGER IF NOT EXISTS`, matching #3152's own precedent for this exact situation. **Measured** (`action_pairs` per-session vs set-based, 4,000 synthetic sessions × 6 tool_use/tool_result pairs): a per-session `refresh_action_pairs` loop took 64.2s vs 0.3s for the set-based statement — **216x**. This confirms the set-based readiness repopulate over a per-session loop for `action_pairs`. The manual pre-promote recovery script is the prototype this productizes; it is not deleted here (it references a specific in-flight generation path from a live incident that may still be relevant to the operator), but its clear+repopulate action is now this PR's automatic, code-verified lifecycle for every future bulk rebuild. ## Verification ``` devtools test tests/unit/storage/test_bulk_build_lifecycle.py \ tests/unit/storage/test_delegation_facts_bulk_rebuild.py \ tests/unit/maintenance/test_rebuild_index_bulk_build.py \ tests/unit/storage/test_index_generation.py \ tests/unit/storage/test_lineage_normalization.py \ tests/unit/storage/test_bulk_fts_prefix_reextract.py # 63 passed devtools verify --quick # exit 0 ``` New tests prove: `bulk_build=True` writes leave all four derived surfaces empty for the written session where mode-off populates them immediately (not vacuously true for every write); the readiness repopulate produces byte-identical `messages_fts`/`blocks_command_trigram`/`action_pairs` content to trickle-mode population of the same corpus (including a prefix-sharing lineage cascade exercising `_bulk_fts_session_guard`'s bulk-build no-op branch); `rebuild_all_delegation_facts_sync` matches per-session `refresh_delegation_facts_for_session` across resolved/ambiguous/edge-only mapping states; the whole-transaction guard row never leaks past an exception; `_clear_bulk_build_derived_stores` only touches the two named surfaces (not `action_pairs`/`blocks`) and is idempotent on an already-empty table; `_repopulate_bulk_build_derived_state` reaches exact archive-wide parity via `verify_archive`'s `fts-parity` check; two anti-vacuity tests (skip the readiness repopulate, skip the delegation scope population) show the corresponding equivalence proof then fails. Confirmed via `git diff`/`checkout`/`apply` revert-and-rerun (no stash, per worktree policy) that 5 pre-existing failures in `test_live_batch_support.py` and 3 in `test_delegations_view.py` (an unrelated `PRAGMA user_tier` attached-database gap in the query-transaction test fixture) reproduce identically on `master` without this change — pre-existing drift, not caused here. Ref polylogue-v6i3 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added bulk-build support for faster archive indexing by deferring derived search and relationship indexes until completion. - Added archive-wide rebuilding for full-text search, trigram search, action pairs, and delegation facts. - Added validation to confirm rebuilt indexes match archive content. - **Bug Fixes** - Prevented stale derived index data during resumed rebuilds. - Added safeguards to ensure temporary bulk-build state is cleared after failures. - **Tests** - Added coverage for bulk-build parity, recovery behavior, and index rebuild correctness. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude <[email protected]>
…materialization paths (#3259) ## Summary Turns on the #3152 guard-gated bulk-FTS mode (byte-identical by its parity suite) at the two daemon chokepoints that still ran per-row trigger mode: the live ingest write and the raw-materialization backfill (which the t93b whale pass uses). ## Problem Live incident 2026-07-22: the freshly deployed daemon's writer sat >1 hour on one whale-session prefix-tail rewrite — 260 GB read, zero commits, zero log lines — because every deleted row fired the full action_pairs + delegation_facts re-derivation (same pathology family as polylogue-meoz, but on the WRITE path). The crd8 close had recorded "live path stays per-row by design (bounded per-session writes)" — this session is the live counterexample; whale sessions exist on the live path. ## Solution `bulk_fts=True` at `_core.py`'s `write_parsed_session_to_archive` call and `repair.py`'s `backfill_historical_revision_evidence` call, with incident comments. No mechanism changes — the guard, parity proofs, and threading all exist since #3152. ## Verification - `devtools test tests/unit/storage/test_bulk_fts_prefix_reextract.py` → 6 passed (the byte-identity + guard-never-leaks + anti-vacuity suite). - `devtools test tests/unit/sources/test_live_batch_support.py tests/unit/storage/test_no_string_interpolated_sql.py` → 7 passed. - `devtools verify --quick` → exit 0. Ref polylogue-crd8 Ref polylogue-t93b 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ --------- Co-authored-by: Claude Fable 5 <[email protected]>
Summary
Adds a guard-row-gated bulk FTS mode for whale prefix-sharing lineage sessions
so the offline rebuild/backfill path can collapse per-row
messages_ftstrigger maintenance into one bulk delete+insert per affected session, without
changing ordinary daemon-ingest behavior.
Problem
Whale prefix-sharing lineage sessions (fork/resume/auto-compaction) can carry
10K+ tool blocks in an inherited prefix.
write_parsed_session_to_archive->_resolve_session_graph->_reextract_prefix_tail_dbdeletes that prefix'sblocks one row at a time once the parent session is known, and
messages_fts_adfires per deleted row (contentless-FTS posting-listmaintenance) with no bulk fallback on this path — measured live as a 25+
minute single-DELETE stall during the ongoing archive rebuild (bead
polylogue-crd8, 2026-07-19). A prior attempt to suspend the trigger via raw
DROP TRIGGERacross the whole write brokeassert_session_fts_exact_sync'strigger-presence check and was reverted; that postmortem designed the
guard-row approach implemented in this PR.
Solution
messages_fts_{ai,ad,au}(polylogue/storage/fts/sql.py) gain aWHEN NOT EXISTS (SELECT 1 FROM derived_refresh_guard WHERE guard_name = 'fts-bulk-session-write')clause — a dedicated guard name, deliberatelynot the existing
'session-write'guard (that guard is set unconditionallyfor every write; reusing it would silently stop FTS indexing for ordinary
daemon ingest, not just whale replays). Triggers stay structurally present
in
sqlite_masterat all times; only their bodies short-circuit, soassert_session_fts_exact_sync's trigger-presence check needs no change.write.py's new_bulk_fts_session_guardcontext manager sets the guardrow, does one explicit session-scoped FTS delete (
delete_session_rows_sql)before the caller's block mutation, and one explicit re-insert
(
insert_session_rows_sql) in thefinally, mirroring the samedelete-then-insert shape
_replace_full_session_messages_and_blocksalready uses for a session's own full replace.
_reextract_prefix_tail_dbwraps both dependent-delete branches (
_delete_prefix_message_dependentsand
_delete_all_session_message_dependents) in this guard whenbulk_fts=True.Falsethroughwrite_parsed_session_to_archive->
_resolve_session_graph->_reextract_prefix_tail_db, and througharchive.py'sapply_raw_revision_replay/apply_raw_membership_classification->
_index_parsed_for_retained_raw->_write_parsed_precedence_result(only its
revision_authoritativebranch), andsources/revision_backfill.py'sbackfill_historical_revision_evidence.Only
maintenance/rebuild_index.py's offline rebuild call (an ownedinactive generation, never live daemon ingest) passes
bulk_fts=True;ordinary daemon writes are byte-for-byte unchanged (deferred as an explicit
follow-up on the bead, per its notes).
Deviation from the bead's literal design text: the design named
_replace_full_session_messages_and_blocks/_clear_session_projection_rowsas the guard locus. Source tracing showed those already have their own
separate, always-on, DROP/CREATE-based FTS optimization for a session's own
replace, and are not on the measured whale call path.
_reextract_prefix_tail_db(invoked via_resolve_session_graph, itselfcalled from inside the same
'session-write'-guarded transaction) is theactual site deleting a cascading child session's inherited-prefix blocks, so
the new guard targets that instead. Recorded on the bead.
Version-bump decision: no
INDEX_SCHEMA_VERSIONbump. The trigger DDLchange is additive/inert on an existing archive —
CREATE TRIGGER IF NOT EXISTSkeeps the old (unguarded) trigger body until a rebuild, so the guardrow is simply never consulted on old archives; they behave exactly as before
(no correctness change, only forgone perf until rebuilt).
test_fresh_init_creates_canonical_fts_trigger_set(
test_schema_policy_contracts.py, #3144) compares trigger names via anINSERT/DELETE INTO <fts_table>substring match, not bodies, so it isunaffected by the new
WHENclause.Verification
New test file
tests/unit/storage/test_bulk_fts_prefix_reextract.pyproves:mode-off matches today's per-row-trigger-maintained FTS content; mode-on
produces byte-identical
messages_ftsrows for the same session across boththe partial-tail (
_delete_prefix_message_dependents) and full-tail(
_delete_all_session_message_dependents) branches (the key equivalenceproof); the guard row never leaks past an injected exception (verified via
transaction rollback, not just in-process cleanup);
assert_session_fts_exact_syncpasses after a bulk-mode apply; and an anti-vacuity check (monkeypatching the
explicit bulk re-insert into a no-op) confirms the parity proof actually
fails without it — the equivalence tests are exercising the new code path,
not passing vacuously.
Confirmed via
git diff/checkout/applyrevert-and-rerun (no stash, perworktree policy) that all failures seen in a broader
tests/unit/storage/sweep (5 in
test_live_batch_support.py, 14 acrosstest_retrieval_readiness_laws.py/test_dangling_fts_derived_surfaces.py/
test_embedding_freshness_invariant.py/test_durable_migrations.py/test_index_fast_forward_lifecycle.py/test_delegations_view.py/test_archive_tiers_archive.py) reproduce identically onmasterwithoutthis change — pre-existing drift, not caused here.
Ref polylogue-crd8
🤖 Generated with Claude Code
Summary by CodeRabbit
Performance
Reliability
Tests