Skip to content

feat(daemon): warn loudly when raw materialization backlog is bulk-scale - #3145

Merged
Sinity merged 1 commit into
masterfrom
feature/daemon/raw-materialization-bulk-rebuild-recommendation
Jul 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/daemon/raw-materialization-bulk-rebuild-recommendation

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

The daemon's raw-materialization trickle conveyor now journals a loud,
rate-limited warning recommending polylogue ops maintenance rebuild-index
whenever the pending backlog it measures is bulk-scale (>2000 candidates or

2 GiB pending payload), instead of silently grinding bounded passes for
weeks.

Problem

Lesson from the 2026-07-18/19 restore (polylogue-m6tp, polylogue-5jak,
polylogue-l3tk, polylogue-p0pw): the raw-materialization conveyor (bounded
16/64-row passes, per-pass candidate recomputation, writer interleaving
with the catch-up walk) is designed for steady-state trickle. Applied to a
large backlog after an index rebuild, it turned ~1h of parse work into a
weeks-scale projection, and census progress went net-negative once the
live watcher minted new pending raws faster than the conveyor cleared
them. The correct bulk path already existed the whole time --
polylogue ops maintenance rebuild-index (resumable blue-green
generation, full envelope, one census+replay sweep) -- but nothing routed
to it or even mentioned it.

Solution

  • polylogue/product/raw_authority.py: RawMaterializationCounts gains
    two fields, candidate_count and pending_blob_bytes, describing the
    whole unbounded backlog a pass measured (not the bounded per-pass
    batch) -- repair_materialization already enumerates every matching
    raw before applying raw_artifact_limit, so these ride on metrics the
    repair result already carries (raw_materialization_candidate_count,
    raw_materialization_total_blob_bytes). No new plumbing invented.
  • polylogue/daemon/cli.py: _drain_raw_materialization_once populates
    the two new fields from result.metrics. A new
    _maybe_recommend_bulk_rebuild helper, called once per burst pass from
    _periodic_raw_materialization_convergence, logs
    logger.warning(...) naming the bulk-rebuild command once the backlog
    crosses either threshold, rate-limited to at most once per hour
    (module-level monotonic timestamp) so a long-lived backlog doesn't spam
    the journal on every pass.

Scope decision (recorded on polylogue-m6tp): the bead offered two
options -- (a) a loud status/journal recommendation, or (b) the daemon
running the bulk path itself. This PR implements (a) only: it is safe,
small, and honest. (b) is deferred to a follow-up because it has real open
design questions this PR does not resolve: pausing the live watcher during
a bulk pass, the frozen source-snapshot requirement a blue-green rebuild
needs, and the restart-required story for swapping generations under a
live daemon.

No daemon status-payload wiring: the existing
RawMaterializationReadiness status surface (daemon/status.py) is a
separate on-demand snapshot computed via polylogue.readiness.capability,
not fed by the conveyor's per-pass metrics -- wiring the recommendation
into it would be a materially larger change than this PR's scope.
Journal-only is the honest surface for now; noted on the bead.

Verification

  • devtools test tests/unit/daemon/test_daemon_cli.py -- 96 passed,
    including 6 new tests: below-threshold silence, independent
    candidate-count/byte-count triggers, once-per-hour rate limiting (three
    calls -> two log lines), and that the periodic loop actually invokes the
    check (not merely defines it unreachably). Anti-vacuity: the tests
    exercise the real _bulk_scale_raw_materialization_backlog predicate
    against production threshold constants -- removing either comparison in
    the predicate (or hardcoding it True/False) fails the below-threshold or
    above-threshold test respectively.
  • devtools verify --quick -- exit 0 (ruff format/check, mypy --strict,
    render all --check). Ran again automatically via the pre-push hook.
  • Not run: devtools verify --all (full suite) -- the per-PR CI runs the
    heavy test suite post-merge, per repo convention; the pre-existing
    master failure test_fresh_init_creates_canonical_fts_trigger_set is
    known and tracked separately (polylogue-dyno), unrelated to this change.

Ref polylogue-m6tp

Problem: the 2026-07-18/19 restore showed the raw-materialization trickle
conveyor's bounded per-pass passes (16/64-row limit, per-pass candidate
recomputation) are structurally wrong for a bulk-scale backlog -- ~1h of
parse work projected out to weeks, with census going net-negative while
the live walk minted new pending raws faster than the conveyor cleared
them. The correct bulk path already existed (`polylogue ops maintenance
rebuild-index`: resumable blue-green generation, one census+replay
sweep) but nothing routed to it or even mentioned it (polylogue-m6tp).

