Skip to content

fix(daemon): remove broad startup maintenance scans - #1464

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/daemon-remove-broad-runtime-scans
May 24, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/daemon-remove-broad-runtime-scans

Conversation

@Sinity

@Sinity Sinity commented May 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Removes broad automatic maintenance scans from the daemon startup/catch-up path. PRAGMA optimize now waits for the daily maintenance interval before first execution, and the daemon no longer starts an exact FTS invariant repair loop 30 seconds after launch.

Problem

Live validation of deployed Polylogue cc0bf5ba still showed unsafe host IO during catch-up:

  • polylogued.service started from /nix/store/10lqh6vbj0b5grkww4iqkvhlipjx2wj7-python3.13-polylogue-0.1.0/bin/polylogued.
  • Chunk 1 and chunk 2 writes were bounded (changed_messages=208 and 368, both under 5s), so source parse/write was no longer the primary issue.
  • IO PSI still climbed to full avg10=31.72%, with process read_bytes=12,176,195,584 and only ~341 MB RSS.
  • The daemon starts PRAGMA optimize immediately and also schedules exact FTS invariant checking after 30 seconds. On this archive the DB file is 46G, so these broad reads run concurrently with catch-up and dominate host IO.

Solution

The always-on daemon now avoids broad maintenance reads during startup/catch-up:

  • PRAGMA optimize sleeps for its 24h maintenance interval before the first pass.
  • The exact FTS invariant repair loop is removed from daemon startup. FTS freshness for live writes still comes from startup structural readiness plus targeted changed-conversation convergence repair.
  • Startup now handles the missing-trigger crash signature by doing the correctness-preserving one-time rebuild before serving search, and targeted daemon FTS repair clears the durable message-search freshness ledger after changed conversations have been repaired.

Full exact FTS invariant audits remain explicit maintenance/lab work rather than a background daemon loop. This does not reduce daemon convergence scope: valid changed source files still ingest and converge; the change only removes unrelated broad maintenance scans from the runtime path.

Verification

  • pytest tests/unit/daemon/test_daemon_cli.py tests/unit/daemon/test_convergence_stages.py -q -> 29 passed in 0.32s
  • ruff check polylogue/daemon/cli.py polylogue/daemon/convergence_stages.py tests/unit/daemon/test_daemon_cli.py tests/unit/daemon/test_convergence_stages.py -> All checks passed!
  • mypy polylogue/daemon/cli.py polylogue/daemon/convergence_stages.py tests/unit/daemon/test_daemon_cli.py tests/unit/daemon/test_convergence_stages.py -> Success: no issues found in 4 source files
  • devtools verify --quick -> passed in 36.05s before push
  • pre-push devtools verify --quick -> passed in 33.85s
  • PR checks: Analyze, CodeQL, GitGuardian, runtime container, and distroless container passed

Ref #1447

Problem: live deployment of #1463 still pushed IO PSI above 30% during catch-up. The daemon launched PRAGMA optimize immediately and scheduled an exact FTS invariant repair loop 30 seconds after start, causing broad reads on a 46G archive while catch-up was already active.

What changed: defer PRAGMA optimize until the daily maintenance interval has elapsed, and remove the automatic exact FTS invariant repair loop from the always-on daemon. FTS freshness for live work remains enforced by startup structural readiness plus targeted changed-conversation convergence repair; full exact invariant audits belong to explicit maintenance, not runtime catch-up.

Verification: pytest tests/unit/daemon/test_daemon_cli.py tests/unit/daemon/test_convergence_stages.py -q; ruff check polylogue/daemon/cli.py tests/unit/daemon/test_daemon_cli.py; mypy polylogue/daemon/cli.py tests/unit/daemon/test_daemon_cli.py; devtools verify --quick.

Ref #1447
@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Daemon maintenance task scheduling is refactored to separate startup optimization from periodic background work: the periodic DB optimization task now sleeps 24 hours before each check, status snapshot monitoring is integrated into maintenance tasks, and FTS repair background task is removed.

Changes

Daemon maintenance task scheduling and optimization

