Skip to content

fix(storage): FTS trigger commit ordering + SIGKILL safety (#1242) - #1362

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/fts-trigger-sigkill-safety-1242-v2
May 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/fts-trigger-sigkill-safety-1242-v2

Conversation

@Sinity

@Sinity Sinity commented May 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fix two related FTS trigger lifecycle bugs from #1242 (slice C of #817):
the post-write side effects ran AFTER the row commit in a finally
block, and a SIGKILL between trigger-suspend and trigger-restore left
the daemon with no FTS triggers across restarts.

Problem

Bug A — commit ordering. _process_ingest_batch_sync ran
_commit_sync_ingest_side_effects in a finally block, so the
post-commit FTS repair landed in a separate transaction AFTER the row
commit. If the repair raised, data was already durable but the FTS
index drifted silently. The same finally also fired after a
conn.rollback(), silently restoring triggers on top of nothing and
masking the original exception in some cases.

Bug B — SIGKILL during bulk suspend.
suspend_fts_triggers_sync is DROP TRIGGER ..., which is DDL and
auto-commits the drop. A SIGKILL between the drop and the matching
restore_fts_triggers_sync leaves all six FTS triggers absent across
process death, and subsequent writes silently bypass the FTS index.
The daemon startup readiness check rebuilt only when the FTS table was
missing or the docsize shadow was empty — it did not detect this
"triggers gone, stale rows still present" drift signature.

Solution

  • polylogue/pipeline/services/ingest_batch/_core.py:
    • Renamed _commit_ingest_results → _flush_ingest_results; it now
      only flushes pending conversation entries and does not commit.
      The earlier in-function restore_fts_triggers_sync + conn.commit()
      is removed because the gateway path below performs both atomically.
    • In _process_ingest_batch_sync, moved
      _commit_sync_ingest_side_effects out of the finally block and
      into the try body, immediately after _flush_ingest_results.
      This collapses trigger restore + per-conversation FTS repair +
      commit into one effects window through
      ArchiveWriteGateway.commit_write_sync →
      commit_archive_write_effects.
    • On exception, rollback the row writes and then explicitly
      restore_fts_triggers_sync + conn.commit() before re-raising, so
      the database is never left in the SIGKILL-drift state from this
      code path.
  • polylogue/daemon/cli.py:
    • _ensure_fts_startup_readiness now enumerates the six canonical
      FTS triggers and, on detected drift (the SIGKILL-during-suspend
      signature), restores triggers and rebuilds the FTS index in one
      startup-time recovery window. Existing FTS-table-missing and
      empty-while-has-messages branches are preserved.
    • Promoted sqlite3 to a module-level import and replaced the
      inline __import__("contextlib") workaround with the module-level
      contextlib that already exists.
  • tests/unit/storage/test_fts_trigger_lifecycle.py:
    • test_ingest_side_effects_run_in_try_block_not_finally — AST-level
      structural assertion that pins the commit-ordering fix against
      accidental reversion.
    • test_sigkill_mid_bulk_recovery_via_daemon_startup — simulates
      drop + commit + die, runs the daemon startup readiness check in a
      fresh process, asserts trigger restore and FTS rebuild happened.
  • tests/unit/daemon/test_daemon_cli.py:
    • Existing fake-connection tests teach FakeCursor.fetchall() and
      handle the new sqlite_master WHERE type='trigger' probe with all
      six expected triggers present (steady-state path).

Verification

nix develop -c pytest tests/unit/storage/test_fts_trigger_lifecycle.py -v
# 7 passed in 13.54s (incl. 2 new #1242 regression tests)

nix develop -c pytest tests/unit/pipeline -x -q
# 336 passed

nix develop -c pytest tests/unit/storage -x -q
# 745 passed

nix develop -c pytest tests/unit/daemon -x -q
# 691 passed

nix develop -c devtools verify --quick
# total_duration_s: 32.37, exit_code: 0

Closes #1242. Ref #817.

Summary by CodeRabbit

Bug Fixes

  • Enhanced daemon startup to automatically detect and restore Full-Text Search indexes if interrupted during prior operations.
  • Improved database transaction handling during data ingestion to prevent inconsistent states when errors occur.

Tests

  • Added test coverage for Full-Text Search recovery and resilience under interruption scenarios.

Review Change Stack

Two related bugs documented in #1242:

Bug A — commit ordering. _process_ingest_batch_sync ran
_commit_sync_ingest_side_effects in a `finally` block, AFTER the row
commit completed. If the post-commit FTS repair raised, data was
already durable but the FTS index drifted silently. Worse, the finally
also ran after a rollback, silently restoring triggers on top of nothing.
The fix moves the side-effects call into the try block, immediately
after _flush_ingest_results, so trigger restore + FTS repair + commit
land as one effects window through the archive write gateway. On
exception the row writes are rolled back AND triggers are explicitly
restored before re-raising, so the database is never left in the
SIGKILL-style drift state from this code path. Removed the redundant
restore + commit from the old _commit_ingest_results (renamed to
_flush_ingest_results to match its new role).

Bug B — SIGKILL during bulk suspend. A SIGKILL between
suspend_fts_triggers_sync (DDL → auto-commits the drop) and the
matching restore leaves all six FTS triggers absent across process
death; subsequent writes silently bypass the FTS index. The daemon
startup readiness check (_ensure_fts_startup_readiness) previously
only rebuilt when the FTS table was missing or the docsize shadow
was empty; it did not detect the SIGKILL-drift signature, where
triggers are gone but the index still has stale rows from before the
kill. The check now explicitly enumerates the six expected triggers
and, on detected drift, restores them and rebuilds the FTS index in
one startup-time recovery window.

Regression tests in tests/unit/storage/test_fts_trigger_lifecycle.py:

- test_ingest_side_effects_run_in_try_block_not_finally: AST-level
  structural assertion that _process_ingest_batch_sync calls the
  side-effects helper inside the try block and NOT in the finally
  block. Pins the structural fix against accidental reversion.
- test_sigkill_mid_bulk_recovery_via_daemon_startup: simulates the
  SIGKILL-during-suspend signature (drop + commit + die), runs
  _ensure_fts_startup_readiness in a fresh "process", and asserts both
  trigger restore and FTS index rebuild happened.

Closes #1242. Ref #817.
@Sinity
Sinity merged commit c931bca into master May 19, 2026
2 of 5 checks passed
@Sinity
Sinity deleted the feature/fix/fts-trigger-sigkill-safety-1242-v2 branch May 19, 2026 06:58
@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8254d1ce-5caf-43a9-b2e4-5a051334759c

📥 Commits

Reviewing files that changed from the base of the PR and between 13a8a03 and 7042b25.

📒 Files selected for processing (4)
  • polylogue/daemon/cli.py
  • polylogue/pipeline/services/ingest_batch/_core.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/storage/test_fts_trigger_lifecycle.py

📝 Walkthrough

Walkthrough

This PR fixes two related FTS (Full-Text Search) safety bugs: incorrect commit ordering in ingest batch transactions and undetected FTS trigger loss after SIGKILL-style terminations. The ingest batch refactoring moves FTS side effects before connection release to keep them atomic, while daemon startup now detects and restores missing triggers that may have been suspended before an interruption.

Changes

FTS Trigger Safety & Recovery

Layer / File(s) Summary
Ingest batch transaction refactoring
polylogue/pipeline/services/ingest_batch/_core.py
_flush_ingest_results() helper separates row writes from post-ingest side effects; _process_ingest_batch_sync() moved FTS commit and trigger restoration into the try block and added exception handler to restore triggers and commit on failure, keeping writes and FTS effects atomic.
Daemon startup FTS trigger verification
polylogue/daemon/cli.py
_EXPECTED_FTS_TRIGGERS constant and _missing_fts_triggers_sync() helper query SQLite for absent FTS triggers; _ensure_fts_startup_readiness() now detects missing triggers at daemon startup and recovers by restoring them and rebuilding the FTS index.
Unit test stub enhancements for daemon startup
tests/unit/daemon/test_daemon_cli.py
FakeCursor supports both single-row fetchone() and multi-row fetchall() results; FakeConnection.execute() recognizes trigger-list queries and returns the expected set of FTS trigger names so tests can verify trigger detection logic.
Regression tests for FTS trigger lifecycle
tests/unit/storage/test_fts_trigger_lifecycle.py
New test verifies FTS side effects execute in try block not finally; second test simulates SIGKILL by suspending triggers mid-operation, then runs daemon startup and asserts all triggers are restored and FTS index is repopulated.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • Sinity/polylogue#882: Modifies ingest_batch/_core.py to change when FTS triggers are restored relative to transaction commit, directly addressing the same commit-ordering bug.
  • Sinity/polylogue#1206: Extends tests/unit/storage/test_fts_trigger_lifecycle.py with FTS trigger suspension/restoration and SIGKILL recovery invariants, overlapping regression test coverage.
  • Sinity/polylogue#554: Adds trigger-aware FTS readiness and repair in storage/fts/ modules, similar trigger detection and restoration logic for daemon startup.

Poem

🐰 A trigger suspension haunted the store,
Till ingest learned to commit right before,
And daemon, on waking, checks every trigger,
Rebuilds what was lost—the search index grows bigger! ✨

✨ 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/fix/fts-trigger-sigkill-safety-1242-v2

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 and usage tips.

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7042b2522d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/daemon/cli.py Resolved
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 62.F028 / P1: fixed-already at the checked revision: The ingest path now begins its transaction before suspending FTS triggers at polylogue/pipeline/services/ingest_batch/_core.py:2962-2968 and runs FTS side effects before releasing that transaction at lines 3657-3663. A killed current ingest no longer commits the trigger-loss/data-drift window that the old restore-before-detect startup logic mishandled.

Only the rows listed above are dispositioned. Held findings remain open.

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.

fix(storage): FTS trigger commit ordering + SIGKILL safety (#817 slice C)

1 participant