Solution: `_drain_raw_materialization_once` now threads through the two
backlog-scale metrics `repair_materialization` already computes over the
*whole* matching candidate set before applying `raw_artifact_limit`
(`raw_materialization_candidate_count`, `raw_materialization_total_blob_bytes`)
via two new `RawMaterializationCounts` fields (`candidate_count`,
`pending_blob_bytes`) -- no new plumbing invented. A new
`_maybe_recommend_bulk_rebuild` check in the periodic conveyor loop logs a
`logger.warning` naming `polylogue ops maintenance rebuild-index` once the
backlog exceeds 2000 candidates or 2 GiB pending, rate-limited to once per
hour so a long-lived backlog doesn't spam the journal every burst pass.

Scope decision (recorded on polylogue-m6tp): implement the loud
status/journal recommendation now (safe, small, honest); defer the
daemon-routes-to-the-bulk-path option to a follow-up, since it needs
design work this PR does not do -- watcher pause during the bulk pass,
a frozen source-snapshot requirement, and the restart-required story are
all still open questions. No daemon status-payload wiring: the existing
`RawMaterializationReadiness` status surface is a separate on-demand
snapshot computed via `polylogue.readiness.capability`, not fed by the
conveyor's per-pass metrics, so wiring it in was out of scope for this
change; journal-only is the honest surface for now.

Verification: `devtools test tests/unit/daemon/test_daemon_cli.py` (96
passed, includes 6 new tests covering below-threshold silence,
independent candidate-count/byte-count triggers, once-per-hour rate
limiting, and that the periodic loop actually invokes the check);
`devtools verify --quick` exit 0 (ruff format/check, mypy --strict,
render all --check).

Ref polylogue-m6tp

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.

@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: 46 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: 50253773-74ca-404c-a7db-9538a0f3d982

📥 Commits

Reviewing files that changed from the base of the PR and between 2ea211b and 74d417b.

