Repository navigation
perf(daemon): run periodic FTS merge every 60s instead of 300s - #3288
Conversation
Problem: live incident 2026-07-27 -- a single live-watcher catch-up append held the sole-writer lock for 860s (14+ minutes) parsing/ writing one modest (~7MB, 547-block) session. At the previous 300s merge interval this starved _periodic_fts_merge outright during exactly the backlog conditions it exists to help with: messages_fts_data (the automerge=0 FTS5 shadow table, #1851) had grown to 705,281 rows live, far past steady state. Unmerged segment bloat itself degrades per-block FTS5 insert cost (a documented FTS5 characteristic), which lengthens the next writer hold and starves the merge task further -- a genuine self-reinforcing degradation spiral, not a one-off slow pass. What changed: interval 300s -> 60s. The per-call work bound is unchanged (still the same small, deliberately-bounded 500-work-unit / 2-4 MiB chunk -- the merge pass itself must never become a long writer hold, see fts_automerge.py's design rationale) -- this only asks for the writer's turn 5x more often, so backlog clears faster once contention eases. Does not fix worst-case starvation: a single very long writer hold still blocks every queued actor regardless of how often they ask. Tracked as polylogue-de2a for the harder writer-fairness/adaptive- merge-budget question, deliberately out of scope for this narrow, low-risk cadence change. Verification: devtools test tests/unit/daemon/test_daemon_cli.py (116 passed); devtools verify --quick (pass). Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
📝 WalkthroughWalkthroughThe daemon’s periodic FTS merge loop now runs every 60 seconds through a new module constant, replacing the previous fixed five-minute interval and updating its documentation. ChangesFTS merge maintenance
Estimated code review effort: 1 (Trivial) | ~5 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 `@polylogue/daemon/cli.py`:
- Around line 395-410: Correct the incident date in the comment above the merge
interval change: replace the future date 2026-07-27 with the actual observed
incident date, or explicitly label the statement as a forecast/planned
observation if the date is not yet known. Preserve the remainder of the incident
context unchanged.
🪄 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 Plus
Run ID: 0b6bd819-a4c2-4a55-a4e8-9c7d12df8cf1
📒 Files selected for processing (1)
polylogue/daemon/cli.py
| #: Live incident 2026-07-27: a long-running ingest/append pass can hold the | ||
| #: sole-writer lock for 14+ minutes straight (observed: 860s for one live | ||
| #: watcher catch-up chunk). At the previous 300s interval this starved the | ||
| #: merge task outright during exactly the backlog conditions it exists to | ||
| #: help with -- messages_fts_data grew to 700K+ rows (steady state is far | ||
| #: lower) before a merge got a turn, and unmerged segment bloat itself makes | ||
| #: every subsequent per-block FTS5 insert slower, which lengthens the next | ||
| #: writer hold and starves the merge task further: a genuine, self- | ||
| #: reinforcing degradation spiral, not merely a slow one-off pass. Shortening | ||
| #: the interval does not touch the per-call work bound (still the same small, | ||
| #: bounded 500-work-unit / 2-4 MiB chunk -- the merge pass itself must never | ||
| #: become a long writer hold, see fts_automerge.py) -- it only asks for the | ||
| #: writer's turn more often, so once contention eases the backlog clears | ||
| #: roughly 5x faster than before. This does not fix worst-case starvation | ||
| #: (a single 14-minute hold still blocks every queued actor including this | ||
| #: one) -- see polylogue-de2a for the harder writer-fairness question. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the incident date in the comment.
2026-07-27 is tomorrow relative to the current date, July 26, 2026, so it cannot describe an already observed live incident. Replace it with the actual incident date or label it as a forecast/planned observation.
🤖 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 `@polylogue/daemon/cli.py` around lines 395 - 410, Correct the incident date in
the comment above the merge interval change: replace the future date 2026-07-27
with the actual observed incident date, or explicitly label the statement as a
forecast/planned observation if the date is not yet known. Preserve the
remainder of the incident context unchanged.
…n live hot path (#3358) ## Summary Fixes the confirmed root cause of polylogue-de2a's multi-minute/multi-hour daemon writer-gate holds: `apply_raw_revision_replay` re-indexes every historical raw revision in a session's append chain on every single new live append, not just the new tail. This PR adds an opt-in fast path that skips re-writing (not re-parsing) already-durably-applied positions. ## Problem polylogue-de2a was opened after observing the live daemon's watcher `catch-up.chunk` actor hold the sole-writer lock for 860 seconds (14+ minutes) processing a single modest (~7MB, 547-block) session append, and in a more extreme case, 9297 seconds (2.6 hours) for one append. While held, every other periodic daemon actor (FTS merge, WAL checkpoint, convergence) was starved for the entire duration, since `DaemonWriteCoordinator` serializes all writers through one gate with no preemption of an already-admitted holder. Two prior fast-follows in this bead (PR #3288: shortened the FTS-merge interval 300s -> 60s; PR #3289: gave maintenance actors queue-admission priority over watcher actors) mitigated recovery speed and worst-case starvation bound, but neither fixes an already-admitted single hold running for minutes to hours. Root-causing this session with a direct SQL-level trace of `apply_raw_revision_replay` (`polylogue/storage/sqlite/archive_tiers/archive.py`): its write loop (`for position, raw_id in enumerate(plan.accepted_raw_ids)`) calls `_index_parsed_for_retained_raw` -> `write_parsed_session_to_archive` for **every** raw_id in the accepted chain, every single call -- including every historical append already durably applied by an earlier successful replay. `messages`/`blocks` writes use `INSERT OR REPLACE`, which re-fires `messages_fts` insert triggers even for byte-identical content that never changed. The live watcher's per-append hot path (`polylogue/sources/live/append_ingest.py`) always builds `parsed_by_raw_id` for the **entire** accepted chain (not just the new tail), so a long-lived session accumulating N small live appends over its life pays O(N) redundant historical writes on its Nth append and O(N^2) cumulatively -- exactly the self-reinforcing FTS-segment-bloat spiral this bead's live evidence already pointed to (`messages_fts_data` at 705K rows). ## Solution - `apply_raw_revision_replay` gains `skip_already_applied: bool = False` (default preserves today's behavior for every existing caller). When `True`, it captures the logical source's current `raw_revision_heads.accepted_raw_id` *before* any clearing (the quarantined-membership-fold path can null it later in the same call), finds that raw_id's position in `plan.accepted_raw_ids`, and skips the index write for every position at or before it -- only the new tail gets written. `session_id` for a skipped position is derived deterministically from its already-parsed content (`make_session_id(parsed.source_name, parsed.provider_session_id)`) instead of the write result. - Only `append_ingest.py`'s live per-append call site opts in (`skip_already_applied=True`). The backfill/restore/membership-classification call sites (`revision_backfill.py`, `batch.py`) keep the full self-healing re-apply unchanged -- their content may predate a parser fix and legitimately need every historical position rewritten, and they run far less often than a live append. - Reparsing (`parse_retained_raw_sessions`) is intentionally left unchanged -- the aggregate content hash and semantic frontier still need every position's parsed content merged. Only the expensive SQL/FTS **write** is skipped for already-applied positions. - Small mechanical drift-fix commit first: `devtools/render_docs_surface.py` had drifted from the current ruff formatter (unrelated pre-existing issue on master), which blocked the pre-push hook's `devtools verify --quick` for every branch; fixed with `ruff format` + `devtools render docs-surface` (no logic change). ## Verification - `devtools test tests/unit/storage/test_revision_replay.py` -- 26 passed, including two new tests added by this PR: - `test_skip_already_applied_indexes_only_new_tail_of_append_chain`: simulates three sequential live appends onto a growing chain (mirroring `append_ingest.py`'s real shape, which always replays the whole accumulated chain), spies on `_index_parsed_for_retained_raw` calls, and proves only the newest tail position is ever indexed on the 2nd/3rd calls -- plus asserts final message content and the recorded head are correct. - `test_skip_already_applied_default_false_still_reindexes_whole_chain`: pins that callers not opting in still re-index every position, unchanged. - `devtools test tests/unit/storage/ tests/unit/sources/test_live_*.py tests/unit/sources/test_revision_backfill.py` -- 267 passed. - `devtools verify --quick` -- format + lint + `mypy --strict` + `render all --check`, exit 0. - `mypy --strict` (standalone) on the two touched production files -- "Success: no issues found in 2 source files". - Two integration-test failures were investigated and confirmed pre-existing on unmodified `origin/master` (verified via `git stash` before/after this change, identical failure both ways, unrelated to this fix): `tests/integration/test_append_cohort_memory.py`'s two tests (a `replay_raw_blob.read_all`/`historical_full_blob.read_all` counter mismatch unrelated to indexing) and `tests/integration/test_live_read_amplification.py::TestRestartedCursorReconcile::test_missing_cursor_reconciles_archived_prefix_for_append`. ## Remaining polylogue-de2a scope This PR removes the dominant cost driver that produced the observed 860s/9297s pathological holds, but does not add a genuine preemption/yield mechanism for an already-admitted single-actor writer hold in general -- a mid-hold SQLite transaction cannot safely release the coordinator's async gate without also releasing the real DB-level write lock, so that harder problem (an unrelated, genuinely slow single stage blocking maintenance for its whole duration) remains open if it ever recurs from a different cause. Left open with this note; not closing the bead from this PR alone. Ref polylogue-de2a --------- Co-authored-by: Claude <[email protected]>
#3534) ## Summary Adds a declared, enforced wall-clock budget to the daemon's raw-materialization trickle pass so it can no longer hold the process-wide writer coordinator for minutes at a time, starving other periodic maintenance actors (FTS merge, session insights, convergence-debt retry). ## Problem Ref polylogue-de2a. Live-observed 2026-07-27: the daemon's watcher `catch-up.chunk` actor held the sole-writer lock for 860 seconds parsing/writing a single session append; every other periodic daemon actor was queued behind it for that entire window. Several mitigations already shipped against this bead (PR #3288 interval tuning, PR #3289 maintenance-actor priority admission, PR #3358 removing an O(n²) redundant-reapply cost driver), but the bead's own 2026-07-29 convergence audit recorded the remaining gap directly: raw materialization still holds the sole writer for ~188s per pass (four consecutive passes measured: 188.7, 188.9, 187.1, 189.8s) with observed maintenance-actor wait up to 616.3s and queue depth 10 — even though the pass's own component-count limit (`raw_artifact_limit`, 16-64) was already small. The count limit did not bound hold time because per-component cost (parse, replay, then a full FTS/action-pairs/delegation-facts rebuild per component) dominates, not component count. ## Solution - `repair_raw_materialization` (`polylogue/storage/repair.py`) gains an optional `max_pass_seconds` parameter (`None` default, byte-for-byte unchanged for existing callers). - Both the CENSUS loop and the REPLAY loop check elapsed time only *between* components — the same point they already commit and requery candidates, a genuine transaction-boundary checkpoint, not an unsafe mid-write yield (a mid-hold SQLite transaction cannot safely release the async gate without releasing the real DB-level write lock, per this bead's own prior analysis). Each loop always completes at least one component before checking the budget, so a single slower-than-budget component still makes forward progress instead of stalling. - Components the replay loop skips due to the budget get an explicit `RETRYABLE` outcome recorded before the loop breaks: `finalize_raw_authority_census` is fail-closed on every *selected* plan having a recorded outcome (discovered via a first failing test iteration), so silently leaving them unattempted is not safe the way `raw_artifact_limit` truncation (which happens before selection) already is. - `polylogue/product/raw_authority.py`'s `repair_materialization` wrapper threads the new parameter through. - `polylogue/daemon/cli.py`'s ordinary drain pass (`_drain_raw_materialization_once`) now always passes a declared `_RAW_MATERIALIZATION_MAX_PASS_SECONDS = 20.0`. The escalation-tier whale pass (`_run_raw_materialization_whale_pass_once`), whose entire purpose is converging one oversized, resource-blocked component in a single pass once the ordinary conveyor is quiescent, is deliberately left unbounded. - New metrics `raw_materialization_pass_seconds` and `raw_materialization_time_budget_exceeded` are forwarded through the existing `_emit_raw_materialization_pass` daemon-event path alongside the writer-hold/wait metrics `write_coordinator.py` already exports, so the bound's effect is observable per pass without grepping the journal. ## Acceptance criteria (bead has 4) 1. **Hold/wait measured and exported** — already satisfied before this PR by `polylogue/daemon/write_coordinator.py`; unchanged here. 2. **No maintenance actor waits longer than a declared, enforced bound** — materially tightened, not fully closed: combined with the already-shipped maintenance-priority admission (PR #3289, which lets a queued maintenance actor cut ahead of queued ingest actors), worst-case queued-actor wait is now bounded by roughly "current pass's remaining time budget + at most one more already-queued, equally-bounded ingest hold" instead of an unbounded multi-minute wait. This is the dominant offender this bead measured; the same technique is not yet applied to every other actor that can hold the writer. 3. **Long-running convergence work yields at declared checkpoints** — satisfied for the raw-materialization pass specifically: the census and replay loops now check a stated time budget between components instead of holding for the whole selected batch. 4. **Live re-measurement under a comparable backlog** — not done in this PR (requires a deployed daemon against a live-scale backlog); left as explicit follow-up. ## Verification ``` devtools test tests/unit/storage/test_repair.py tests/unit/daemon/test_daemon_cli.py tests/unit/daemon/test_raw_materialization_parse_stage_equivalence.py ``` → 169 passed, 11 pre-existing failures unchanged from baseline (confirmed by stashing this branch's changes and re-running against origin/master tip: the identical 11 tests fail identically, all an unrelated "no messages, no positive conversational evidence" parser-refusal drift in shared test fixtures — out of scope for this bead). New regression test `test_raw_materialization_max_pass_seconds_bounds_one_pass_and_preserves_progress` reproduces the shape of the live incident with a synthetic 3-component backlog and a deterministic fake monotonic clock: with `max_pass_seconds=1.0` a single `repair_raw_materialization` call replays exactly 1 of 3 selected components and leaves the other 2 as ordinary candidates (`remaining_candidate_count == 2`, `success is False`), and a follow-up call without a budget finishes the remaining 2 — proving no work is lost or corrupted by the early stop. Verified this test is load-bearing by reverting the production changes only (`git stash` on the three touched non-test files) and confirming it fails with `TypeError: unexpected keyword argument 'max_pass_seconds'`. ``` devtools verify --quick ``` → passes (ruff format/check, mypy --strict, render all --check, layering, schema-versioning, all other quick gates). `devtools verify` (testmon) was not run — the checkout's testmon cache is unseeded in this worktree; the two `devtools test` invocations above cover every file this PR touches plus their existing test suites. ## Follow-ups - AC2's declared bound currently applies only to the raw-materialization pass, the dominant offender this bead measured. If another actor is later found to produce comparably long holds, the same time-budget-between-checkpoints technique should be applied there too. - AC4 (live re-measurement) needs a deployed daemon under a comparable backlog; not attempted here. Co-authored-by: Claude <[email protected]>
Summary
Shortens the FTS5 periodic-merge interval from 300s to 60s to break a self-reinforcing degradation spiral discovered live while investigating why PR #3287's stale-plan auto-resolve hadn't taken effect after deploy.
Problem
Live incident, 2026-07-27: a single live-watcher catch-up append held the daemon's sole-writer lock for 860 seconds (14+ minutes) parsing/writing one modest (~7MB, 547-block) session. At the previous 300s merge interval this starved
_periodic_fts_mergeduring exactly the backlog conditions it exists to help with.Root cause chain, verified against the live archive (not speculation):
messages_ftsruns withautomerge=0(fts_automerge.py, daemon: ~14 MiB of DB writes per live-ingest batch regardless of payload size (~1000x app-level write amplification for small appends) #1851) — segment consolidation depends entirely on the periodic merge task, bounded to a small 500-work-unit (2-4 MiB) chunk per call by design.messages_fts_data(the FTS5 shadow table) had grown to 705,281 rows live — far past steady state, consistent with the merge task being starved for an extended period.Solution
Interval 300s → 60s. The per-call work bound is unchanged — still the same deliberately small, bounded chunk (the merge pass itself must never become a long writer hold). This only asks for the writer's turn 5x more often, so once contention eases the backlog clears roughly 5x faster.
Not a complete fix: a single very long writer hold still blocks every queued actor regardless of how often they ask. The harder question — writer-lock fairness/priority, or bounding how long a single ingest pass can hold the lock without yielding — is tracked separately as polylogue-de2a, deliberately out of scope for this narrow, low-risk cadence change.
Verification
devtools test tests/unit/daemon/test_daemon_cli.py— 116 passed.devtools verify --quick— pass.Ref polylogue-de2a
Summary by CodeRabbit