Layer / File(s) Summary
Periodic DB optimization timing
polylogue/daemon/cli.py
_periodic_db_optimize loop is adjusted to unconditionally sleep 24 hours before checking database existence, instead of sleeping only when the database is absent. Docstring is updated to clarify this optimization pass executes after startup readiness.
Maintenance task composition
polylogue/daemon/cli.py
run_daemon_services adds status_snapshot_task to maintenance tasks and removes the previously included periodic _periodic_fts_repair task creation.
Startup behavior validation and FTS test mocking
tests/unit/daemon/test_daemon_cli.py
Three existing FTS startup readiness test cases are updated with enhanced sqlite_master query mocking to return results for specific table names (messages, messages_fts, action_events, action_events_fts). New test test_periodic_db_optimize_does_not_run_on_startup validates that periodic DB optimization does not open a connection during daemon startup by patching asyncio.sleep to immediately error and asserting connection opening is never invoked.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • Sinity/polylogue#1445: The FTS startup readiness test mocking improvements in this PR (handling SELECT 1 FROM sqlite_master ... name = ? queries for specific base/FTS table names) correspond to structural fts_readiness_info() probing changes introduced in that PR.

Poem

🐰 A daemon's morning work now waits its turn,
No hurried checks at startup's churn,
Tasks shuffle in, some exit stage right,
Sleep's promise keeps the balance tight—
Tests confirm the caution reigns,
While snapshots flow through maintenance lanes. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% 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 'fix(daemon): remove broad startup maintenance scans' accurately summarizes the primary change: removing automatic maintenance scans from daemon startup, which directly addresses the expensive host IO problem during catch-up.
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.
Description check ✅ Passed The pull request description is comprehensive and well-structured, covering the summary, problem statement, solution, verification steps, and appropriate references.

✏️ 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-remove-broad-runtime-scans

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: 59f2acf928

ℹ️ 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 merged commit 2dc505c into master May 24, 2026
6 checks passed
@Sinity
Sinity deleted the feature/fix/daemon-remove-broad-runtime-scans branch May 24, 2026 02:00
Sinity added a commit that referenced this pull request May 24, 2026
## Summary

Blocks offline maintenance repair/cleanup paths while a live
`polylogued` pidfile points at an actual daemon process, and surfaces
that refusal through both `doctor --repair` and `polylogue maintenance
run` envelopes. Dry-run previews remain allowed.

## Problem

During the #1447 live deployment pass after #1464, a foreground
`polylogue doctor --repair --target session_insights` process appeared
while `polylogued` was catching up a large Codex session. The repair
process held the SQLite lock and daemon insight convergence failed with
`OperationalError: database is locked`, leaving the latest live ingest
attempt stuck in `running/convergence` until shutdown. That is not valid
daemon convergence behavior; offline repair must not race the live
daemon-owned writer.

## Solution

- Add `polylogue.maintenance.offline_guard` to verify a `daemon.pid`
belongs to a live `polylogued` process.
- Make `storage.repair.run_selected_maintenance` return target-level
failures instead of starting offline repair/cleanup when the daemon is
live.
- Make maintenance replay return a typed failed operation with
`OfflineMaintenanceBlocked` failure samples under the same condition.
- Refresh topology generated surfaces for the new module.

This preserves daemon scope: the daemon still owns live convergence and
should drain valid inputs; out-of-band offline repair now requires
stopping the daemon first.

## Verification

- `pytest tests/unit/storage/test_repair.py
tests/unit/maintenance/test_idempotency.py
tests/unit/sources/test_live_batch_convergence.py
tests/unit/daemon/test_ingest_worker_handoff.py -q` → `22 passed in
2.91s`
- `ruff check polylogue/maintenance/offline_guard.py
polylogue/storage/repair.py polylogue/maintenance/replay.py
tests/unit/storage/test_repair.py
tests/unit/maintenance/test_idempotency.py` → `All checks passed!`
- `mypy polylogue/maintenance/offline_guard.py
polylogue/storage/repair.py polylogue/maintenance/replay.py
tests/unit/storage/test_repair.py
tests/unit/maintenance/test_idempotency.py` → `Success: no issues found
in 5 source files`
- `devtools verify-file-budgets` → `file-size budgets: clean`
- `devtools verify-topology` → `realized=829 declared=829
blocking=False`
- `devtools render-all --check` → passed
- `devtools verify --quick` → `exit_code: 0`, `total_duration_s: 36.4`
- pre-push `devtools verify --quick` → `exit_code: 0`,
`total_duration_s: 34.44`

Ref #1447
@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.F031 / P1: fixed-already at the checked revision: Search readiness now delegates to authoritative message_fts_readiness_sync at polylogue/storage/fts/fts_lifecycle.py:614 rather than treating a non-ready freshness ledger row as permanent authority. The daemon's recurring convergence service receives the FTS owner at polylogue/daemon/cli.py:2838-2842, so the removed legacy exact-ledger task is no longer required to unlock healthy searches.

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