Skip to content

perf(sources): batch replay-phase index+source commits across cohorts - #3147

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/replay-commit-batching
Jul 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/replay-commit-batching

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

Extends polylogue-amg1's commit-batching to the replay phase. amg1 (PR #3136) batched the CENSUS phase's per-raw source.db commits but deliberately left the REPLAY phase's per-cohort index.db commit + per-raw terminal source.db marker commit unbatched, because a naive multi-cohort batch risked inverting a pinned crash-recovery ordering invariant. This PR does the deferred redesign: commit_batch_size now also batches replay commits across multiple independent cohorts, while preserving the invariant at batch granularity.

Problem

backfill_historical_revision_evidence's replay loop calls ArchiveStore.apply_raw_revision_replay (and apply_raw_membership_classification) once per logical-source cohort. Each call self-committed index.db immediately (with self._conn:), then looped over terminal raw ids calling mark_raw_parse_succeeded — an independent, immediate source.db commit per raw. For amg1's own benchmark shape (independent single-session raws, cohort size == 1), this meant the replay phase still committed once per raw on BOTH tiers — the larger lever amg1's own notes explicitly named and deferred to this bead (polylogue-oikv), pending its own adversarial review of the crash-recovery stakes.

Solution

  • ArchiveStore.apply_raw_revision_replay / apply_raw_membership_classification gain a manage_transaction: bool = True parameter, following the exact with conn if manage_transaction else nullcontext() pattern amg1 already established for census (replace_raw_membership_census, bind_raw_revision). When False, the cohort's index.db writes stay in the caller's open transaction, and its terminal parse-state marker is pushed onto the existing _pending_raw_parse_states queue instead of committing immediately via mark_raw_parse_succeeded.
  • backfill_historical_revision_evidence's existing commit_batch_size parameter now governs BOTH phases: a commit_replay_unit() closure (mirroring census's own) fires archive.commit() every commit_batch_size cohorts across the byte-cohort and membership-classification loops, plus a final flush commit after both loops. None (the default) preserves the exact original per-cohort commit behavior for every existing caller.
  • Why the invariant still holds: ArchiveStore.commit() already commits the index connection before flushing pending source markers (_flush_pending_raw_parse_states). Batching multiple cohorts into one shared commit() call means the ordering invariant now holds at BATCH granularity instead of per-cohort: a crash anywhere in an open (uncommitted) batch discards every cohort in that batch — index writes and terminal markers together, since neither side ever committed (SQLite implicitly rolls back an uncommitted transaction when the connection closes) — never a partial batch, and a resume reprocesses every lost cohort from scratch with zero duplication.
  • The rare non-terminal "incomplete cohort" NULL-reset branch in apply_raw_membership_classification (a sibling member still undecided) is left immediately-committing regardless of batching — it's a correction path, not a terminal marker, out of scope for this bead.
  • repair_raw_materialization's docstring is updated to note its per-component call shape (selected_raw_ids=[raw_id]) means this daemon loop sees minimal cross-cohort benefit; the wider selected_raw_ids=None CLI rebuild-index path is where the batching pays off — same caveat lane I (polylogue-nh44) already documented for census.

Acceptance criteria (polylogue-oikv)

  • Design decision recorded (this PR body): the new batch-boundary invariant is "index commits, then source terminal markers commit" at BATCH granularity, equivalent-or-stronger than the prior per-cohort invariant (still index-before-source, just deferred over N cohorts) — satisfied.
  • Both existing crash-recovery tests (test_backfill_resumes_after_index_receipt_commits_before_source_terminal, test_backfill_resumes_after_only_some_source_markers_commit) pass unmodified — satisfied; they call backfill_historical_revision_evidence with no commit_batch_size, so default (None → unbatched) behavior is byte-for-byte unchanged.
  • New crash-mid-batch test (test_backfill_resumes_after_replay_batch_crash_discards_whole_batch_cleanly) proves a fault between two cohorts in the same batch discards the whole batch cleanly — satisfied; also verified non-vacuous by temporarily forcing replay_batched=False and confirming the same assertion fails (5 != 4).
  • Benchmark shows measurable additional speedup beyond amg1's 1.05x-1.34x ceiling — satisfied (below).

