Skip to content

fix(daemon): bound raw-materialization writer holds by wall-clock time - #3534

Merged
Sinity merged 1 commit into
masterfrom
feature/daemon/raw-materialization-pass-time-budget
Aug 2, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/daemon/raw-materialization-pass-time-budget

Conversation

@Sinity

@Sinity Sinity commented Aug 2, 2026

Copy link
Copy Markdown
Owner

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 perf(daemon): give maintenance actors priority over bulk-ingest waiters #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.

Problem: the daemon's ordinary raw-materialization trickle pass held the
process-wide writer coordinator for 188-210s per call in live measurement
(polylogue-de2a), starving FTS merge, session insights, and convergence-debt
retry for minutes even though those actors want a 60s cadence. The existing
per-call component count limit (16-64) did not bound this: per-component cost
(parse, replay, then a full FTS/action-pairs/delegation-facts rebuild) is
itself expensive enough that a modest component count still produced
multi-minute holds.

Solution: repair_raw_materialization gains an optional max_pass_seconds
budget (polylogue/storage/repair.py). 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 rather than an unsafe mid-write yield -- and always complete at
least one component regardless of the budget, so a single slower-than-budget
component still makes forward progress. Components skipped by the replay
loop's budget get an explicit RETRYABLE outcome (finalize_raw_authority_census
is fail-closed on every selected plan having a recorded outcome, so a silent
gap there is not safe). The daemon's ordinary drain pass
(_drain_raw_materialization_once) now passes a declared
_RAW_MATERIALIZATION_MAX_PASS_SECONDS = 20.0 through
polylogue/product/raw_authority.py's repair_materialization wrapper; the
whale pass (a deliberately unbounded single-component escalation tier) is
untouched. New metrics raw_materialization_pass_seconds and
raw_materialization_time_budget_exceeded make the bound's effect observable
per pass, alongside the existing hold/wait metrics in
daemon/write_coordinator.py.

This satisfies AC3 (yield at declared checkpoints) and, combined with the
already-shipped maintenance-priority admission (PR #3289), materially
tightens AC2 (worst-case queued-actor wait is now roughly this pass's budget
plus at most one more already-queued, equally-bounded ingest hold, instead of
an unbounded multi-minute wait). AC1 (hold/wait measurement) was already
satisfied by write_coordinator.py. Live re-measurement under a comparable
backlog (AC4) is not done in this PR -- it requires a deployed daemon and is
tracked as 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 (same 11 fail
identically on origin/master with none of this branch's changes applied;
unrelated "no messages, no positive conversational evidence" parser-refusal
drift in test fixtures, out of scope for this bead). devtools verify --quick
passes (ruff format/check, mypy --strict, render all --check, layering,
schema-versioning, all other quick gates).

Ref polylogue-de2a

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

coderabbitai Bot commented Aug 2, 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: 56 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: d0558343-4e87-4547-a87d-a6c762159408

📥 Commits

Reviewing files that changed from the base of the PR and between 1059339 and f875ddd.

📒 Files selected for processing (5)
  • polylogue/daemon/cli.py
  • polylogue/product/raw_authority.py
  • polylogue/storage/repair.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/storage/test_repair.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 0830a9f into master Aug 2, 2026
3 checks passed
@Sinity
Sinity deleted the feature/daemon/raw-materialization-pass-time-budget branch August 2, 2026 10:16
Sinity added a commit that referenced this pull request Aug 2, 2026
)

## Summary

Applies the same bounded-pass technique polylogue-de2a shipped for the
daemon's `raw_materialization` actor (PR #3534, `max_pass_seconds`,
merged same day this bead's measurement window predates) to a second,
still-unbounded writer-holding actor: `maintenance.drive_catchup`.

## Problem

polylogue-qlae's journal aggregation (2026-07-29 to 2026-07-31)
measured:

