Skip to content

fix(daemon): restore all active FTS triggers - #1455

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/daemon-fts-health-locks
May 23, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/daemon-fts-health-locks

Conversation

@Sinity

@Sinity Sinity commented May 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Restore and monitor the full active FTS trigger set during daemon startup, recovery, health checks, metrics, and workload probes. The patch also makes cursor-lag sample writes best-effort under SQLite write contention so observability does not add more pressure during catch-up.

Problem

Live deployment showed fts_readiness errors for session_work_events_fts and work_threads_fts missing triggers while the daemon was also hitting SQLite lock contention. The lifecycle module knew about twelve trigger names, but restore paths recreated only the message and action-event triggers. A catch-up recovery window could therefore leave insight search surfaces stale even after the daemon believed trigger recovery had run.

This is related to #1447 but does not close it: WAL growth, bounded checkpoints, and large-session memory release remain open there.

Solution

  • Export the canonical FTS trigger inventory from polylogue.storage.fts.fts_lifecycle.
  • Recreate triggers for every active FTS surface: messages, action events, session work events, and work threads.
  • Rebuild the insight FTS tables during full FTS recovery so repair covers the indexed surfaces it now owns.
  • Teach daemon startup, health, metrics, and devtools daemon-workload-probe to use the same inventory.
  • Scope startup/health checks to active surfaces so partial/minimal databases do not report irrelevant missing triggers.
  • Make cursor-lag sample and GC writes return immediately when SQLite is locked.

Ref #1447

Verification

  • pytest tests/unit/storage/test_fts_trigger_lifecycle.py tests/unit/daemon/test_cursor_lag_integration.py tests/unit/daemon/test_fts_trigger_drift.py tests/unit/daemon/test_metrics_endpoint.py tests/unit/devtools/test_daemon_workload_probe.py -q → 60 passed
  • python -m mypy polylogue/storage/fts/fts_lifecycle.py polylogue/daemon/cursor_lag_baseline.py polylogue/daemon/health.py polylogue/daemon/metrics.py polylogue/daemon/cli.py devtools/daemon_workload_probe.py tests/unit/storage/test_fts_trigger_lifecycle.py tests/unit/daemon/test_cursor_lag_integration.py tests/unit/daemon/test_fts_trigger_drift.py → Success: no issues found in 9 source files
  • devtools verify --quick → exit 0
  • pre-push devtools verify --quick → exit 0

Summary by CodeRabbit

Release Notes

  • New Features

    • Extended full-text search capability to cover session work events and work threads in addition to existing message and action event search surfaces.
  • Bug Fixes

    • Improved database lock handling in health monitoring to prevent blocking operations during concurrent database access.
  • Improvements

    • Enhanced search health checks with more reliable trigger monitoring and drift detection across all search surfaces.

Review Change Stack

Problem: live catch-up can suspend FTS triggers across every active search surface, but daemon recovery and health only treated messages/action-events as canonical. That left insight FTS triggers missing after recovery windows and kept readiness noisy while the archive was already under write pressure. Cursor-lag history writes also used the normal write timeout for observability-only samples, adding lock contention during ingest.

What changed: centralize the FTS trigger inventory from the lifecycle module, recreate and monitor archive plus insight triggers only for active surfaces, rebuild insight FTS tables during full FTS recovery, and make cursor-lag sample/GC writes skip cleanly when SQLite is already locked.

Verification: pytest tests/unit/storage/test_fts_trigger_lifecycle.py tests/unit/daemon/test_cursor_lag_integration.py tests/unit/daemon/test_fts_trigger_drift.py tests/unit/daemon/test_metrics_endpoint.py tests/unit/devtools/test_daemon_workload_probe.py -q; python -m mypy polylogue/storage/fts/fts_lifecycle.py polylogue/daemon/cursor_lag_baseline.py polylogue/daemon/health.py polylogue/daemon/metrics.py polylogue/daemon/cli.py devtools/daemon_workload_probe.py tests/unit/storage/test_fts_trigger_lifecycle.py tests/unit/daemon/test_cursor_lag_integration.py tests/unit/daemon/test_fts_trigger_drift.py; devtools verify --quick.

Ref #1447
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 43ae5a2f-267d-4abb-b085-43262d57cc95

📥 Commits

Reviewing files that changed from the base of the PR and between 38a268e and 8ffbb36.

📒 Files selected for processing (9)
  • devtools/daemon_workload_probe.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/cursor_lag_baseline.py
  • polylogue/daemon/health.py
  • polylogue/daemon/metrics.py
  • polylogue/storage/fts/fts_lifecycle.py
  • tests/unit/daemon/test_cursor_lag_integration.py
  • tests/unit/daemon/test_fts_trigger_drift.py
  • tests/unit/storage/test_fts_trigger_lifecycle.py

📝 Walkthrough

Walkthrough

This PR expands the FTS (Full Text Search) trigger set from 6 to 12 canonical triggers, introduces a shared trigger names constant across daemon components, makes trigger lifecycle operations conditional on table existence, and adds database-lock resilience to cursor lag sampling.

Changes

FTS Trigger Canonicalization and Conditional Lifecycle