Verification

  • devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_repair.py tests/unit/devtools/test_raw_authority_restart_proof.py tests/unit/devtools/test_raw_authority_scale_proof.py — 105 passed.
  • Broader sweep devtools test -k "raw_authority or raw_materialization or revision_backfill or revision_replay" — 190 passed, 1 pre-existing unrelated failure (test_live_multi_session_divergence_reopens_raw_authority in test_live_batch_support.py, already documented by amg1's own notes as failing identically on clean master with none of this bead's/amg1's changes present).
  • mypy --strict clean on archive.py, revision_backfill.py, repair.py, and the test file.
  • devtools verify --quick (format+lint+mypy+render-all-check) — clean.
  • Ad-hoc before/after benchmark (tests/infra/revision_backfill_benchmark.py fixtures, not committed — same convention amg1 used), commit_batch_size=None vs 20 (production default RAW_MATERIALIZATION_COMMIT_BATCH_SIZE), median of 3 runs each:
    • SMALL_PAYLOAD_SHAPE (200 raws, ~50KB avg): 11.734s → 5.453s, 2.15x
    • LARGE_PAYLOAD_SHAPE (80 raws, ~1.7MB avg): 9.743s → 7.492s, 1.30x

Ref polylogue-oikv

Problem: polylogue-amg1 (PR #3136) batched the census phase's per-raw
source.db commits but deliberately left the replay phase's per-cohort
index.db commit + per-raw terminal source.db marker commit unbatched --
apply_raw_revision_replay/apply_raw_membership_classification each self-
committed once per cohort/raw, because a naive multi-cohort batch risked
inverting the crash-recovery invariant pinned by
test_backfill_resumes_after_index_receipt_commits_before_source_terminal
and test_backfill_resumes_after_only_some_source_markers_commit ("index
commits, then source terminal marker commits").

Solution: extend ArchiveStore.apply_raw_revision_replay and
apply_raw_membership_classification with the same manage_transaction=False
/ nullcontext() pattern amg1 already used for census, routing terminal
parse-state markers through the existing _pending_raw_parse_states queue
instead of committing immediately. backfill_historical_revision_evidence's
existing commit_batch_size parameter now also batches the replay loops
(byte-cohort + membership), via a commit_replay_unit() closure mirroring
census's own, with a final flush commit after both loops. archive.commit()
already commits index.db before flushing pending source markers, so the
ordering invariant holds unchanged -- just at BATCH granularity instead of
per-cohort: a crash anywhere in an open batch discards every cohort in
that batch (neither side committed), never a partial batch, and resume
reprocesses cleanly with zero duplication. Default (commit_batch_size=None)
preserves the exact original per-cohort commit behavior for every existing
caller, so the two pinned tests pass unmodified.

New test_backfill_resumes_after_replay_batch_crash_discards_whole_batch_cleanly
proves the batched invariant (crash on cohort 6 of a 10-cohort/batch-size-4
run: exactly 4 sessions/4 parsed markers survive, resume converges to 10/10
with zero duplicate application receipts); verified non-vacuous by
temporarily forcing replay_batched=False and confirming the same assertion
fails (5 != 4).

Benchmarked before/after with tests/infra/revision_backfill_benchmark.py's
SMALL_PAYLOAD_SHAPE (200 raws/~50KB) and LARGE_PAYLOAD_SHAPE (80 raws/~1.7MB),
commit_batch_size=None vs 20 (production default), median of 3 runs:
- SMALL: 11.734s -> 5.453s, 2.15x speedup
- LARGE: 9.743s -> 7.492s, 1.30x speedup
Both exceed amg1's own committed 1.05x-1.34x ceiling.

Verification: devtools test tests/unit/sources/test_revision_backfill.py
tests/unit/storage/test_repair.py tests/unit/devtools/test_raw_authority_restart_proof.py
tests/unit/devtools/test_raw_authority_scale_proof.py -- 105 passed. mypy
--strict clean on archive.py/revision_backfill.py/repair.py/test file.
devtools verify --quick clean. Broader -k "raw_authority or raw_materialization
or revision_backfill or revision_replay" sweep: 190 passed, 1 pre-existing
unrelated failure (test_live_multi_session_divergence_reopens_raw_authority,
already documented by amg1 as failing identically on clean master).

Ref polylogue-oikv

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 19, 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: 12 minutes

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

Run ID: b7cc62c2-f31b-4798-b740-ce4aea0d1f6b

📥 Commits

Reviewing files that changed from the base of the PR and between 1f77d5d and af8273e.

📒 Files selected for processing (4)
  • polylogue/sources/revision_backfill.py
  • polylogue/storage/repair.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/sources/test_revision_backfill.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/replay-commit-batching

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.

@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.

@Sinity
Sinity merged commit 99c8686 into master Jul 19, 2026
3 checks passed
@Sinity
Sinity deleted the feature/perf/replay-commit-batching branch July 19, 2026 03:50
Sinity added a commit that referenced this pull request Jul 31, 2026
…3494)

## Summary

Two beads, one branch: (1) a P1 correctness-of-contract bug fix — a
resumable
rebuild pass's deadline is now checked *between* REPLAY-phase cohorts,
not
only after the whole page's replay call returns — and (2) the small
remaining
slice of a P2 observability bead, a durable "selection phase" timing on
every
rebuild receipt.

## Problem

**polylogue-uhgm** (P1): live recovery evidence — operation `3f8fa7b0`
configured `pass_deadline_ms=300000` (5 minutes), yet 100-row pages ran
roughly 8-9 minutes, because `rebuild_index_from_source`
(`maintenance/rebuild_index.py`) checked elapsed time only *after*
`replay_source(...)` — the whole page's census + every cohort +
planner-stats
refresh — returned. A page can also expand into a much larger authority
cohort, making the overshoot unbounded in the worst case. The advertised
bounded-pass contract was not enforced at the work boundary.

**polylogue-6mvg** (P2, remaining slice): a live full index rebuild
spent
~86s of one CPU core selecting which raws to replay before the inactive
generation held a single session, and nothing durable recorded where
that
time went. Most of this bead's original scope (planner stats #3141,
byte-skip #3146, batched commits #3147, pool floor #3149, dedup #3151)
had
already shipped via sibling beads; the bead's own notes call out durable
phase-timing telemetry — specifically a selection-phase breakdown — as
the
one still-unowned piece.

## Solution

- `polylogue/sources/revision_backfill.py`:
`backfill_historical_revision_evidence`
gains an optional `deadline_check: Callable[[], None] | None` parameter,
  called at the top of every REPLAY-phase cohort iteration (both the
byte-cohort and membership-cohort loops) — between cohorts, not only
after
the whole call returns. New `RebuildDeadlineExceededError` is the
expected
  interrupt signal.
- `polylogue/maintenance/replay.py`: threads `deadline_check` through
  unchanged to `backfill_historical_revision_evidence`.
- `polylogue/maintenance/rebuild_index.py`:
- Builds a `_check_pass_deadline` closure from the resumable
transaction's
`pass_deadline_ms`, wired only when a durable transaction exists (never
for non-resumable `--raw-id`/`--only-missing`/`--max-blob-mb`
selections,
    matching existing validation).
- Catches `RebuildDeadlineExceededError` around the `replay_source()`
call.
    On interrupt it deliberately does **not** advance the transaction's
cursor/processed counters — the next pass re-derives from the exact same
    source-order position, safe by the existing content-hash idempotency
invariant (re-applying an already-committed cohort is a no-op upsert,
never a duplicate) and consistent with the crash-recovery contract an
    open replay batch already has.
- The deferred receipt's `replay` dict is zero-shaped like a normal
replay
    dict (not a bare marker), so every existing consumer that indexes
replay-dict keys unconditionally (the daemon-mode CLI text formatter,
the
    daemon HTTP route's raw `receipt.to_dict()` response) keeps working.
- `RebuildPassCost.selection_s` (polylogue-6mvg) extends the *existing*
timings vocabulary — the same `RebuildPassCost`/`timings_s` shape every
    other phase (`parse_s`/`apply_s`, the `terminal.*` stages from
    polylogue-o56w) already uses — rather than inventing a parallel one.
    Measured around `next_raw_page` (resumable path) and
    `select_rebuild_raw_ids` (one-shot path), threaded into all three
    receipt-building call sites (deadline-interrupt, deferred/paused
    post-hoc, final materialized).

**Alternatives rejected:** proactive page-sizing against a throughput
estimate (checks only *before* a page starts, so still misses a
mid-page-expanding cohort — the exact worst case the bead names) and
per-raw interruption inside `apply_raw_revision_replay` itself (would
interrupt mid-transaction-write, risking corruption of the
owned-inactive-
generation state). Both were flagged and deliberately deferred in the
bead's own prior investigation as too risky for the intended scope.

## Conflict avoidance note for the merge conductor

`polylogue/sources/revision_backfill.py` is flagged as owned by another
live
lane. This PR's addition there is the smallest possible: one new
exception
class, one new optional parameter, and two `if deadline_check is not
None:
deadline_check()` call sites at the top of the two existing cohort loops
—
no other line touched. The branch was rebased onto current `master`
(`90d4df67e`, which includes the sibling lane's `polylogue-5q2u`
lineage-order
replay change, `_lineage_aware_replay_order`); the rebase conflict was
exactly the loop header line and was resolved by keeping the new
`ordered_logical_keys` iteration and re-adding the `deadline_check()`
call —
verified with a fresh test run post-rebase.

## Acceptance-criteria matrix

**polylogue-uhgm:**
- "A transaction with a short pass deadline stops before starting work
that
  would exceed its remaining budget, commits a valid cursor, and reports
deadline deferral." — **Satisfied.**
`test_rebuild_index_deadline_stops_mid_page_and_resumes_without_omission_or_duplication`.
- "Restarting resumes exactly at the next source-order raw/cohort with
no
duplicates or omissions." — **Satisfied** (by construction: the cursor
is
never advanced on interrupt, and resumption re-derives from the
identical
keyset position; idempotent re-application makes any redone cohort
safe).
Proven end-to-end by the same test (interrupted pass → resume → exact
final
  session count).
- "A deliberately slow/expanded cohort proves the deadline is checked
inside
production replay work rather than only after the outer call returns." —
**Satisfied.**
`test_deadline_check_invoked_between_replay_cohorts_not_only_after_return`
proves the interrupt fires after exactly one cohort durably commits (not
zero, not all three) at the direct
`backfill_historical_revision_evidence`
  boundary.
- "Final terminal readiness checks remain exact and either have their
own
bounded receipt or are explicitly separately scheduled." —
**Unchanged**:
no terminal-stage code was touched; `terminal.*` timings
(polylogue-o56w)
  remain as before.

**polylogue-6mvg** (remaining slice only — full bead AC already
satisfied by
sibling beads per its own 2026-07-19/27 notes):
- Durable selection-phase timing receipt — **Satisfied.**
  `RebuildPassCost.selection_s` / `terminal_timings_s["selection_s"]`,
  present on every receipt shape (deferred, paused, replayed).
- Cohort/parse/write/insight phase timings — **Already delivered** by
prior
work (`stage_timings_s` from `revision_backfill.py`, `parse_s`/`apply_s`
  split, `terminal.*` stages) — not re-touched here.
- Daemon catch-up shares the improvement — **Satisfied by
construction**:
`daemon/bulk_rebuild.py`'s `run_daemon_bulk_rebuild_pass` returns the
exact
same `RebuildIndexReceipt` from the same
`rebuild_index_from_source_sync`
  engine, so both the deadline fix and the selection-phase timing apply
  automatically with zero daemon-side changes needed.

## Anti-vacuity

- Deadline fix: production caller is `rebuild_index_from_source_sync`
(the
real offline/daemon rebuild engine, no reimplementation). The mutation
that
makes
`test_deadline_check_invoked_between_replay_cohorts_not_only_after_return`
fail is moving the `deadline_check()` calls out of the cohort loops back
to
a single call after `backfill_historical_revision_evidence` returns (the
  pre-fix bug shape) — the mock would then never be called before the
  function's own natural completion. The mutation that makes

`test_rebuild_index_deadline_stops_mid_page_and_resumes_without_omission_or_duplication`
fail is either reverting to the post-hoc-only check (the fake clock
would
  never interrupt anything mid-replay, so the first pass would report
`status="replayed"` instead of `"deferred"`) or advancing the
transaction's
cursor on interrupt (the resumed pass would then skip or duplicate a
raw,
  and the final session count would not equal 3).
- Phase timing: production caller is the same
`rebuild_index_from_source_sync`.
The mutation that makes `test_rebuild_index_phase_timing.py`'s two tests
  fail is reverting `selection_elapsed_s`'s measurement or its
`selection_s=selection_elapsed_s` threading — the `"selection_s"` key
would
then be absent from `receipt.timings_s` (a dict-key assertion failure,
not
  merely a zero value).

## Verification

```
python -m devtools test tests/unit/maintenance/test_rebuild_index_deadline.py \
  tests/unit/maintenance/test_rebuild_index_phase_timing.py \
  tests/unit/daemon/test_bulk_rebuild_ownership.py \
  tests/unit/cli/test_archive_maintenance_cli.py \
  tests/unit/daemon/test_route_contracts.py \
  tests/unit/maintenance/test_rebuild_index_bulk_build.py \
  tests/unit/maintenance/test_rebuild_index_ownership.py \
  tests/unit/maintenance/test_rebuild_index_selection.py \
  tests/unit/maintenance/test_rebuild_parse_apply_split.py \
  tests/unit/storage/test_index_generation.py
# 212 passed
python -m devtools verify --quick
# exit_code: 0, all 18 steps ok
```

**Known pre-existing failure, unrelated to this branch** — filed as
`polylogue-s0ug`:

`tests/unit/storage/test_incremental_rebuild_equivalence.py::test_incremental_restart_and_fresh_generation_rebuild_are_equivalent`
fails deterministically on current `origin/master` (`90d4df67e`) in
isolation,
introduced by `0d27e3da7` (#3484, tightened Codex CONTINUATION lineage
evidence) landing after this branch was cut — the test's hand-built
fixture
predates that tightening. `git diff origin/master...HEAD` for this
branch
touches neither `codex.py`, `revision_backfill.py`'s classification
logic,
nor that test file, confirming it is not caused by this change.

Not run: `devtools verify` (full testmon suite) — the coordinator
directed a
synchronous quick-gate + focused-test path instead of the backgrounded
testmon seed, since a fresh worktree has no testmon seed to run the
default
affected-selection path against.

Ref polylogue-uhgm
Ref polylogue-6mvg

Co-Authored-By: Claude <[email protected]>

---------

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