Repository navigation
perf(daemon): give maintenance actors priority over bulk-ingest waiters - #3289
Conversation
Problem: DaemonWriteCoordinator serialized every writer through a plain asyncio.Lock (strict FIFO). Under a sustained live-watcher catch-up backlog, "watcher.*" chunk requests re-queue almost immediately after each release, so a periodic maintenance actor (FTS merge, WAL checkpoint, raw-materialization convergence) that only wakes every N seconds could be stuck behind an ever-refilling line of ingest waiters. This starved polylogue-de2a's auto_resolve_stale_plan_blockers pass (polylogue-d7im) and let messages_fts_data balloon to 705K rows during a live incident (2026-07-26): a single 14-minute ingest hold plus continuous re-queueing left FTS merge with no turn for an extended period. What changed: replaced the coordinator's plain asyncio.Lock with a _PriorityGate that admits queued waiters by (priority, arrival order) instead of pure FIFO. Every actor name outside the existing "watcher." naming convention (maintenance.*, startup.*, daemon.lifecycle.*, etc.) is classified as higher priority and admitted ahead of any queued watcher.* waiter, bounding worst-case maintenance latency to "current hold + at most one more already-queued ingest hold" instead of "current hold + unbounded backlog". This only reorders *queued* admission - it does not preempt an actor that already holds the gate, so it does not fix the separate (larger, riskier) problem of a single ingest pass holding the gate for minutes; that remains tracked in polylogue-de2a as the harder writer-preemption/internal-chunking fix. The gate mirrors asyncio.Lock's cancellation-safety shape (a cancelled waiter always removes itself and, if not yet re-locked, forwards the wake to the next waiter) so a waiter cancelled exactly as it's woken never strands the grant - covered by a dedicated test that reproduces the race deterministically (release() then task.cancel() with no intervening await). Verification: tests/unit/daemon/test_write_coordinator.py (17 tests, including 3 new: actor-priority classification, priority-ordered admission under a simulated refilling backlog, and the wake-then-cancel race). Full tests/unit/daemon/ suite (1950 passed, 1 pre-existing unrelated failure - test_no_token_in_log_or_print_calls, a static scan flagging http.py/browser_capture/server.py, untouched by this change). mypy --strict polylogue/daemon/write_coordinator.py clean. ruff check + format clean. Ref polylogue-de2a
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
📝 WalkthroughWalkthroughThe daemon write coordinator replaces FIFO locking with a cancellation-safe priority gate. Bulk-ingest watcher actors receive lower admission priority, while maintenance actors can proceed ahead of queued watchers without preempting the current writer. ChangesPriority-aware write coordination
Estimated code review effort: 4 (Complex) | ~45 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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/write_coordinator.py`:
- Around line 59-117: Update the CancelledError handler in
_PriorityGate.acquire() to call _wake_next() only when the cancelled waiter’s
future was itself cancelled, not when it was already resolved with a grant. Use
fut.cancelled() to distinguish a wasted grant from cancellation of another
queued waiter, preventing multiple waiters from setting _locked simultaneously.
🪄 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: d53c3842-3033-4594-b603-2958e1390950
📒 Files selected for processing (2)
polylogue/daemon/write_coordinator.pytests/unit/daemon/test_write_coordinator.py
| class _PriorityGate: | ||
| """Single-holder async gate admitting the lowest-priority queued waiter first. | ||
|
|
||
| Mirrors ``asyncio.Lock``'s cancellation-safety shape (a waiter removes | ||
| itself from the wait set in all cases; a cancelled-after-woken waiter | ||
| re-triggers the wake so the grant is never silently dropped) but orders | ||
| waiters by ``(priority, sequence)`` instead of pure FIFO. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| self._locked = False | ||
| self._waiters: list[tuple[int, int, asyncio.Future[None]]] = [] | ||
| self._sequence = 0 | ||
|
|
||
| @property | ||
| def locked(self) -> bool: | ||
| return self._locked | ||
|
|
||
| async def acquire(self, priority: int) -> None: | ||
| if not self._locked and not self._waiters: | ||
| self._locked = True | ||
| return | ||
| loop = asyncio.get_running_loop() | ||
| fut: asyncio.Future[None] = loop.create_future() | ||
| self._sequence += 1 | ||
| entry = (priority, self._sequence, fut) | ||
| heapq.heappush(self._waiters, entry) | ||
| try: | ||
| await fut | ||
| except asyncio.CancelledError: | ||
| self._discard(entry) | ||
| if not self._locked: | ||
| self._wake_next() | ||
| raise | ||
| self._discard(entry) | ||
| self._locked = True | ||
|
|
||
| def release(self) -> None: | ||
| if not self._locked: | ||
| raise RuntimeError("_PriorityGate.release() called while not held") | ||
| self._locked = False | ||
| self._wake_next() | ||
|
|
||
| def _discard(self, entry: tuple[int, int, asyncio.Future[None]]) -> None: | ||
| try: | ||
| self._waiters.remove(entry) | ||
| except ValueError: | ||
| return | ||
| heapq.heapify(self._waiters) | ||
|
|
||
| def _wake_next(self) -> None: | ||
| while self._waiters: | ||
| _, _, fut = self._waiters[0] | ||
| if fut.done(): | ||
| heapq.heappop(self._waiters) | ||
| continue | ||
| fut.set_result(None) | ||
| return | ||
|
|
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
python3 - <<'PY'
import asyncio
import heapq
class _PriorityGate:
def __init__(self):
self._locked = False
self._waiters = []
self._sequence = 0
`@property`
def locked(self):
return self._locked
async def acquire(self, priority):
if not self._locked and not self._waiters:
self._locked = True
return
loop = asyncio.get_running_loop()
fut = loop.create_future()
self._sequence += 1
entry = (priority, self._sequence, fut)
heapq.heappush(self._waiters, entry)
try:
await fut
except asyncio.CancelledError:
self._discard(entry)
if not self._locked: # <-- current (unfixed) condition
self._wake_next()
raise
self._discard(entry)
self._locked = True
def release(self):
if not self._locked:
raise RuntimeError("not held")
self._locked = False
self._wake_next()
def _discard(self, entry):
try:
self._waiters.remove(entry)
except ValueError:
return
heapq.heapify(self._waiters)
def _wake_next(self):
while self._waiters:
_, _, fut = self._waiters[0]
if fut.done():
heapq.heappop(self._waiters)
continue
fut.set_result(None)
return
async def main():
gate = _PriorityGate()
await gate.acquire(0) # holder
async def w(name, box):
await gate.acquire(0)
box.append(name)
r1, r3 = [], []
t1 = asyncio.create_task(w("W1", r1))
t2 = asyncio.create_task(w("W2", []))
t3 = asyncio.create_task(w("W3", r3))
await asyncio.sleep(0) # let all three enqueue
# Cancel W2 (a non-top, still-pending waiter) BEFORE releasing, so its
# cancellation wakeup is scheduled ahead of W1's grant wakeup.
t2.cancel()
gate.release()
for _ in range(5):
await asyncio.sleep(0)
double_grant = bool(r1) and bool(r3)
print("W1 acquired:", bool(r1), "W3 acquired:", bool(r3))
print("DOUBLE GRANT BUG REPRODUCED:", double_grant)
for t in (t1, t2, t3):
if not t.done():
t.cancel()
await asyncio.gather(t1, t2, t3, return_exceptions=True)
asyncio.run(main())
PYRepository: Sinity/polylogue
Length of output: 224
Double-grant _PriorityGate bug in _PriorityGate.acquire() cancellation handler
Canceling a non-top waiter while an earlier waiter has already been granted but not yet resumed triggers _wake_next() again; the already-resolved waiter is cleaned up and another waiter gets a grant, letting both resumed waiters set self._locked = True. Scope the wake-forward logic to the actual wasted grant by checking not fut.cancelled(): a forcibly cancelled waiter whose future already had a result has fut.cancelled() == False.
🤖 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/write_coordinator.py` around lines 59 - 117, Update the
CancelledError handler in _PriorityGate.acquire() to call _wake_next() only when
the cancelled waiter’s future was itself cancelled, not when it was already
resolved with a grant. Use fut.cancelled() to distinguish a wasted grant from
cancellation of another queued waiter, preventing multiple waiters from setting
_locked simultaneously.
Source: Path instructions
…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
DaemonWriteCoordinatorserialized every writer through a plainasyncio.Lock(strict FIFO). Replaced it with a_PriorityGatethat admits queued waiters by(priority, arrival order)instead of pure FIFO.watcher.*naming convention (maintenance.*,startup.*,daemon.lifecycle.*, etc.) is classified as higher priority and admitted ahead of any queuedwatcher.*waiter.Problem
Under a sustained live-watcher catch-up backlog,
watcher.*chunk requests re-queue almost immediately after each release, so a periodic maintenance actor (FTS merge, WAL checkpoint, raw-materialization convergence) that only wakes every N seconds could get stuck behind an ever-refilling line of ingest waiters. This starvedpolylogue-de2a'sauto_resolve_stale_plan_blockerspass (polylogue-d7im) and letmessages_fts_databalloon to 705K rows during a live incident (2026-07-26): a single 14-minute ingest hold plus continuous re-queueing left FTS merge with no turn for an extended period.Solution
Priority-ordered admission bounds worst-case maintenance latency to "current hold + at most one more already-queued ingest hold" instead of "current hold + unbounded backlog". This only reorders queued admission - it does not preempt an actor that already holds the gate, so it does not fix the separate (larger, riskier) problem of a single ingest pass holding the gate for minutes; that remains tracked in
polylogue-de2aas the harder writer-preemption/internal-chunking fix.The gate mirrors
asyncio.Lock's cancellation-safety shape (a cancelled waiter always removes itself and, if not yet re-locked, forwards the wake to the next waiter) so a waiter cancelled exactly as it's woken never strands the grant - covered by a dedicated test reproducing the race deterministically (release()thentask.cancel()with no interveningawait).Verification
tests/unit/daemon/test_write_coordinator.py: 17 tests (3 new - actor-priority classification, priority-ordered admission under a simulated refilling backlog, wake-then-cancel race)tests/unit/daemon/suite: 1950 passed, 1 pre-existing unrelated failure (test_no_token_in_log_or_print_calls, a static scan flagginghttp.py/browser_capture/server.py, untouched by this change)mypy --strict polylogue/daemon/write_coordinator.py: cleanruff check+format: cleanRef polylogue-de2a
Summary by CodeRabbit