Skip to content

fix(maintenance): enforce rebuild pass deadlines inside replay work - #3494

Merged
Sinity merged 2 commits into
masterfrom
perf/rebuild-deadline-and-phase-receipts
Jul 31, 2026
Merged

Sinity merged 2 commits into
masterfrom
perf/rebuild-deadline-and-phase-receipts

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

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]

Sinity and others added 2 commits August 1, 2026 00:34
Problem: rebuild_index_from_source checked a bounded pass's deadline only
AFTER the whole page's replay_source() call (census + every cohort +
planner-stats refresh) returned. Live recovery evidence: operation
3f8fa7b0 configured pass_deadline_ms=300000, yet 100-row pages ran
roughly 8-9 minutes -- the advertised bounded-pass contract was not
enforced at the work boundary. A page can also expand into a much
larger authority cohort, making the overshoot unbounded in the worst
case.

What changed: backfill_historical_revision_evidence
(sources/revision_backfill.py) now accepts an optional deadline_check
callback, invoked 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. It is expected to raise the new
RebuildDeadlineExceededError to interrupt. maintenance/replay.py
threads the parameter through unchanged.

rebuild_index.py builds a deadline_check closure from the resumable
transaction's pass_deadline_ms and 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, which is safe
by the existing content-hash idempotency invariant (re-applying an
already-committed cohort is a no-op upsert, never a duplicate) and
matches the crash-recovery contract an open replay batch already has.
The deferred receipt is zero-shaped like a normal replay dict 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.

This diff also carries polylogue-6mvg's small remaining slice
(RebuildPassCost.selection_s + the selection-phase timing measurement
around next_raw_page/select_rebuild_raw_ids) because it shares the
same function bodies as the deadline fix above and could not be split
into a separate commit without fragmenting a single hunk; see the
following commit for its dedicated test.

Alternatives rejected: proactive page-sizing against a throughput
estimate (checks only BEFORE a page, not between cohorts inside it,
so still misses the description's own worst case) and per-raw
interruption inside apply_raw_revision_replay itself (would need to
interrupt mid-transaction-write, corrupting the owned-inactive-
generation state) -- both noted as considered-and-deferred in the
bead's own prior investigation.

Verification: devtools test tests/unit/maintenance/test_rebuild_index_deadline.py
tests/unit/maintenance/test_rebuild_index_phase_timing.py
tests/unit/storage/test_incremental_rebuild_equivalence.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 -- 213 passed.
devtools verify --quick -- all 18 steps ok, exit 0.

Ref polylogue-uhgm
Ref polylogue-6mvg

Co-Authored-By: Claude <[email protected]>
Problem: polylogue-6mvg's remaining scope after prior sibling beads
(planner stats #3141, byte-skip #3146, batched commits #3147, pool
floor #3149, dedup #3151) was durable phase-timing telemetry -- a live
full rebuild spent ~86s of one CPU core choosing which raws to replay
before the inactive generation held a single session, with nothing
durable recording where that time went. The prior commit on this
branch already added RebuildPassCost.selection_s and the matching
"selection_s" key on the terminal/materialized receipt's timings_s
(extending the existing timings_s/RebuildPassCost vocabulary rather
than inventing a parallel one -- see polylogue-o56w's terminal.*
stages and the existing parse_s/apply_s split it sits beside).

What changed: this commit adds the dedicated test coverage for that
addition, both on the one-shot "replayed" receipt path and on a
resumable pass's "deferred" pass-cost receipt, proving the same key
appears on every receipt shape.

Anti-vacuity: the production caller exercised is
rebuild_index_from_source_sync (the real offline-rebuild
orchestrator, no reimplementation). The mutation that makes these
tests fail is reverting the selection_elapsed_s measurement or its
selection_s=selection_elapsed_s threading into RebuildPassCost /
terminal_timings_s in rebuild_index.py -- the "selection_s" key would
then be absent from receipt.timings_s entirely (KeyError via
dict indexing), not merely zero.

Verification: devtools test tests/unit/maintenance/test_rebuild_index_phase_timing.py -- 2 passed.

Ref polylogue-6mvg

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 31, 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: 25 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 Plus

Run ID: 27aad0fe-f36d-4b56-8fa1-37b54a432dba

📥 Commits

Reviewing files that changed from the base of the PR and between d8d6a37 and f09600e.

📒 Files selected for processing (6)
  • polylogue/maintenance/rebuild_index.py
  • polylogue/maintenance/replay.py
  • polylogue/sources/revision_backfill.py
  • tests/unit/cli/test_archive_maintenance_cli.py
  • tests/unit/maintenance/test_rebuild_index_deadline.py
  • tests/unit/maintenance/test_rebuild_index_phase_timing.py

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 4ab9dcf into master Jul 31, 2026
3 checks passed
@Sinity
Sinity deleted the perf/rebuild-deadline-and-phase-receipts branch July 31, 2026 22:42
Sinity added a commit that referenced this pull request Jul 31, 2026
Rebased perf/sharded-from-empty-rebuild onto origin/master (merged since
branch point: #3494 deadline_check, #3496 pipeline-decode pin, #3497
conversational-evidence gate, #3498 lineage fixture fix). Conflicts
resolved in rebuild_index.py by keeping both #3494's mid-replay deadline
checkpointing (non-sharded path) and this PR's shard dispatch, with
shard_count>1 + pass_deadline_seconds explicitly rejected (validator and
CLI) since the sharded path has no deadline_check seam yet.

Ref polylogue-pzxm

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