Skip to content

perf(daemon): bound startup FTS checks - #1434

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/bounded-daemon-startup
May 23, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/bounded-daemon-startup

Conversation

@Sinity

@Sinity Sinity commented May 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Bounds daemon restart/status FTS probes so ordinary restarts do not scan the full messages table or rebuild FTS from the idle convergence loop. The daemon now writes its pidfile before startup FTS readiness and uses existence probes for startup health; status derives source message counts from conversation_stats instead of COUNT(*) FROM messages WHERE text IS NOT NULL.

Problem

While deploying #1433 to the real archive, polylogued spent about 59 seconds before logging the FTS mismatch and about 10 minutes rebuilding FTS before the watcher started. During that window it had no fresh pidfile, so polylogue status reported a stale pidfile for the old process. The expensive startup path was caused by full-table FTS parity counts on a multi-million-row archive, and the idle convergence loop still had another global count/rebuild path.

Solution

  • Acquire the daemon pidfile before FTS startup readiness so operator status does not misclassify a live restart as stale.
  • Replace startup FTS parity counts with bounded SELECT 1 ... LIMIT 1 probes that only rebuild the historical empty-index case.
  • Remove global FTS count/rebuild work from _periodic_convergence_check; per-source and per-conversation convergence repair remains intact.
  • Use conversation_stats for daemon FTS status source counts so status avoids scanning messages.

Verification

  • pytest tests/unit/daemon/test_daemon_cli.py::test_ensure_fts_startup_readiness_uses_bounded_probes tests/unit/daemon/test_daemon_cli.py::test_ensure_fts_startup_readiness_rebuilds_empty_fts tests/unit/daemon/test_daemon_cli.py::test_ensure_fts_startup_readiness_rebuilds_when_triggers_missing tests/unit/daemon/test_daemon_status.py::test_daemon_status_fts_readiness_uses_stats_not_message_scan tests/unit/daemon/test_daemon_status.py::test_daemon_status_fts_readiness_uses_lightweight_table_probe -q → 5 passed
  • python -m mypy polylogue/daemon/cli.py polylogue/daemon/fts_status.py tests/unit/daemon/test_daemon_cli.py tests/unit/daemon/test_daemon_status.py → success
  • ruff format ... && ruff check ... → all checks passed
  • devtools render-all --check → OK
  • pre-push devtools verify --quick → exit_code 0, total_duration_s 34.75

Summary by CodeRabbit

  • Performance Improvements
    • Optimized daemon startup by replacing Full Text Search readiness detection with efficient presence checks instead of full message counts.
    • Enhanced message indexable count calculations to use statistics tables instead of scanning individual messages, reducing computational overhead.
    • Refined periodic maintenance logic for improved index convergence handling.

Review Change Stack

Problem: daemon restart was paying full-archive FTS count scans before writing its pidfile, which left status reporting stale pidfiles and kept the host in IO pressure during ordinary restarts. The idle convergence loop also repeated global FTS count/rebuild checks instead of relying on per-source convergence debt.

What changed: acquire the pidfile before startup FTS readiness, replace startup FTS parity counts with bounded existence probes, use conversation_stats for daemon FTS status source counts, and remove global FTS rebuild scans from the periodic idle convergence loop. Per-source and per-conversation convergence repair remains in the daemon path.

Verification: ruff format/check on touched files; focused daemon pytest nodes; focused mypy on touched files.
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR optimizes FTS readiness monitoring by replacing expensive full-table COUNT(*) scans with lightweight presence checks and stats-based accounting. Startup readiness detection now uses bounded LIMIT 1 queries; message indexable counts come from conversation_stats aggregates; the readiness check is repositioned after pidfile acquisition; and periodic maintenance shifts to convergence debt retry logic.

Changes

Lightweight FTS Readiness and Indexing Monitoring

Layer / File(s) Summary
Bounded FTS Readiness Detection
polylogue/daemon/cli.py, tests/unit/daemon/test_daemon_cli.py
_ensure_fts_startup_readiness() replaces count-based mismatch detection with bounded SELECT 1 ... LIMIT 1 presence checks for messages and messages_fts_docsize, triggering rebuild only when messages exist but docsize is empty. Test scenarios updated to validate bounded probes and forbid unbounded COUNT(*) queries.
Message Indexable Count via Conversation Stats
polylogue/daemon/fts_status.py, tests/unit/daemon/test_daemon_status.py
fts_readiness_info computes message_indexable_count by summing message_count from conversation_stats instead of scanning messages table. conversation_stats added to SQLite table allowlist. New test traces executed SQL to verify stats-based probe avoids message row scans.
Startup Sequencing: Readiness After Pidfile
polylogue/daemon/cli.py
run_daemon_services moves _ensure_fts_startup_readiness() call to after pidfile (advisory lock) acquisition, removing the earlier pre-pidfile check with updated comments on operator visibility and bounded maintenance.
Periodic Convergence Debt Retry
polylogue/daemon/cli.py
_periodic_convergence_check() is repurposed from FTS coverage validation to a convergence-debt retry safety net that periodically runs _drain_convergence_debt_once() in a background thread, removing FTS gap/mismatch detection logic and logging retry counts.

🎯 3 (Moderate) | ⏱️ ~18 minutes


🐰 With LIMIT 1 queries and stats so bright,
We check FTS presence without database fright—
No more COUNT(*) scans on messages of old,
Just presence checks and conversation gold,
Convergence debt now our periodic fold! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% 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 'perf(daemon): bound startup FTS checks' accurately and concisely summarizes the main optimization: bounding (limiting) expensive full-table FTS checks during daemon startup to avoid scanning the messages table.
Description check ✅ Passed The pull request description is comprehensive and follows the template structure with all required sections: Summary, Problem, Solution, Verification, Changelog (appropriately skipped), and Risks/Follow-ups (appropriately omitted).
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/perf/bounded-daemon-startup

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: bf0d8538af

ℹ️ 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/fts_status.py Resolved

@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

🤖 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 `@tests/unit/daemon/test_daemon_status.py`:
- Around line 314-327: The test currently only asserts a negative condition on
the traced SQL queries which will vacuously pass if no queries were captured;
update the test around traced_connect/queries/_fts_readiness_info to first
assert that queries captured is non-empty (e.g., assert queries) and then
perform normalized matching (lowercase and strip whitespace) when checking that
no query contains the pattern "count(*) from messages where"; locate the
traced_connect helper and the queries list used in the with-patch block and add
the positive assertion plus use normalized query strings for the negative
membership check against the COUNT(*) pattern.
🪄 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: ad1bfafc-e123-4e62-a778-b1ffd62f8bc2

📥 Commits

Reviewing files that changed from the base of the PR and between 3dea102 and bf0d853.

📒 Files selected for processing (4)
  • polylogue/daemon/cli.py
  • polylogue/daemon/fts_status.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/daemon/test_daemon_status.py

Comment on lines +314 to +327
def traced_connect(*args: Any, **kwargs: Any) -> sqlite3.Connection:
conn = original_connect(*args, **kwargs)
conn.set_trace_callback(queries.append)
return cast(sqlite3.Connection, conn)

with (
patch("polylogue.daemon.status.db_path", return_value=db),
patch("polylogue.storage.sqlite.connection_profile.sqlite3.connect", side_effect=traced_connect),
):
readiness = status_module._fts_readiness_info()

assert readiness["message_indexable_count"] == 5
assert readiness["message_indexed_count"] == 5
assert all("COUNT(*) FROM messages WHERE" not in query for query in queries)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Strengthen the SQL-trace assertion to avoid vacuous pass.

If trace capture ever breaks, the current negative assertion still passes with an empty queries list. Add a positive capture assertion and normalize SQL before matching.

Proposed fix
 def test_daemon_status_fts_readiness_uses_stats_not_message_scan(tmp_path: Path) -> None:
@@
     with (
         patch("polylogue.daemon.status.db_path", return_value=db),
         patch("polylogue.storage.sqlite.connection_profile.sqlite3.connect", side_effect=traced_connect),
     ):
         readiness = status_module._fts_readiness_info()
 
     assert readiness["message_indexable_count"] == 5
     assert readiness["message_indexed_count"] == 5
-    assert all("COUNT(*) FROM messages WHERE" not in query for query in queries)
+    assert queries
+    normalized_queries = [" ".join(query.upper().split()) for query in queries]
+    assert any("FROM CONVERSATION_STATS" in query for query in normalized_queries)
+    assert all("COUNT(*) FROM MESSAGES WHERE" not in query for query in normalized_queries)
🤖 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 `@tests/unit/daemon/test_daemon_status.py` around lines 314 - 327, The test
currently only asserts a negative condition on the traced SQL queries which will
vacuously pass if no queries were captured; update the test around
traced_connect/queries/_fts_readiness_info to first assert that queries captured
is non-empty (e.g., assert queries) and then perform normalized matching
(lowercase and strip whitespace) when checking that no query contains the
pattern "count(*) from messages where"; locate the traced_connect helper and the
queries list used in the with-patch block and add the positive assertion plus
use normalized query strings for the negative membership check against the
COUNT(*) pattern.

@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.F064 / P1: fixed-already at the checked revision: FTS status now derives its source count from the authoritative searchable-block surface at polylogue/daemon/fts_status.py:159-169. The adapter counts blocks WHERE search_text != '' at polylogue/storage/fts/derivation.py:166, not conversation_stats.message_count, so non-indexable messages do not depress coverage.

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