📒 Files selected for processing (3)
  • polylogue/daemon/cli.py
  • polylogue/product/raw_authority.py
  • tests/unit/daemon/test_daemon_cli.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/daemon/raw-materialization-bulk-rebuild-recommendation

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 e4c6c69 into master Jul 19, 2026
3 checks passed
@Sinity
Sinity deleted the feature/daemon/raw-materialization-bulk-rebuild-recommendation branch July 19, 2026 03:22
Sinity added a commit that referenced this pull request Jul 20, 2026
…n build (#3189)

## Summary

Implements polylogue-gd6v (m6tp phase (c)): the daemon now routes a
bulk-scale raw backlog into a resumable, transactional, blue-green index
generation build running in-process, reusing the SAME engine the offline
`polylogue ops maintenance rebuild-index` CLI command already drives —
no
duplicate implementation. Off by default behind a new
`daemon_bulk_rebuild_routing` config flag.

## Problem

The trickle raw-materialization conveyor is sized for steady-state
drift;
a bulk-scale backlog turns it into a weeks-scale grind (#3145's own
threshold-warning evidence). The correct bulk path already existed as
the
offline CLI command (resumable transaction, blue-green generation, one
census+replay sweep), but nothing routed to it automatically, and its
own
resume model silently re-walks the whole corpus when a caller omits
`--operation-id` (polylogue-fbte: measured ~2.25h pure re-verification
per
resume on a ~50K-raw archive, observed on operation `ab5bad1f`).

## Solution

- `polylogue/daemon/bulk_rebuild.py` (new): resolves/resumes a single
  well-known bulk-rebuild transaction per archive
  (`DAEMON_BULK_REBUILD_OPERATION_ID`), drives it through
  `rebuild_index_from_source_sync`, and retires a terminal
  (promoted/stale/failed) transaction so the id is reused for the next
  backlog. The daemon never has an operator-supplied operation id to
forget, so the fbte bug class is structurally unreachable on this path.
- `polylogue/daemon/cli.py`: `_maybe_route_daemon_bulk_rebuild`, called
  from the existing raw-materialization convergence tick right after the
  #3145 recommendation log line. Keeps driving an in-flight build every
tick even if the instantaneous backlog reading dips below threshold, so
  partial progress is never abandoned. A dedicated `DaemonParseStage`
singleton (separate pool from the trickle conveyor's own) shuts down at
  daemon teardown alongside the existing one.
- `polylogue/daemon/parse_prefetch.py`: `DaemonParseStage.warm_raw_ids`
extracts `warm`'s dispatch/admit logic to also accept an explicit raw-id
  list — the bulk driver already knows its next page's raw ids from the
  transaction's own paged cursor, so it pre-warms them in the #3168
  thread pool before ever requesting the writer hold.
- `polylogue/sources/revision_backfill.py`,
`polylogue/maintenance/replay.py`,
`polylogue/maintenance/rebuild_index.py`: thread a new `prefetch_cache`
  parameter from `RebuildIndexRequest` down through
  `backfill_historical_revision_evidence`'s census phase, mirroring the
#3168 raw-materialization wiring. A prefetch hit flows through the same
  `spill.add(...)` as a fresh parse, so the replay phase's own
  `spill.for_raw` lookups see identical warmed content — census-phase
  prefetching alone is enough to also skip replay-phase reparsing.
  Degrades gracefully to the unmodified sequential in-hold parse on any
  miss or on a GIL build (real parallel-parse speedup lands with the
  3.14t deploy, m6tp phase (b); this PR is orchestration only).
- `polylogue/storage/index_generation.py`:
  `IndexGenerationStore.discard_transaction` retires a terminal
  transaction record so its operation id can be reused.
- `polylogue/config.py`, `docs/configuration.md`:
  `daemon_bulk_rebuild_routing` config flag (off by default), same
  pattern as `daemon_parse_stage_split`.

**Non-obvious decisions:**

- **Single-writer invariant.** The bead's design note mentions "a second
writer connection on the generation's own index.db." This PR's explicit
task constraints restate the single-writer invariant more strongly (main
  process is the sole SQLite writer; parse workers only produce parsed
  payloads, never write), so every bulk-rebuild write — like every other
  daemon writer actor — is scheduled through the existing
`daemon_write_coordinator().run_sync`. Responsiveness instead comes from
  moving parse off that hold (mirroring phase (a)'s
  `daemon_parse_stage_split`), not a second concurrent writer thread.
- **No trickle suppression.** Bulk routing does not pause or coordinate
with the trickle conveyor while a build is in flight — both converge to
  the same eventual state (the bulk build reads a snapshot and replays
  into a separate generation file; promotion is atomic). The resulting
  redundant per-raw work during the backlog window is a known,
  deliberately out-of-scope efficiency gap — m6tp's own design sketch
  flags watcher-pause/frozen-snapshot semantics as still-open questions
  this PR does not attempt to resolve.
- **CLI command NOT deleted.** `ops maintenance rebuild-index` remains;
  deletion is gated on an archive-scale equivalence receipt
(coordinator-owned, post-promote) per the gd6v AC. This PR delivers the
  fixture-scale half of that gate.

## Verification

```
devtools test tests/unit/daemon/test_bulk_rebuild.py tests/unit/daemon/test_daemon_cli.py \
  tests/unit/daemon/test_parse_prefetch.py tests/unit/daemon/test_raw_materialization_parse_stage_equivalence.py \
  tests/unit/maintenance/test_rebuild_index_bulk_build.py tests/unit/storage/test_incremental_rebuild_equivalence.py \
  tests/unit/storage/test_index_generation.py tests/unit/sources/test_revision_backfill.py
=> 176 passed in 8.58s

uv run mypy polylogue --active
=> Success: no issues found in 1059 source files

devtools verify --quick
=> exit_code 0 (ruff format/check, mypy, render all --check, layering,
   topology, docs-coverage, closure-matrix, all clean; grepped for
   "out of sync" — none found)

devtools render topology-projection && devtools render topology-status
=> regenerated docs/plans/topology-target.yaml + docs/topology-status.md
   for the new polylogue/daemon/bulk_rebuild.py module
```

New fixture-scale tests (`tests/unit/daemon/test_bulk_rebuild.py`):

- `test_daemon_bulk_rebuild_equivalent_to_cli_rebuild` — builds the same
  6-raw corpus through the CLI path (single call, `prefetch_cache=None`)
  and the daemon path (multi-pass, `DaemonParseStage`-warmed
  `prefetch_cache`), asserts identical `sessions`/`messages`/`blocks`/
`session_links` row-level content, `messages_fts` row count, and session
  count.
- `test_daemon_bulk_rebuild_pass_resumes_without_reprocessing_raw_ids` +

`test_daemon_bulk_rebuild_pass_next_page_excludes_already_scheduled_raws`
  — the **fbte requirement**: each bounded pass's transaction cursor
  (`last_raw_id`/`processed_raw_count`, written by the existing
  `IndexGenerationStore.checkpoint_transaction`) only ever advances; a
  later page is proven disjoint from every earlier page; a simulated
  restart (fresh `DaemonParseStage` per pass, mirroring a fresh process)
  resumes from the persisted cursor instead of re-walking the corpus.
- `test_resolve_or_start_creates_resumes_and_retires_transaction` —
  transaction lifecycle: create, resume-unchanged, retire-on-terminal,
  fresh restart at the same well-known operation id.
- `tests/unit/daemon/test_daemon_cli.py`: 4 new tests for the routing
gate
  (flag off never checks/drives; below-threshold+not-resumable is a
  no-op; an in-flight operation keeps being driven below threshold; a
  pass failure never propagates to the caller).

## Remaining gd6v scope (follow-up, coordinator-owned)

- Archive-scale equivalence receipt and the resulting CLI-command
deletion
  (polylogue-4jsk).
- agvo responsiveness p99 gate proving live reads/ingest stay responsive
  during a real drain (this PR's responsiveness claim rests on parse
  moving off the writer hold, same mechanism as phase (a); not
  independently measured here).
- Trickle-conveyor coordination/suppression during an in-flight bulk
build
  (explicitly out of scope above).

Ref polylogue-gd6v

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