Repository navigation
perf(storage): productize empty-derived-state bulk-build lifecycle - #3165
Conversation
Problem A live whale offline rebuild (bead polylogue-v6i3) stalled for 3+ hours doing per-session FTS/trigram maintenance one session at a time, where an archive-wide messages_fts + blocks_command_trigram delete-all measured 28.7s. 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 via a guard-gated bulk delete+insert, but every session write still did its own action_pairs/delegation_facts refresh and (for full replaces) its own messages_fts delete/suspend/insert/restore dance -- real, avoidable per-session work when a single archive-wide repopulate happens anyway. Solution - write_parsed_session_to_archive gains bulk_build (alongside the existing bulk_fts), threaded through archive.py's _write_parsed_precedence_result / apply_raw_revision_replay / apply_raw_membership_classification, sources/revision_backfill.py, and maintenance/replay.py -- the same call chain #3152 built. When True: the whole-transaction FTS_BULK_SESSION_ WRITE_GUARD row is set once per session write (gating messages_fts AND, newly, blocks_command_trigram trigger bodies for every block mutation in that write, not just the reextract cascade); _replace_full_session_ messages_and_blocks skips its own scoped FTS dance and action_pairs refresh; 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). - 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, not a weakened default. - New bulk repopulate primitives: rebuild_command_trigram_index_sync (storage/fts/fts_lifecycle.py, using the FTS5 'delete-all' command for this external-content table), action_pairs_refresh_all_sql / rebuild_all_action_pairs_sync (set-based, no per-session predicate), and rebuild_all_delegation_facts_sync (populates delegation_refresh_scope with every session id, reusing the existing view/insert SQL unmodified). - maintenance/rebuild_index.py: _clear_bulk_build_derived_stores runs once per RESUMED operation (guarded by a new IndexRebuildTransaction. derived_stores_cleared marker, default False, so it never re-fires on a later page); _repopulate_bulk_build_derived_state runs once at readiness, followed by verify_archive(checks=["fts-parity"]) -- failing the operation loudly on any mismatch before promotion can 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: a per-session action_pairs refresh loop over 4,000 synthetic sessions (6 tool_use/tool_result pairs each) took 64.2s vs 0.3s for the set-based rebuild_all_action_pairs_sync statement -- 216x. The manual pre-promote recovery script is the prototype this productizes; it is not deleted here since it references a specific in-flight generation path from a live incident, but its clear+repopulate action is now this PR's automatic, code-verified lifecycle for all future bulk rebuilds. 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 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 reproduce identically on master without this change -- pre-existing drift, not caused here. Ref polylogue-v6i3 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. |
📝 WalkthroughWalkthroughBulk rebuild replay now defers FTS, trigram, action-pairs, and delegation-facts maintenance until archive-wide repopulation. Resumable transactions persist derived-store clearing state, and rebuild completion verifies FTS parity. ChangesBulk-build rebuild lifecycle
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant RebuildIndex
participant Replay
participant ArchiveStore
participant SQLite
participant Verifier
RebuildIndex->>Replay: start bulk replay
Replay->>ArchiveStore: write sessions with bulk_build
ArchiveStore->>SQLite: defer derived-store refresh
RebuildIndex->>SQLite: repopulate derived stores archive-wide
RebuildIndex->>Verifier: run FTS parity verification
Possibly related PRs
Suggested labels: 🚥 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.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
polylogue/storage/sqlite/archive_tiers/archive.py (1)
1695-1706: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueForward
bulk_ftsandbulk_buildflags to the fallback write.While
bulk_buildandbulk_ftsare currently false for non-authoritative writes by default, explicitly forwarding them to this fallbackwrite_parsed_session_to_archivecall ensures the flags won't be silently swallowed if_write_parsed_precedence_resultis ever invoked with these flags set toTrueduring a non-authoritative operation.♻️ Proposed refactor
stage_timing_prefix=stage_timing_prefix, preacquired_attachment_blobs=preacquired_attachment_blobs, manage_transaction=manage_transaction, + bulk_fts=bulk_fts, + bulk_build=bulk_build, )🤖 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 1695 - 1706, Forward the existing bulk_fts and bulk_build values from _write_parsed_precedence_result into the fallback write_parsed_session_to_archive call, alongside the other write options. Preserve the current behavior while ensuring these flags are not dropped during non-authoritative writes.
🤖 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.
Inline comments:
In `@polylogue/storage/sqlite/action_pairs.py`:
- Around line 72-128: Extract the duplicated CTE/window-function SQL shared by
action_pairs_refresh_sql and action_pairs_refresh_all_sql into a common helper
parameterized by the optional session predicate. Update both functions to use
that helper, preserving the per-session filtering for action_pairs_refresh_sql
and archive-wide behavior for action_pairs_refresh_all_sql without changing
query results.
---
Outside diff comments:
In `@polylogue/storage/sqlite/archive_tiers/archive.py`:
- Around line 1695-1706: Forward the existing bulk_fts and bulk_build values
from _write_parsed_precedence_result into the fallback
write_parsed_session_to_archive call, alongside the other write options.
Preserve the current behavior while ensuring these flags are not dropped during
non-authoritative writes.
🪄 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: 27784dfe-ed82-441c-b021-bcb4be3cc364
📒 Files selected for processing (17)
polylogue/maintenance/rebuild_index.pypolylogue/maintenance/replay.pypolylogue/sources/revision_backfill.pypolylogue/storage/fts/fts_lifecycle.pypolylogue/storage/fts/sql.pypolylogue/storage/index_generation.pypolylogue/storage/sqlite/action_pairs.pypolylogue/storage/sqlite/archive_tiers/archive.pypolylogue/storage/sqlite/archive_tiers/index.pypolylogue/storage/sqlite/archive_tiers/revision_application.pypolylogue/storage/sqlite/archive_tiers/write.pypolylogue/storage/sqlite/delegation_facts.pytests/unit/maintenance/test_rebuild_index_bulk_build.pytests/unit/storage/test_bulk_build_lifecycle.pytests/unit/storage/test_delegation_facts_bulk_rebuild.pytests/unit/storage/test_index_generation.pytests/unit/storage/test_lineage_normalization.py
| def action_pairs_refresh_all_sql() -> str: | ||
| """Set-based, archive-wide equivalent of :func:`action_pairs_refresh_sql`. | ||
|
|
||
| polylogue-v6i3: a bulk-generation-build replay skips the per-session | ||
| ``refresh_action_pairs`` call for every session (see | ||
| ``write_parsed_session_to_archive``'s ``bulk_build`` mode) and instead | ||
| repopulates ``action_pairs`` archive-wide exactly once at readiness. | ||
| Measured (4,000 synthetic sessions, 6 tool_use/tool_result pairs each): | ||
| a per-session ``refresh_action_pairs`` loop took 64.2s vs 0.3s for this | ||
| one set-based statement -- 216x, the same shape of win #3152/#3147 | ||
| already proved for FTS/index commits. The predicate is simply the | ||
| per-session ``WHERE session_id = ?`` removed; the CTE/window-function | ||
| body is otherwise identical to :func:`action_pairs_refresh_sql`. | ||
| """ | ||
| return """ | ||
| INSERT INTO action_pairs ( | ||
| tool_use_block_id, session_id, message_id, tool_id, use_rank, | ||
| tool_name, semantic_type, tool_command, tool_path, | ||
| tool_result_block_id, is_error, exit_code | ||
| ) | ||
| WITH ranked_uses AS ( | ||
| SELECT u.session_id, u.message_id, u.block_id AS tool_use_block_id, | ||
| u.tool_name, u.semantic_type, u.tool_command, u.tool_path, | ||
| u.tool_id, | ||
| ROW_NUMBER() OVER ( | ||
| PARTITION BY u.session_id, u.tool_id | ||
| ORDER BY um.position, um.variant_index, u.position | ||
| ) AS use_rank | ||
| FROM blocks u JOIN messages um ON um.message_id = u.message_id | ||
| WHERE u.block_type = 'tool_use' | ||
| AND u.tool_id IS NOT NULL AND u.tool_id != '' | ||
| ), ranked_results AS ( | ||
| SELECT r.session_id, r.tool_id, r.block_id AS tool_result_block_id, | ||
| r.tool_result_is_error AS is_error, | ||
| r.tool_result_exit_code AS exit_code, | ||
| ROW_NUMBER() OVER ( | ||
| PARTITION BY r.session_id, r.tool_id | ||
| ORDER BY rm.position, rm.variant_index, r.position | ||
| ) AS result_rank | ||
| FROM blocks r JOIN messages rm ON rm.message_id = r.message_id | ||
| WHERE r.block_type = 'tool_result' | ||
| AND r.tool_id IS NOT NULL AND r.tool_id != '' | ||
| ) | ||
| SELECT u.tool_use_block_id, u.session_id, u.message_id, u.tool_id, u.use_rank, | ||
| u.tool_name, u.semantic_type, u.tool_command, u.tool_path, | ||
| r.tool_result_block_id, r.is_error, r.exit_code | ||
| FROM ranked_uses u LEFT JOIN ranked_results r | ||
| ON r.session_id = u.session_id AND r.tool_id = u.tool_id AND r.result_rank = u.use_rank | ||
| UNION ALL | ||
| SELECT u.block_id, u.session_id, u.message_id, u.tool_id, NULL, | ||
| u.tool_name, u.semantic_type, u.tool_command, u.tool_path, | ||
| NULL, NULL, NULL | ||
| FROM blocks u | ||
| WHERE u.block_type = 'tool_use' | ||
| AND (u.tool_id IS NULL OR u.tool_id = '') | ||
| """ | ||
|
|
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Duplicate CTE body between action_pairs_refresh_sql and action_pairs_refresh_all_sql.
The two functions carry an almost-identical ~50-line CTE/window-function body, differing only in whether AND u.session_id = {session_expr} / AND r.session_id = {session_expr} predicates are present. The docstring itself flags this: "the CTE/window-function body is otherwise identical to :func:action_pairs_refresh_sql." Two independently-maintained copies of correctness-critical SQL is a real drift risk — a future column/join change applied to one and missed in the other would silently desync bulk-rebuilt archives from trickle-built ones (exactly the failure mode the parity tests exist to catch, but only after the fact).
Extracting a shared body parameterized by the use/result predicates would remove the duplication without changing behavior.
♻️ Proposed refactor to share the CTE body
+def _action_pairs_refresh_body(*, use_filter: str, result_filter: str) -> str:
+ return f"""
+ INSERT INTO action_pairs (
+ tool_use_block_id, session_id, message_id, tool_id, use_rank,
+ tool_name, semantic_type, tool_command, tool_path,
+ tool_result_block_id, is_error, exit_code
+ )
+ WITH ranked_uses AS (
+ SELECT u.session_id, u.message_id, u.block_id AS tool_use_block_id,
+ u.tool_name, u.semantic_type, u.tool_command, u.tool_path,
+ u.tool_id,
+ ROW_NUMBER() OVER (
+ PARTITION BY u.session_id, u.tool_id
+ ORDER BY um.position, um.variant_index, u.position
+ ) AS use_rank
+ FROM blocks u JOIN messages um ON um.message_id = u.message_id
+ WHERE u.block_type = 'tool_use' {use_filter}
+ AND u.tool_id IS NOT NULL AND u.tool_id != ''
+ ), ranked_results AS (
+ SELECT r.session_id, r.tool_id, r.block_id AS tool_result_block_id,
+ r.tool_result_is_error AS is_error,
+ r.tool_result_exit_code AS exit_code,
+ ROW_NUMBER() OVER (
+ PARTITION BY r.session_id, r.tool_id
+ ORDER BY rm.position, rm.variant_index, r.position
+ ) AS result_rank
+ FROM blocks r JOIN messages rm ON rm.message_id = r.message_id
+ WHERE r.block_type = 'tool_result' {result_filter}
+ AND r.tool_id IS NOT NULL AND r.tool_id != ''
+ )
+ SELECT u.tool_use_block_id, u.session_id, u.message_id, u.tool_id, u.use_rank,
+ u.tool_name, u.semantic_type, u.tool_command, u.tool_path,
+ r.tool_result_block_id, r.is_error, r.exit_code
+ FROM ranked_uses u LEFT JOIN ranked_results r
+ ON r.session_id = u.session_id AND r.tool_id = u.tool_id AND r.result_rank = u.use_rank
+ UNION ALL
+ SELECT u.block_id, u.session_id, u.message_id, u.tool_id, NULL,
+ u.tool_name, u.semantic_type, u.tool_command, u.tool_path,
+ NULL, NULL, NULL
+ FROM blocks u
+ WHERE u.block_type = 'tool_use' {use_filter}
+ AND (u.tool_id IS NULL OR u.tool_id = '')
+ """
+
+
def action_pairs_refresh_sql(session_expr: str) -> str:
"""..."""
- return f"""...full body with session_expr inline..."""
+ return _action_pairs_refresh_body(
+ use_filter=f"AND u.session_id = {session_expr}",
+ result_filter=f"AND r.session_id = {session_expr}",
+ )And action_pairs_refresh_all_sql becomes:
def action_pairs_refresh_all_sql() -> str:
"""..."""
- return """...full body with no session predicate..."""
+ return _action_pairs_refresh_body(use_filter="", result_filter="")📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def action_pairs_refresh_all_sql() -> str: | |
| """Set-based, archive-wide equivalent of :func:`action_pairs_refresh_sql`. | |
| polylogue-v6i3: a bulk-generation-build replay skips the per-session | |
| ``refresh_action_pairs`` call for every session (see | |
| ``write_parsed_session_to_archive``'s ``bulk_build`` mode) and instead | |
| repopulates ``action_pairs`` archive-wide exactly once at readiness. | |
| Measured (4,000 synthetic sessions, 6 tool_use/tool_result pairs each): | |
| a per-session ``refresh_action_pairs`` loop took 64.2s vs 0.3s for this | |
| one set-based statement -- 216x, the same shape of win #3152/#3147 | |
| already proved for FTS/index commits. The predicate is simply the | |
| per-session ``WHERE session_id = ?`` removed; the CTE/window-function | |
| body is otherwise identical to :func:`action_pairs_refresh_sql`. | |
| """ | |
| return """ | |
| INSERT INTO action_pairs ( | |
| tool_use_block_id, session_id, message_id, tool_id, use_rank, | |
| tool_name, semantic_type, tool_command, tool_path, | |
| tool_result_block_id, is_error, exit_code | |
| ) | |
| WITH ranked_uses AS ( | |
| SELECT u.session_id, u.message_id, u.block_id AS tool_use_block_id, | |
| u.tool_name, u.semantic_type, u.tool_command, u.tool_path, | |
| u.tool_id, | |
| ROW_NUMBER() OVER ( | |
| PARTITION BY u.session_id, u.tool_id | |
| ORDER BY um.position, um.variant_index, u.position | |
| ) AS use_rank | |
| FROM blocks u JOIN messages um ON um.message_id = u.message_id | |
| WHERE u.block_type = 'tool_use' | |
| AND u.tool_id IS NOT NULL AND u.tool_id != '' | |
| ), ranked_results AS ( | |
| SELECT r.session_id, r.tool_id, r.block_id AS tool_result_block_id, | |
| r.tool_result_is_error AS is_error, | |
| r.tool_result_exit_code AS exit_code, | |
| ROW_NUMBER() OVER ( | |
| PARTITION BY r.session_id, r.tool_id | |
| ORDER BY rm.position, rm.variant_index, r.position | |
| ) AS result_rank | |
| FROM blocks r JOIN messages rm ON rm.message_id = r.message_id | |
| WHERE r.block_type = 'tool_result' | |
| AND r.tool_id IS NOT NULL AND r.tool_id != '' | |
| ) | |
| SELECT u.tool_use_block_id, u.session_id, u.message_id, u.tool_id, u.use_rank, | |
| u.tool_name, u.semantic_type, u.tool_command, u.tool_path, | |
| r.tool_result_block_id, r.is_error, r.exit_code | |
| FROM ranked_uses u LEFT JOIN ranked_results r | |
| ON r.session_id = u.session_id AND r.tool_id = u.tool_id AND r.result_rank = u.use_rank | |
| UNION ALL | |
| SELECT u.block_id, u.session_id, u.message_id, u.tool_id, NULL, | |
| u.tool_name, u.semantic_type, u.tool_command, u.tool_path, | |
| NULL, NULL, NULL | |
| FROM blocks u | |
| WHERE u.block_type = 'tool_use' | |
| AND (u.tool_id IS NULL OR u.tool_id = '') | |
| """ | |
| def action_pairs_refresh_all_sql() -> str: | |
| """Set-based, archive-wide equivalent of :func:`action_pairs_refresh_sql`. | |
| polylogue-v6i3: a bulk-generation-build replay skips the per-session | |
| ``refresh_action_pairs`` call for every session (see | |
| ``write_parsed_session_to_archive``'s ``bulk_build`` mode) and instead | |
| repopulates ``action_pairs`` archive-wide exactly once at readiness. | |
| Measured (4,000 synthetic sessions, 6 tool_use/tool_result pairs each): | |
| a per-session ``refresh_action_pairs`` loop took 64.2s vs 0.3s for this | |
| one set-based statement -- 216x, the same shape of win `#3152/`#3147 | |
| already proved for FTS/index commits. The predicate is simply the | |
| per-session ``WHERE session_id = ?`` removed; the CTE/window-function | |
| body is otherwise identical to :func:`action_pairs_refresh_sql`. | |
| """ | |
| return _action_pairs_refresh_body(use_filter="", result_filter="") |
🤖 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/action_pairs.py` around lines 72 - 128, Extract the
duplicated CTE/window-function SQL shared by action_pairs_refresh_sql and
action_pairs_refresh_all_sql into a common helper parameterized by the optional
session predicate. Update both functions to use that helper, preserving the
per-session filtering for action_pairs_refresh_sql and archive-wide behavior for
action_pairs_refresh_all_sql without changing query results.
## Summary Extends `polylogue demo seed` to populate all eight wired origins instead of five, and refreshes the generated demo-corpus evidence that depends on the corpus contents. ## Problem `polylogue demo seed` only populated `claude-code-session`, `codex-session`, `chatgpt-export`, `claude-ai-export`, and `aistudio-drive`. The `gemini-cli-session`, `antigravity-session`, and `hermes-session` parsers were verified only by unit fixtures, never by the public demo archive — `polylogue --origin gemini-cli-session read --all` (and the other two) returned zero rows against a fresh demo seed, and the README carried a caveat about this gap (owned by a separate lane, not touched here). Operator: "why wouldn't we just generate stuff for all the origins?" ## Solution - `polylogue/demo/seed.py`: write hand-authored, realistic-but-synthetic fixture documents for each of the three origins, routed through the real dispatch/parse path — the same mechanism the existing `claude-ai-temporary`, `browser-capture`, and `agent-lineage-matrix` fixture families already use (not hand-inserted rows): - `gemini-cli-session`: a local-agent JSON document (`sources/parsers/local_agent.py:parse_gemini_cli`) with a tool call, a recorded thought, and per-message usage. - `antigravity-session`: the Antigravity language-server markdown-export shape (`sources/parsers/antigravity.py:parse_markdown_export`), the real ingestion route real Antigravity exports use. - `hermes-session`: the Hermes exported-snapshot JSON shape (`sources/parsers/local_agent.py:parse_hermes`, distinct from the live `state.db` acquisition path) with a system prompt, a tool call, and its tool result. - `polylogue/scenarios/corpus.py`: new `DEMO_GEMINI_CLI_SESSION_ID`/`DEMO_ANTIGRAVITY_SESSION_ID`/`DEMO_HERMES_SESSION_ID`, extended `DEMO_SESSION_IDS`, and three new `DemoCorpusFamily` entries (`synthetic=False`, matching the existing hand-authored pattern) documenting the fixtures. - `polylogue/demo/constructs.py`: three new declared constructs (`gemini_cli_origin_rows`, `antigravity_origin_rows`, `hermes_origin_rows`) so `polylogue demo verify` positively asserts each new origin resolved a session, not just that totals grew. - `polylogue/demo/tour.py`: the "archive facets" tour narration now computes the origin count from the seeded session ids instead of a hardcoded "five" — it can't silently go stale again. - Regenerated `docs/plans/demo-corpus-construct-audit.md` (`devtools render demo-corpus-datasheet`) and `docs/examples/demo-tour/*` (`polylogue demo tour --out-dir polylogue-demo-tour --force`, per `devtools lab policy demo-tour-freshness`'s own remediation instructions) since both are committed snapshots of a fresh seed/tour run and the new sessions change their counts. - `docs/demos.md`, `docs/proof-artifacts.md`: replaced the hand-written "five origins" claim/list with current reality (`README.md` is intentionally untouched — a separate lane owns its origin-coverage caveat). - `tests/unit/scenarios/test_corpus.py`: updated the pinned `DEMO_SESSION_IDS`/`DEMO_CORPUS_FAMILIES` assertions for the three new families/ids. ## Verification - Fresh scratch-root cold seed (`POLYLOGUE_ARCHIVE_ROOT=/realm/tmp/... python3 -m polylogue.cli demo seed`, then `--origin gemini-cli-session read --all` / `antigravity-session` / `hermes-session`): each origin returns rows (2, 2, and 5 messages respectively). - `python3 -m polylogue.cli demo verify --require-overlays`: `Demo archive verification: ok` — 19 sessions, 71 messages, 8 origins, 0 problems. - `devtools test tests/unit/sources tests/unit/demo tests/unit/scenarios`: 1907 passed. 7 pre-existing failures in `test_live_batch_support.py`/`test_live_cursor_persistence.py` (a `bulk_build` `TypeError` from the unrelated, already-merged #3165) — none of those files are touched by this change. - `devtools render all --check`: no drift (`OK: site sources render and generated local links resolve.`). - `devtools lab policy demo-tour-freshness`: "fresh tour output matches committed docs/examples/demo-tour/ (masked)". - `devtools lab policy docs-drift`: "zero unhandled drift across the reference-docs sweep." - `devtools verify --quick`: all 16 steps `ok` (also re-ran automatically via the pre-push hook). ## Acceptance criteria (Ref polylogue-b036) - `--origin gemini-cli-session read --all` (and antigravity-session, hermes-session) each return rows against a fresh scratch-root seed: **satisfied**. - `polylogue demo verify` passes and covers the new origins: **satisfied** (three new declared constructs + the existing session-id/count assertions). - Existing demo tests still green: **satisfied** (`tests/unit/demo/*`, `tests/unit/cli/test_demo_command.py`, `tests/unit/scenarios/test_corpus.py` all pass). - README no longer needs the coverage caveat: **deferred** — explicitly out of scope for this PR (a separate lane owns README). Ref polylogue-b036 Co-Authored-By: Claude <[email protected]>
) Ref polylogue-lvz6 **Summary**: test-only fix — the `_lock_first_index_persistence` monkeypatch stub mirrors `_write_parsed_precedence_result` but was not updated when #3165 added the `bulk_build` kwarg. **Problem**: on clean master, both lock-retry tests in `tests/unit/sources/test_live_cursor_persistence.py` fail — the live watcher swallows the stub TypeError as "ingest failed". Surfaced while verifying a lane report; the heavy suite runs post-merge only, so per-PR CI never caught it. **Solution**: the stub accepts and forwards `bulk_build`. **Verification**: `devtools test tests/unit/sources/test_live_cursor_persistence.py tests/unit/sources/test_live_batch_support.py` → the 2 cursor-persistence failures clear (66 passed across the pair); the 5 remaining `test_live_batch_support` failures are unrelated pre-existing drift, being triaged under polylogue-lvz6.
Summary
Extends the offline rebuild path (
maintenance/rebuild_index.py) so a bulkgeneration build keeps
messages_fts,blocks_command_trigram,action_pairs, anddelegation_factsempty for every session throughoutreplay, 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_trigramdelete-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 bothsurfaces 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_factsrefresh, and a full-session replace still did its own
messages_ftsdelete/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_archivegainsbulk_build(alongside theexisting
bulk_fts), threaded through the same call chain perf(storage): guard-gate messages_fts triggers for prefix-tail bulk delete #3152 built:archive.py's_write_parsed_precedence_result/apply_raw_revision_replay/apply_raw_membership_classification,sources/revision_backfill.py,maintenance/replay.py. WhenTrue:FTS_BULK_SESSION_WRITE_GUARDrow is set once persession write, gating both
messages_ftsand (newly)blocks_command_trigramtrigger bodies for every block mutation in thatwrite — not just the prefix-reextract cascade perf(storage): guard-gate messages_fts triggers for prefix-tail bulk delete #3152 already guarded.
_replace_full_session_messages_and_blocksskips its own scoped FTSdance and
action_pairsrefresh entirely.action_pairsrefresh.refresh_delegation_facts_for_sessionis skipped._bulk_fts_session_guardbecomes a no-op (the outer guard already coversit; no redundant per-session delete+insert).
assert_session_fts_exact_syncgainsbulk_build=False: whenTrueitskips 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.
rebuild_command_trigram_index_sync(storage/fts/fts_lifecycle.py) —uses the FTS5
'delete-all'command required for this external-contenttable, then one bulk insert from
blocks.action_pairs_refresh_all_sql/rebuild_all_action_pairs_sync— aset-based, archive-wide variant with the per-session predicate simply
removed.
rebuild_all_delegation_facts_sync— populatesdelegation_refresh_scopewith every session id, reusing the existing view/insert SQL unmodified
(that table already scopes
delegation_facts_sourceby an allow-list,not an inline predicate, so no new SQL shape was needed).
maintenance/rebuild_index.pyorchestrates the lifecycle:_clear_bulk_build_derived_storesruns once per resumed operation,guarded by a new
IndexRebuildTransaction.derived_stores_clearedmarker(default
False, persisted throughcheckpoint_transaction) so it neverre-fires on a later page of the same operation. A fresh generation starts
empty by construction and never needs this.
_repopulate_bulk_build_derived_stateruns once at readiness (before_archive_readiness_status), followed byverify_archive(checks=["fts-parity"])— failing the operation loudly onany mismatch before promotion can ever see it.
blocks_command_trigram's three triggers gain the same guard-rowWHENclause
messages_fts's triggers already had. NoINDEX_SCHEMA_VERSIONbump: additive/inert via
CREATE TRIGGER IF NOT EXISTS, matching perf(storage): guard-gate messages_fts triggers for prefix-tail bulk delete #3152'sown precedent for this exact situation.
Measured (
action_pairsper-session vs set-based, 4,000 syntheticsessions × 6 tool_use/tool_result pairs): a per-session
refresh_action_pairsloop 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
New tests prove:
bulk_build=Truewrites leave all four derived surfacesempty 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_pairscontentto trickle-mode population of the same corpus (including a prefix-sharing
lineage cascade exercising
_bulk_fts_session_guard's bulk-build no-opbranch);
rebuild_all_delegation_facts_syncmatches per-sessionrefresh_delegation_facts_for_sessionacross resolved/ambiguous/edge-onlymapping states; the whole-transaction guard row never leaks past an
exception;
_clear_bulk_build_derived_storesonly touches the two namedsurfaces (not
action_pairs/blocks) and is idempotent on an already-emptytable;
_repopulate_bulk_build_derived_statereaches exact archive-wideparity via
verify_archive'sfts-paritycheck; 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/applyrevert-and-rerun (no stash, perworktree policy) that 5 pre-existing failures in
test_live_batch_support.pyand 3 in
test_delegations_view.py(an unrelatedPRAGMA user_tierattached-database gap in the query-transaction test fixture) reproduce
identically on
masterwithout this change — pre-existing drift, not causedhere.
Ref polylogue-v6i3
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests