Skip to content

test(storage): reconcile canonical FTS trigger set with fresh-init reality - #3144

Merged
Sinity merged 1 commit into
masterfrom
feature/test/reconcile-canonical-fts-trigger-set
Jul 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/test/reconcile-canonical-fts-trigger-set

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes tests/unit/storage/test_schema_policy_contracts.py::test_fresh_init_creates_canonical_fts_trigger_set, which failed on master by asserting exact equality between a hand-maintained trigger-name set and the full sqlite_master trigger inventory of a fresh index.db.

Problem

_CANONICAL_FTS_TRIGGERS lists 12 triggers backing the four FTS5 virtual tables (messages_fts, session_work_events_fts, threads_fts, blocks_command_trigram). The test compared this set for exact equality against SELECT name FROM sqlite_master WHERE type='trigger' — i.e. literally every trigger fresh init creates.

Two trigger families landed since the blocks_command_trigram (ohbx) addition and were never reconciled with this test:

  • query_unit_frame_* (21 triggers) — bump a query_unit_frame_state epoch counter on writes to sessions/messages/blocks/session_links/session_profiles/session_tags/delegation_facts.
  • blocks_action_pairs_* / session_links_delegation_facts_* / session_profiles_delegation_facts_* (7 triggers) — materialize the plain action_pairs and delegation_facts tables.

Neither family writes into an FTS5 virtual table, so the test failed with 28 unexpected "extra" trigger names. Per-PR CI skips the heavy test suite, so this landed silently (confirmed via polylogue-dyno, filed after a stash-and-rerun while landing an unrelated bead).

Solution

Rather than hand-listing every non-FTS trigger to exclude (which would rot again at the next unrelated trigger addition), the test now:

  1. Discovers the actual FTS5 virtual tables fresh init creates (SELECT name FROM sqlite_master WHERE type='table' AND sql LIKE '%USING fts5%').
  2. Keeps only triggers whose body writes into one of those tables (INSERT INTO <table>, or DELETE FROM <table> for the three _ad triggers that don't use the FTS5 external-content special-delete form).
  3. Asserts exact equality between that structurally filtered set and _CANONICAL_FTS_TRIGGERS, unchanged (not weakened to a subset/superset check).

This reading is consistent with the existing ohbx comment on _CANONICAL_FTS_TRIGGERS: blocks_command_trigram's triggers belong because they are genuinely FTS-backing (even though not tracked by fts_trigger_state), not because the set is meant to enumerate "every trigger fresh init happens to create." query_unit_frame_* and the delegation_facts family are legitimately out of scope for an FTS trigger inventory.

Only tests/unit/storage/test_schema_policy_contracts.py changed — no production DDL touched.

Verification

  • devtools test tests/unit/storage/test_schema_policy_contracts.py — 14 passed (was 1 failed, 13 passed before the fix).
  • devtools verify --quick — exit_code: 0.
  • Pre-push quick verification baseline (ruff format/check, mypy, render all, topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/docs-coverage/test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly) — all ok.

Ref polylogue-dyno

Co-Authored-By: Claude [email protected]

…ality

Problem: test_fresh_init_creates_canonical_fts_trigger_set asserted exact
equality between _CANONICAL_FTS_TRIGGERS and every trigger sqlite_master
reports for a fresh index.db. Fresh init now also creates two unrelated
trigger families that predate this bead but were never reconciled here:
query_unit_frame_* (21 triggers bumping the query_unit_frame_state epoch
counter on writes to sessions/messages/blocks/session_links/
session_profiles/session_tags/delegation_facts) and the
blocks_action_pairs_*/session_links_delegation_facts_*/
session_profiles_delegation_facts_* family (materializing the plain
action_pairs and delegation_facts tables). Neither family backs an FTS5
virtual table, so the test failed with 28 "extra" triggers.

Solution: rather than hand-listing every non-FTS trigger to exclude (which
would just rot again at the next unrelated trigger addition), the test now
discovers the actual FTS5 virtual tables fresh init creates
(messages_fts, threads_fts, session_work_events_fts,
blocks_command_trigram -- confirmed via `CREATE VIRTUAL TABLE ... USING
fts5` in archive_tiers/index.py) and keeps only triggers whose body writes
into one of them (INSERT INTO or, for messages_fts_ad/threads_fts_ad/
session_work_events_fts_ad which don't use the fts5 external-content
special-delete form, DELETE FROM). This is the reading consistent with the
existing ohbx comment on _CANONICAL_FTS_TRIGGERS: blocks_command_trigram's
triggers belong because they are genuinely FTS-backing, not because the
set is meant to be "every trigger fresh init happens to create". Kept the
assertion as exact equality (not weakened to a subset/superset check) --
only the trigger-discovery query changed.

Verification:
- devtools test tests/unit/storage/test_schema_policy_contracts.py -- 14
  passed (was 1 failed, 13 passed).
- devtools verify --quick -- exit 0.

Ref polylogue-dyno

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

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 47 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f7c5cf26-7f6a-42cc-ba45-5ea840ea6257

📥 Commits

Reviewing files that changed from the base of the PR and between 5effee3 and 26c835c.

📒 Files selected for processing (1)
  • tests/unit/storage/test_schema_policy_contracts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/test/reconcile-canonical-fts-trigger-set

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 fc85e2a into master Jul 19, 2026
3 checks passed
@Sinity
Sinity deleted the feature/test/reconcile-canonical-fts-trigger-set branch July 19, 2026 03:17
Sinity added a commit that referenced this pull request Jul 19, 2026
…delete (#3152)

## 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_fts`
trigger 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_db` deletes that
prefix's
blocks one row at a time once the parent session is known, and
`messages_fts_ad` fires per deleted row (contentless-FTS posting-list
maintenance) 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 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 in this PR.

## 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
unconditionally
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 (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_rows`
as 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`,
itself
called from inside the same `'session-write'`-guarded transaction) is
the
actual 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_VERSION` bump. The trigger
DDL
change is additive/inert on an existing archive — `CREATE TRIGGER IF NOT
EXISTS` keeps the old (unguarded) trigger body until a rebuild, so the
guard
row 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
an
`INSERT/DELETE INTO <fts_table>` substring match, not bodies, so it is
unaffected by the new `WHEN` clause.

## 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
```

New test file `tests/unit/storage/test_bulk_fts_prefix_reextract.py`
proves:
mode-off matches today's per-row-trigger-maintained FTS content; mode-on
produces byte-identical `messages_fts` rows for the same session across
both
the partial-tail (`_delete_prefix_message_dependents`) and full-tail
(`_delete_all_session_message_dependents`) branches (the key equivalence
proof); the guard row never leaks past an injected exception (verified
via
transaction rollback, not just in-process cleanup);
`assert_session_fts_exact_sync`
passes 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`/`apply` revert-and-rerun (no stash,
per
worktree policy) that all failures seen in a broader
`tests/unit/storage/`
sweep (5 in `test_live_batch_support.py`, 14 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 on `master`
without
this change — pre-existing drift, not caused here.

Ref polylogue-crd8

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Performance**
* Improved offline index rebuilds by using a bulk search-index refresh
process, reducing expensive per-record maintenance.
  * Preserved search results while improving rebuild efficiency.

* **Reliability**
* Added safeguards to ensure temporary bulk-refresh state is cleared,
including when an operation fails.

* **Tests**
* Added coverage for bulk refresh accuracy, rollback behavior, and
lineage-related scenarios.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude <[email protected]>
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