Skip to content

perf(storage): productize empty-derived-state bulk-build lifecycle - #3165

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/bulk-build-empty-derived-state
Jul 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/bulk-build-empty-derived-state

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026 •

Copy link
Copy Markdown
Owner

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 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. 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 perf(storage): guard-gate messages_fts triggers for prefix-tail bulk delete #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 perf(storage): guard-gate messages_fts triggers for prefix-tail bulk delete #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

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.

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]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Bulk 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.

Changes

Bulk-build rebuild lifecycle

Layer / File(s) Summary
Rebuild orchestration and resume state
polylogue/maintenance/rebuild_index.py, polylogue/maintenance/replay.py, polylogue/sources/revision_backfill.py, polylogue/storage/index_generation.py
Replay accepts and propagates bulk_build; resumable rebuilds clear derived stores once, repopulate them archive-wide, and fail on blocking parity results.
Bulk-write propagation and guards
polylogue/storage/sqlite/archive_tiers/archive.py, polylogue/storage/sqlite/archive_tiers/write.py, polylogue/storage/sqlite/archive_tiers/index.py, polylogue/storage/sqlite/archive_tiers/revision_application.py
Bulk mode suppresses per-session derived refreshes, uses a transaction guard, gates trigram triggers, and relaxes per-session parity checks while preserving trigger validation.
Archive-wide derived-store rebuilds
polylogue/storage/fts/*, polylogue/storage/sqlite/action_pairs.py, polylogue/storage/sqlite/delegation_facts.py
Adds bulk rebuild operations for trigram FTS, action pairs, and delegation facts.
Lifecycle validation
tests/unit/maintenance/test_rebuild_index_bulk_build.py, tests/unit/storage/test_bulk_build_lifecycle.py, tests/unit/storage/test_delegation_facts_bulk_rebuild.py, tests/unit/storage/test_index_generation.py, tests/unit/storage/test_lineage_normalization.py
Tests cover deferred population, exact parity, idempotent clearing, guard cleanup, delegation scope cleanup, persisted transaction state, and updated failure hooks.

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
Loading

Possibly related PRs

Suggested labels: area:storage

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.21% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the bulk-build lifecycle change.
Description check ✅ Passed The description includes the required Summary, Problem, Solution, and Verification sections with concrete details.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/bulk-build-empty-derived-state

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit 573a2d7 into master Jul 19, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the feature/perf/bulk-build-empty-derived-state branch July 19, 2026 18:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 value

Forward bulk_fts and bulk_build flags to the fallback write.

While bulk_build and bulk_fts are currently false for non-authoritative writes by default, explicitly forwarding them to this fallback write_parsed_session_to_archive call ensures the flags won't be silently swallowed if _write_parsed_precedence_result is ever invoked with these flags set to True during 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

📥 Commits

Reviewing files that changed from the base of the PR and between aa45aa5 and f84bb01.

📒 Files selected for processing (17)
  • polylogue/maintenance/rebuild_index.py
  • polylogue/maintenance/replay.py
  • polylogue/sources/revision_backfill.py
  • polylogue/storage/fts/fts_lifecycle.py
  • polylogue/storage/fts/sql.py
  • polylogue/storage/index_generation.py
  • polylogue/storage/sqlite/action_pairs.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/index.py
  • polylogue/storage/sqlite/archive_tiers/revision_application.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • polylogue/storage/sqlite/delegation_facts.py
  • tests/unit/maintenance/test_rebuild_index_bulk_build.py
  • tests/unit/storage/test_bulk_build_lifecycle.py
  • tests/unit/storage/test_delegation_facts_bulk_rebuild.py
  • tests/unit/storage/test_index_generation.py
  • tests/unit/storage/test_lineage_normalization.py

Comment on lines +72 to +128
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 = '')
"""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Suggested change
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.

Sinity added a commit that referenced this pull request Jul 19, 2026
Sinity added a commit that referenced this pull request Jul 19, 2026
## 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]>
Sinity added a commit that referenced this pull request Jul 19, 2026
)

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant