Skip to content

perf(storage): skip re-indexing already-applied append-chain positions - #3358

Merged
Sinity merged 2 commits into
masterfrom
feature/perf/skip-already-applied-append-replay
Jul 27, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/perf/skip-already-applied-append-replay

Conversation

@Sinity

@Sinity Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner

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

Sinity and others added 2 commits July 27, 2026 22:55
Problem: polylogue-de2a observed the live watcher's writer gate held for
860s and, in one case, 9297s (2.6h) processing a single modest append.
Root-caused via SQL-level trace: apply_raw_revision_replay's write loop
re-runs _index_parsed_for_retained_raw for EVERY raw_id in
plan.accepted_raw_ids on every call, including every historical raw
already durably indexed by an earlier successful replay of the same
byte chain. append_ingest.py's live-watcher hot path always passes the
full accumulated chain (not just the new tail), so a long-lived session
accumulating N small live appends pays O(N) redundant historical writes
on its Nth append and O(N^2) cumulatively over its lifetime. Those
writes use INSERT OR REPLACE against messages/blocks, which re-fires
messages_fts insert triggers for content that never changed -- exactly
the FTS-segment-bloat/writer-hold spiral this bead already diagnosed
from live evidence (messages_fts_data at 705K rows, #1851 automerge).
While this write held the daemon's sole writer lock, every other
periodic actor (FTS merge, WAL checkpoint, convergence) was starved for
the entire hold, per DaemonWriteCoordinator's single-holder design
(prior fast-follows in this bead: PR #3288 shortened the FTS-merge
interval, PR #3289 added maintenance-actor queue priority; neither
bounds an already-admitted single hold).

What changed: apply_raw_revision_replay gains skip_already_applied
(default False, so every existing caller is byte-for-byte unchanged).
When True, it looks up the logical source's current
raw_revision_heads.accepted_raw_id BEFORE any clearing and skips the
index write for every accepted_raw_ids entry at or before that
position -- only the new tail is actually written. Only
append_ingest.py's live per-append hot path opts in; the
backfill/restore/membership replay call sites keep full self-healing
re-apply (their content may predate a parser fix and legitimately need
every historical position rewritten, and they run far less often than
a live append). session_id for skipped positions is derived
deterministically from the already-parsed content instead of the
write result.

Verification:
- devtools test tests/unit/storage/test_revision_replay.py -- 26 passed,
  including two new tests: one proving only the newest tail position
  reaches _index_parsed_for_retained_raw across three sequential
  appends onto a growing chain (with correctness of the final merged
  content and head unaffected), and one pinning that callers not
  opting in (skip_already_applied unset) still re-index the whole
  chain, 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.
- tests/integration/test_append_cohort_memory.py and
  tests/integration/test_live_read_amplification.py::TestRestartedCursorReconcile
  each have one pre-existing failure verified identical on unmodified
  master (git stash) before and after this change -- unrelated to this
  fix, not introduced by it.

Remaining polylogue-de2a scope: no genuine preemption/yield mechanism
for an already-admitted single-actor writer hold exists yet (a mid-hold
SQLite transaction can't safely release the async gate without also
releasing the real DB-level lock). This fix removes the dominant O(n^2)
cost driver instead, which is the mechanism that produced the
860s/9297s pathological holds in the first place; a genuinely
unbounded slow stage (not driven by chain replay) would still need a
future preemption design.

Ref polylogue-de2a

Co-Authored-By: Claude <[email protected]>
Problem: devtools/render_docs_surface.py had drifted from the current
ruff formatter's line-wrapping (a generator-expression argument that no
longer fit the line width), which failed `ruff format --check` and, in
turn, `devtools render docs-surface` (README.md's generated table was
stale relative to it). This is pre-existing on origin/master, unrelated
to this branch's actual change, but the pre-push hook runs
`devtools verify --quick` and blocks ALL pushes while it fails.

What changed: `ruff format devtools/render_docs_surface.py` +
`devtools render docs-surface` to regenerate README.md. No logic
change.

Verification: devtools verify --quick exits 0.

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 seconds

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 721a5251-53bb-4272-bf2d-a6c68a54746a

📥 Commits

Reviewing files that changed from the base of the PR and between ffd7ff7 and f2c96ec.

📒 Files selected for processing (5)
  • README.md
  • devtools/render_docs_surface.py
  • polylogue/sources/live/append_ingest.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/storage/test_revision_replay.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/skip-already-applied-append-replay

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.

@Sinity
Sinity merged commit b5f4078 into master Jul 27, 2026
3 checks passed
@Sinity
Sinity deleted the feature/perf/skip-already-applied-append-replay branch July 27, 2026 21:04
Sinity added a commit that referenced this pull request Aug 2, 2026
#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]>
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