- `maintenance.raw_materialization` hold_max=21,433.6s -- the actor
de2a's PR #3534 bounded via `max_pass_seconds=20.0`. That PR merged
2026-08-02, the same day as this measurement window's upper bound; this
bead's specific number predates re-verification against the fix and
should not be treated as still-live without a fresh live re-measurement
(explicitly called out as AC4/follow-up in #3534's own PR body).
- `maintenance.drive_catchup` hold_max=18,623s -- a **different** actor,
not touched by de2a, confirmed still unbounded by reading
`_periodic_drive_source_catchup` / `_run_drive_source_catchup_once`
(`polylogue/daemon/cli.py`): the entire Drive acquire+parse pass runs
inside one `coordinator.run("maintenance.drive_catchup", ...)` call with
no internal checkpoint.
- During these holds, every other maintenance actor starved for hours
(heartbeat waited up to 17,042s, `wal_checkpoint` 17,642s, `fts_merge`
17,882s, `watcher.catch_up.prefilter` 20,298s).

`DaemonWriteCoordinator`'s priority classes
(`write_coordinator.py:44-56`) bound queue *order*, not the *duration*
of an already-admitted hold -- this is the same structural gap de2a's
own analysis already established.

## Solution

- `parse_from_raw` and `ingest_sources`
(`polylogue/pipeline/services/parsing_workflow.py`) gain an optional
`max_pass_seconds: float | None = None` parameter, byte-for-byte
unchanged for existing callers. `ParsingService.parse_from_raw` /
`.ingest_sources` (`polylogue/pipeline/services/parsing.py`) thread it
through.
- `parse_from_raw` already batches raw ids by `raw_batch_size` /
blob-byte budget (`_iter_raw_id_batches`) -- a genuine write/transaction
boundary, structurally identical to raw-materialization's per-component
checkpoint. Elapsed time is checked only *between* batches, and each
branch always completes at least one batch before the budget is
enforced, so a single slower-than-budget batch still makes forward
progress instead of stalling.
- `ParseResult` gains `time_budget_exceeded: bool` so callers can
observe an early stop.
- `polylogue/daemon/cli.py`'s `_run_drive_source_catchup_once` passes a
declared `_DRIVE_CATCHUP_MAX_PASS_SECONDS = 20.0` (matching de2a's
constant) and logs when a pass yields early. Raw ids left unattempted
this call stay ordinary parse backlog, recomputed by
`collect_parse_backlog`/`collect_validation_backlog` on the next
`_periodic_drive_source_catchup` tick -- no work is lost or corrupted.

**Deliberately not bounded here:** the acquire stage (network/filesystem
walk across configured Drive sources), which runs before the parse stage
and isn't chunked at a granularity this checkpoint can safely cover.
Left as residual scope.

## On the general per-actor time-budget mechanism (qlae task item 3)

Not attempted in this PR. Both de2a and this PR apply the same manual,
per-actor opt-in pattern at a call site the actor's own author
understands (its natural transaction boundaries). A general enforcement
mechanism inside `DaemonWriteCoordinator` itself would have to either
preempt a hold mid-flight (unsafe -- a mid-hold SQLite transaction
cannot safely release the async gate without releasing the real DB-level
write lock, per de2a's own prior analysis) or externally cancel a
non-cooperating actor's task (behavior-changing for any actor not
written to expect cancellation mid-write). I recommend a follow-up bead
scoped to *auditing every current writer actor* for whether it already
has an equivalent natural checkpoint it could opt into, rather than
building a generic coordinator-level mechanism speculatively ahead of a
third, not-yet-identified offender.

## Verification

```
devtools test tests/unit/pipeline/test_parsing_service.py tests/unit/daemon/test_daemon_cli.py
```
-> 140 passed. Includes new regression test
`test_parse_from_raw_max_pass_seconds_bounds_one_call_and_preserves_progress`,
mirroring de2a's own raw-materialization regression test shape: with
`max_pass_seconds=1.0` and `raw_batch_size=1` against 3 raw ids, exactly
1 batch is processed and `time_budget_exceeded` is `True`; a follow-up
call without a budget processes the declared remainder (2 batches),
proving no work is lost. Verified load-bearing by reverting the
production changes only and confirming the new test fails on a
`TypeError: unexpected keyword argument 'max_pass_seconds'`.

Also updated 3 pre-existing tests that asserted the exact kwargs of a
mocked `parse_from_raw`/`ingest_sources` call (now includes
`max_pass_seconds=None`/the new fake parameter) and one daemon test's
fake `ingest_sources` signature.

```
devtools test tests/unit/pipeline/test_hermes_raw_identity.py tests/unit/pipeline/test_stage_independence.py tests/unit/storage/test_repair.py
```
-> 67 passed, 11 pre-existing failures unchanged (same "no messages, no
positive conversational evidence" parser-refusal drift already
documented as out of scope in de2a's PR #3534; `repair.py` is untouched
by this PR).

```
devtools verify --quick
```
-> passes (ruff format/check, mypy --strict, render all --check,
layering, schema-versioning, all other quick gates). Ran again as part
of the pre-push hook after the branch rename, also green.

`devtools verify` (testmon) was not run -- this worktree's testmon cache
is unseeded; the `devtools test` invocations above cover every file this
PR touches plus their existing test suites.

## Follow-ups

- AC2 (archive-wide worst-case wait bound) and a live re-measurement
under a comparable backlog remain open, same as de2a's own follow-up
notes -- both require a deployed daemon under live-scale load.
- Recommend a new bead: audit every remaining `DaemonWriteCoordinator`
actor for an unbounded hold, rather than a generic coordinator-level
time-budget mechanism (see reasoning above).

Ref polylogue-qlae

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

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem

Ref polylogue-11cg9. de2a (PR #3534) and qlae (PR #3550) bounded
maintenance.raw_materialization and maintenance.drive_catchup writer
holds to a declared max_pass_seconds checkpoint, but watcher.catch_up.chunk
and watcher.live_ingest.full had only size bounds (4 files/16MiB per
catch-up chunk; up to 64 files/64MiB per full-ingest progress group) and
no time bound. The original de2a incident (an in-size-bounds ~7MB chunk
that held the sole archive writer for 860s) is exactly the case a time
budget would catch, and it starves every other writer-lock actor for
however long parsing/materializing takes.

Solution

Both actors bottom out in LiveBatchProcessor.ingest_files ->
_ingest_full_paths -> _ingest_full_paths_sync -> _ingest_full_records_archive,
regardless of which outer wrapper (watcher.catch_up.chunk or a plain
watch-flush) invokes them. A max_pass_seconds parameter is threaded through
this whole chain, checked against one shared time.monotonic() reference
established once at the top of ingest_files:

- Between full-ingest progress groups in ingest_files's by-source loop.
- Between records inside _ingest_full_records_archive's per-record loop
  (the important case: a progress group can already bundle up to 64 small
  files into one writer hold).

A single logical session write cannot be split mid-transaction, so the
budget is only ever checked between complete units, never inside one; the
first unit of every pass always completes regardless of budget (forward
progress guarantee). Records/groups skipped by the budget are excluded from
both succeeded and failed (a new _ArchiveFullWriteResult.skipped_raw_ids /
_FullIngestResult.time_budget_exceeded bucket) so no cursor is recorded and
no failure backoff applies -- they remain ordinary backlog for the next
catch-up scan or watch tick. LiveWatcher passes a declared
_LIVE_INGEST_MAX_PASS_SECONDS = 20.0 (matching de2a/qlae's constant),
observable via LiveBatchMetrics.time_budget_exceeded and a new log line.

Residual gap (documented, not fixed here): a single file whose own
parse+materialize exceeds the budget still cannot be interrupted --
bounding that would need a streaming/interruptible parser, out of scope
for this pass (matches the bead's own framing and qlae's precedent of
leaving Drive's acquire stage unbounded for the same reason).

Verification

devtools test tests/unit/sources/test_live_watcher.py
  tests/unit/sources/test_live_batch_support.py
  tests/unit/sources/test_live_batch_observability.py
  tests/unit/sources/test_live_watcher_catchup_order.py
  tests/unit/sources/test_live_watcher_locking.py
  tests/unit/sources/test_live_watcher_parse_stage_equivalence.py
  tests/unit/sources/test_live_cursor_locking.py
  tests/unit/daemon/test_schema_preflight.py
  tests/unit/pipeline/test_parsing_service.py
  tests/unit/storage/test_repair.py
-> 294 passed, 4 pre-existing failures unchanged (confirmed identical on
origin/master by stashing this branch's changes and re-running 3x; same
"did not prove one session and cursor identity" / "raw revision did not
replay to exactly one session" fixture drift, unrelated to this change).

New regression test test_ingest_files_max_pass_seconds_bounds_one_pass_and_preserves_progress
reproduces the shape of the de2a incident: three small same-progress-group
codex sessions with a deterministic fake monotonic clock and
max_pass_seconds=1.0 -- exactly one is written this pass, the other two are
left as ordinary un-recorded backlog (not succeeded, not failed), and a
follow-up call without a budget finishes them with nothing lost. Verified
load-bearing by reverting the production changes only 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).

Ref polylogue-11cg9

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem

Ref polylogue-11cg9. de2a (PR #3534) and qlae (PR #3550) bounded
maintenance.raw_materialization and maintenance.drive_catchup writer
holds to a declared max_pass_seconds checkpoint, but watcher.catch_up.chunk
and watcher.live_ingest.full had only size bounds (4 files/16MiB per
catch-up chunk; up to 64 files/64MiB per full-ingest progress group) and
no time bound. The original de2a incident (an in-size-bounds ~7MB chunk
that held the sole archive writer for 860s) is exactly the case a time
budget would catch, and it starves every other writer-lock actor for
however long parsing/materializing takes.

Solution

Both actors bottom out in LiveBatchProcessor.ingest_files ->
_ingest_full_paths -> _ingest_full_paths_sync -> _ingest_full_records_archive,
regardless of which outer wrapper (watcher.catch_up.chunk or a plain
watch-flush) invokes them. A max_pass_seconds parameter is threaded through
this whole chain, checked against one shared time.monotonic() reference
established once at the top of ingest_files:

- Between full-ingest progress groups in ingest_files's by-source loop.
- Between records inside _ingest_full_records_archive's per-record loop
  (the important case: a progress group can already bundle up to 64 small
  files into one writer hold).

A single logical session write cannot be split mid-transaction, so the
budget is only ever checked between complete units, never inside one; the
first unit of every pass always completes regardless of budget (forward
progress guarantee). Records/groups skipped by the budget are excluded from
both succeeded and failed (a new _ArchiveFullWriteResult.skipped_raw_ids /
_FullIngestResult.time_budget_exceeded bucket) so no cursor is recorded and
no failure backoff applies -- they remain ordinary backlog for the next
catch-up scan or watch tick. LiveWatcher passes a declared
_LIVE_INGEST_MAX_PASS_SECONDS = 20.0 (matching de2a/qlae's constant),
observable via LiveBatchMetrics.time_budget_exceeded and a new log line.

Residual gap (documented, not fixed here): a single file whose own
parse+materialize exceeds the budget still cannot be interrupted --
bounding that would need a streaming/interruptible parser, out of scope
for this pass (matches the bead's own framing and qlae's precedent of
leaving Drive's acquire stage unbounded for the same reason).

Verification

devtools test tests/unit/sources/test_live_watcher.py
  tests/unit/sources/test_live_batch_support.py
  tests/unit/sources/test_live_batch_observability.py
  tests/unit/sources/test_live_watcher_catchup_order.py
  tests/unit/sources/test_live_watcher_locking.py
  tests/unit/sources/test_live_watcher_parse_stage_equivalence.py
  tests/unit/sources/test_live_cursor_locking.py
  tests/unit/daemon/test_schema_preflight.py
  tests/unit/pipeline/test_parsing_service.py
  tests/unit/storage/test_repair.py
-> 294 passed, 4 pre-existing failures unchanged (confirmed identical on
origin/master by stashing this branch's changes and re-running 3x; same
"did not prove one session and cursor identity" / "raw revision did not
replay to exactly one session" fixture drift, unrelated to this change).

New regression test test_ingest_files_max_pass_seconds_bounds_one_pass_and_preserves_progress
reproduces the shape of the de2a incident: three small same-progress-group
codex sessions with a deterministic fake monotonic clock and
max_pass_seconds=1.0 -- exactly one is written this pass, the other two are
left as ordinary un-recorded backlog (not succeeded, not failed), and a
follow-up call without a budget finishes them with nothing lost. Verified
load-bearing by reverting the production changes only 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).

Ref polylogue-11cg9

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
…wall-clock (#3571)

## Summary

Adds a declared, enforced wall-clock budget to the daemon's watcher full-ingest path so `watcher.catch_up.chunk` and `watcher.live_ingest.full` can no longer hold the process-wide writer coordinator indefinitely, closing the last residual gap in the de2a/qlae starvation-fix series.

## Problem

Ref polylogue-11cg9. de2a (PR #3534) and qlae (PR #3550) bounded `maintenance.raw_materialization` and `maintenance.drive_catchup` writer holds to a declared `max_pass_seconds` checkpoint, but `watcher.catch_up.chunk` and `watcher.live_ingest.full` had only *size* bounds (4 files/16MiB per catch-up chunk; up to 64 files/64MiB per full-ingest progress group) and no *time* bound. Grep confirmed zero `max_pass_seconds` hits in `watcher.py`/`batch.py` before this change. The original de2a incident (an in-size-bounds ~7MB chunk that held the sole archive writer for 860s) is exactly the case a time budget would have caught, and while that hold runs, every other writer-lock actor is starved.

This bead's own framing flagged the harder constraint: a single logical session write cannot be split mid-transaction, so a simple checkpoint loop (like raw-materialization's) isn't directly applicable — the right unit to bound is the *record/group* boundary, not mid-record.

## Solution

Both named actors bottom out in the same call chain regardless of which outer wrapper invokes them: `LiveBatchProcessor.ingest_files` -> `_ingest_full_paths` -> `_ingest_full_paths_sync` -> `_ingest_full_records_archive`. A `max_pass_seconds` parameter is threaded through this whole chain, checked against one shared `time.monotonic()` reference established once at the top of `ingest_files` (not re-armed per group/record, which would let many individually-in-budget units sum to an unbounded total hold):

- Between full-ingest progress groups in `ingest_files`'s by-source loop.
- Between records inside `_ingest_full_records_archive`'s per-record loop — the case that matters most, since one progress group can already bundle up to 64 small files into a single writer hold.

The first unit of every pass always completes regardless of budget (forward-progress guarantee, same shape as de2a/qlae). Records/groups skipped by the budget go into a new `_ArchiveFullWriteResult.skipped_raw_ids` / `_FullIngestResult.time_budget_exceeded` bucket, kept distinct from both `succeeded` and `failed`: no cursor is recorded (so no work is silently marked done) and no failure backoff applies (so retry isn't penalized) — they remain ordinary backlog for the next catch-up scan or watch tick.

`LiveWatcher` passes a declared `_LIVE_INGEST_MAX_PASS_SECONDS = 20.0` (matching de2a/qlae's constant), observable via `LiveBatchMetrics.time_budget_exceeded` and a new log line when a pass yields early.

**Deliberately not bounded here** (documented residual gap, matching qlae's precedent for Drive's acquire stage): a single file whose own parse+materialize step exceeds the budget still cannot be interrupted mid-record — bounding that would need a streaming/interruptible parser, out of scope for this pass. This PR fixes the "many files back-to-back" unbounded case completely and tightens the "one pathological file" case to at most one file over budget per pass, down from unbounded.

## Verification

```
devtools test tests/unit/sources/test_live_watcher.py tests/unit/sources/test_live_batch_support.py tests/unit/sources/test_live_batch_observability.py tests/unit/sources/test_live_watcher_catchup_order.py tests/unit/sources/test_live_watcher_locking.py tests/unit/sources/test_live_watcher_parse_stage_equivalence.py tests/unit/sources/test_live_cursor_locking.py tests/unit/daemon/test_schema_preflight.py tests/unit/pipeline/test_parsing_service.py tests/unit/storage/test_repair.py
```
-> 294 passed, 4 pre-existing failures unchanged (confirmed identical on `origin/master` by stashing this branch's changes and re-running 3x; same "did not prove one session and cursor identity" / "raw revision did not replay to exactly one session" fixture drift, unrelated to this change). One additional test (`test_end_to_end_hidden_root_file_creation_triggers_ingest`, a real-filesystem-watch timing test) flaked once under heavy concurrent load from an unrelated background suite run and passed cleanly on every other run (4/4 in isolation, 2/2 in the full batch afterward) — confirmed pre-existing timing fragility, not a regression, by reproducing the same flake shape on `origin/master` under identical load.

New regression test `test_ingest_files_max_pass_seconds_bounds_one_pass_and_preserves_progress` reproduces the shape of the de2a incident: three small same-progress-group codex sessions with a deterministic fake monotonic clock and `max_pass_seconds=1.0` — exactly one is written this pass, the other two are left as ordinary un-recorded backlog (not succeeded, not failed), and a follow-up call without a budget finishes them with nothing lost. Verified load-bearing by reverting the production changes only 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).

## Acceptance criteria (bead has 1 explicit ask: apply the de2a/qlae bounded-pass pattern to the two remaining unbounded watcher actors)

1. **`watcher.catch_up.chunk` bounded in time** — satisfied: chunks already atomically bound the writer per `_run_coordinated` call, and the internal `ingest_files` call this chunk makes now also checks the shared budget between records/groups.
2. **`watcher.live_ingest.full` bounded in time** — satisfied via the same shared code path.
3. **Per-session atomicity preserved** — satisfied: the checkpoint only ever fires between complete records/groups, never mid-write; verified by the new regression test's second (follow-up) call completing the deferred work intact.
4. **Live re-measurement under a comparable backlog** — not done here, consistent with de2a/qlae's own follow-up notes; requires a deployed daemon under live-scale load.

## Follow-ups

- AC4 (live re-measurement) needs a deployed daemon under a comparable backlog; not attempted here.
- The single-pathological-file case (one file whose own parse+materialize exceeds the budget) remains genuinely unbounded; a streaming/interruptible parser would be required to close it fully.

Ref polylogue-11cg9
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