Layer / File(s) Summary
Define canonical FTS trigger names and expanded DDL
polylogue/storage/fts/fts_lifecycle.py
Introduces FTS_TRIGGER_NAMES constant exporting the full set of 12 canonical triggers for messages, action_events, session_work_events, and work_threads surfaces, and includes new trigger DDL for the two newly supported surfaces.
Conditional trigger lifecycle—restore and create only for existing surfaces
polylogue/storage/fts/fts_lifecycle.py
Trigger restoration and creation now apply DDL conditionally based on whether base and FTS tables exist; new helpers detect table presence and compute applicable DDL for sync and async paths.
FTS rebuild with new surfaces and invariant snapshot
polylogue/storage/fts/fts_lifecycle.py
rebuild_fts_index_sync expands to rebuild data for session_work_events_fts and work_threads_fts, and records an invariant snapshot after rebuild steps.
Daemon health—dynamic FTS trigger drift detection
polylogue/daemon/health.py
Health check now imports canonical trigger names and filters to only "active" triggers based on FTS table presence; missing-trigger detection and alert messaging report against the active count rather than the full canonical set.
Daemon CLI—dynamic missing trigger detection on startup
polylogue/daemon/cli.py
CLI startup missing-trigger detection imports canonical names and adds _active_fts_triggers_sync helper to compute expected triggers only for surfaces whose base tables exist.
Daemon metrics and probe—canonical trigger sourcing
polylogue/daemon/metrics.py, devtools/daemon_workload_probe.py
Both metrics and workload probe import FTS_TRIGGER_NAMES instead of maintaining local hardcoded copies, allowing all daemon components to share a single canonical set.
Tests—FTS trigger drift validation expanded to 12 triggers
tests/unit/daemon/test_fts_trigger_drift.py
Test fixtures and expectations expand from 6 to 12 expected triggers; new SQL fixtures create session_work_events and work_threads tables; drift checks and auto-restore assertions updated for expanded inventory.
Tests—FTS trigger lifecycle with new surfaces and rebuild recovery
tests/unit/storage/test_fts_trigger_lifecycle.py
Expected trigger set expanded to 12; bootstrap schema creates new source/FTS tables; new test validates rebuild recovery for insight surfaces; concurrent suspend/restore tests adjusted for expanded set.

Cursor Lag Database Lock Resilience

Layer / File(s) Summary
Lock-resilient cursor lag sampling with short timeout
polylogue/daemon/cursor_lag_baseline.py
record_cursor_lag_sample and gc_cursor_lag_samples now use 0.1 second timeout and catch OperationalError to detect "database is locked" condition, returning 0 instead of blocking or propagating exceptions.
Tests—cursor lag non-blocking under database lock
tests/unit/daemon/test_cursor_lag_integration.py
New integration test verifies that both cursor lag functions complete without blocking when a concurrent SQLite EXCLUSIVE lock is held.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Sinity/polylogue#1362: Both PRs modify daemon startup missing FTS trigger detection and recovery logic, changing what triggers are considered expected and when they are restored or rebuilt.
  • Sinity/polylogue#1206: Both PRs couple to FTS trigger lifecycle behavior—main PR expands the canonical expected trigger set affecting drift/restore expectations, while #1206 adds concurrency invariant tests against the expected trigger inventory.
  • Sinity/polylogue#554: Both PRs propagate FTS trigger expectations from polylogue/storage/fts/fts_lifecycle.FTS_TRIGGER_NAMES into daemon and trigger-awareness components, modifying how missing/unready triggers are detected.

🐰 The triggers now bloom in threes and fours,
No longer guessing which surfaces have floors!
With tables that exist, we activate with grace,
And locks shan't slow the lag-sampling race. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.42% 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 accurately and specifically summarizes the primary change: restoring all active FTS triggers in the daemon.
Description check ✅ Passed The description follows the template with complete Summary, Problem, Solution, and Verification sections; Changelog and Risks/Follow-ups sections are appropriately omitted or handled.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/daemon-fts-health-locks

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.

@Sinity
Sinity merged commit 2ba4b07 into master May 23, 2026
5 of 6 checks passed
@Sinity
Sinity deleted the feature/fix/daemon-fts-health-locks branch May 23, 2026 23:26

@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: 8ffbb36960

ℹ️ 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/metrics.py Resolved
Comment thread devtools/daemon_workload_probe.py Resolved
Sinity added a commit that referenced this pull request May 23, 2026
## Summary

Adds process-holder diagnostics to WAL checkpoint observations so live ingest and daemon checkpoint logs can explain when SQLite checkpointing is blocked by another reader instead of silently leaving a large WAL behind.

## Problem

While deploying the FTS trigger repair work from #1455, `polylogued` generated a growing WAL during catch-up and checkpointing stayed busy. The live blocker was an unrelated long-running `lynchpin.cli.current_state` process holding Polylogue database files open, but Polylogue only reported checkpoint mode/page counts. That left the operator to manually correlate `/proc`, `fuser`, and service logs.

## Solution

`WalCheckpointObservation` now carries bounded `/proc` process-holder details when a checkpoint is busy, locked, or leaves the WAL above the truncate threshold. Batch ingest logs `wal_checkpoint_blocked` with the checkpoint reason, WAL sizes, busy pages, and first blockers; the daemon periodic checkpoint log includes the same blocker list. The `/proc` scan is Linux-only, bounded to active file descriptors for `polylogue.db`, `.db-wal`, and `.db-shm`, and degrades quietly when `/proc` entries vanish during iteration.

Ref #1447.

## Verification

- `pytest tests/unit/pipeline/test_ingest_batch_wal_checkpoint.py -q` → `2 passed in 0.08s`
- `python -m mypy polylogue/storage/sqlite/wal_checkpoint.py polylogue/pipeline/services/ingest_batch/_core.py polylogue/daemon/cli.py tests/unit/pipeline/test_ingest_batch_wal_checkpoint.py` → `Success: no issues found in 4 source files`
- `devtools verify --quick` → exit 0, total `38.78s`
@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.

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

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

  • 63.F117 / P2: fixed-already at the checked revision: Metrics now obtain their expected trigger set from active_fts_triggers_sync at polylogue/daemon/metrics.py:589 rather than the old global twelve-name inventory. They emit presence only for that returned set at line 598, so absent retired optional surfaces do not create phantom missing-trigger samples.

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.

1 participant