Repository navigation
perf(storage): wire prepare_session_rows off the writer thread - #3468
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 5 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
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. Comment |
…lk rebuild Problem polylogue-fpid: `prepare_session_rows`/`PreparedSessionRows` (polylogue-623q, off the writer thread but had zero production callers -- every full-replace write still built rows inline on the single SQLite writer's own hold. Instrumented the real rebuild engine (not a microbenchmark) against the two largest population strata (codex-session/d9: 7508 raws, claude-code-session/d9: 15954 raws, 57% of the corpus by count) via `tests/infra/rebuild_cost_model.py`'s `_run_one_rebuild_pass`, printing full `stage_timings_s`. `index.full_replace.field_path_union`'s timer wraps `_union_with_existing_rows`'s call expression -- whose ARGUMENTS (`_build_message_rows`/`_build_block_rows`) evaluate before the function body's early return -- so on a from-empty bulk build (`existing_raw_id is None`, always the early-return branch) this stage's entire measured cost is pure row construction, not the union it's named for: 0.355s/40 raws (42% of `full_replace`) on codex-d9, 0.072s/40 (11%) on claude-code-d9. Solution Threaded `PreparedSessionRows`/`Future[PreparedSessionRows]` through `apply_raw_revision_replay` -> `_index_parsed_for_retained_raw` -> `_write_parsed_precedence_result` -> `write_parsed_session_to_archive`'s existing `prepared` parameter (previously unwired). `backfill_historical_ revision_evidence`'s byte-proven replay loop submits `prepare_session_rows` for a chain's sole full-replace position (position 0 -- every other position is `merge_append`, which never accepts prepared rows) to a one-worker `ThreadPoolExecutor` right when `parsed_by_raw_id` is built, so it runs concurrently with `apply_raw_revision_replay`'s own attachment-preacquisition/ blob-flush/head-lookup preamble on a free-threaded interpreter (gated on `parallel_threads_effective()`, matching the existing parse-thread guard -- a GIL build gets `prepare_pool=None` and is byte-for-byte unchanged). Correctness: `write_parsed_session_to_archive`'s existing validity gate (content-hash match, not merge_append, not prefix-sharing) already made a stale/wrong `prepared` argument always safe to pass -- this change adds no new gating logic, only a new supplier. Also restores `literal_check` (deleted by already fixed on another branch as 3fc622ecb, cherry-picked here to unblock local verification on this worktree's `origin/master` base) and fixes a test double (`test_live_cursor_persistence.py`'s `_lock_first_index_persistence` fixture) that re-declares `_write_parsed_precedence_result`'s signature and needed the new `prepared` parameter to stay a faithful passthrough. Verification Re-instrumented after wiring, same two strata, 4 repeated runs each under host load 14-17: `field_path_union` collapsed from 0.355s/0.072s to a consistent ~0.0002s (99.9%+ eliminated) in every run. `full_replace` dropped 25-45% (codex-d9: 0.85s -> 0.46-0.63s; claude-code-d9: 0.64s -> 0.45-0.48s). `index_parsed_write` (the full per-session writer hold) dropped 19-22%. Weighted by raw count across the two dominant strata (57% of the corpus), this projects to roughly a 10-15% cut of writer apply time on the majority of a full rebuild -- an estimated 25-40 minutes off the calibrated 4h20m baseline. Did not run the full ~40-pass population projection benchmark (host had a concurrent instance of the same benchmark already running in another worktree; the per-stage stratum measurement above is the same real engine, just without the two-point regression's fixed-cost stripping). `devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_revision_replay.py tests/unit/storage/test_raw_retention.py tests/unit/storage/test_prepared_session_rows.py tests/unit/storage/test_archive_tiers_write.py tests/unit/sources/test_live_cursor_persistence.py` -- 228 passed, 1 failed (`test_parse_one_still_replays_real_claude_code_sessions_with_no_path_rule`, confirmed pre-existing on unmodified origin/master via a diff-free byte-for-byte rerun; filed as polylogue-6mpy, unrelated to this change). `devtools verify --quick` -- exit 0. `mypy polylogue devtools` -- Success, no issues found in 1277 source files. Ref polylogue-fpid, polylogue-623q, polylogue-7qfq Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01KAAzxpu1wNZLmuAb8Wgyso
polylogue-fpid closed with the field_path_union/full_replace/ index_parsed_write measurements from ab65c29. polylogue-6mpy tracks the pre-existing content-classification test regression discovered (and confirmed unrelated) during that verification. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01KAAzxpu1wNZLmuAb8Wgyso
6759337 to
9d5c0e4
Compare
…che (#3477) ## Summary The offline `polylogue ops maintenance rebuild-index` CLI and the daemon's own `POST /api/maintenance/rebuild-index` HTTP route both build a `RebuildIndexRequest` without ever populating `prefetch_cache`, so they silently pay the full unwarmed census parse cost that the daemon's bulk-rebuild loop (`daemon/bulk_rebuild.py`, #3168) has always avoided by warming ahead of the writer hold. This PR closes that gap for both routes in one place. ## Problem `RebuildIndexRequest.prefetch_cache` (the off-writer-hold census pre-parse seam introduced by #3168) had exactly one caller in the whole codebase that ever populated it: `daemon/bulk_rebuild.py`'s automagic bulk-rebuild routing. Every other caller of the shared rebuild engine — the offline CLI `rebuild-index` command, and the daemon's own HTTP rebuild-index route — left it at its `None` default. The operator's real 4h22m CLI rebuild run measured `spill_load` (serial re-deserialization of already-parsed sessions, inline on the writer thread) at 2,830s — 70% of the run's `parse_s` (4,032s). The daemon's bulk-rebuild route would not have paid this the same way. ## Solution - Relocated the parse-stage warmer from `polylogue.daemon.parse_prefetch.DaemonParseStage` (daemon-only, one caller) to substrate as `polylogue.sources.census_parse_stage.CensusParseStage` — the mechanism has no daemon-specific behavior, only a daemon-specific import path. `polylogue.daemon.parse_prefetch` now re-exports the same objects unchanged (verified: 6 existing daemon/sources/storage test files still pass, 110 tests total, all unmodified in behavior). - `maintenance/rebuild_index.py`'s `_rebuild_index_from_source_owned` now calls a new `_warm_offline_prefetch_cache` helper whenever a caller leaves `request.prefetch_cache` at its `None` default, warming exactly this pass's own `selected_raw_ids` in a bounded thread pool before replay. This fixes **both** the offline CLI route and the daemon's own HTTP route in one place (both call the same engine function), instead of needing two separate call-site patches. It composes with #3468's `prepare_session_rows` threading without touching it, and never overrides a cache a caller already supplied (`daemon/bulk_rebuild.py`'s own external off-writer-hold warm is untouched). - Updated `docs/plans/layering-surface-baseline.json` (5 stale `daemon/parse_prefetch.py` import entries replaced by 1 new `census_parse_stage` entry) and regenerated `docs/plans/topology-target.yaml` for the new module. ## Alternatives rejected - Duplicating a warm helper directly in the CLI adapter (`cli/commands/maintenance/_rebuild_index.py`): rejected because the CLI would need to re-derive the exact page/raw_id selection the engine's own resumable-transaction logic computes internally, risking a second, drifting implementation of that selection policy — the same defect class this PR is trying to close, not reproduce. - Leaving `DaemonParseStage` in `daemon/parse_prefetch.py` and importing it from `maintenance/rebuild_index.py`: rejected because `maintenance` is documented as the substrate engine CLI/daemon/HTTP adapt over (`rebuild_index.py`'s own module docstring), so a substrate module reaching into a surface package would invert that relationship even though today's `layering.yaml` ruleset happens not to forbid it explicitly. ## Verification - `devtools verify --quick` (ruff format/check, mypy --strict, `render all --check`, topology, layering) — all green. - `devtools test` across the 12 affected files (`tests/unit/daemon/test_parse_prefetch.py`, `test_config_resolution_regression.py`, `test_daemon_bulk_rebuild_responsiveness.py`, `test_live_watcher_parse_stage_equivalence.py`, `test_prefetch_cache_thread_safety.py`, `test_rebuild_paging_content_order.py`, `test_raw_materialization_parse_stage_equivalence.py`, `test_bulk_rebuild.py`, `test_rebuild_parse_apply_split.py`, `test_rebuild_index_ownership.py`, `test_rebuild_index_selection.py`, `test_rebuild_index_bulk_build.py`, `test_archive_maintenance_cli.py`) — 110 passed. - New test `test_rebuild_index_from_source_sync_warms_prefetch_cache_when_caller_omits_one` drives the real `rebuild_index_from_source_sync` entry point (the exact function both the CLI and HTTP route call) with a request that omits `prefetch_cache`, and asserts `CensusParseStage.warm_raw_ids` was actually reached with this pass's raw ids. Anti-vacuity verified manually: temporarily disabled the internal warm call, confirmed the assertion fails with "offline rebuild_index_from_source_sync never warmed a prefetch cache", then restored the fix. - Measurement (synthetic 400-raw / ~60KB corpus, `tests.infra.revision_backfill_benchmark`): `census` stage time collapses from ~0.8s to ~0.1-0.15s with warming enabled. `spill_load` stayed at 0.0s in both runs — this synthetic corpus is far too small to overflow the ~256MiB-2GiB decoded-session hot cache that gates whether `spill_load` ever pays a `pickle.loads` reload at all, so the real 87K-raw whale-corpus `spill_load` collapse from the operator's receipt is **not independently reproduced here** and is not claimed as measured. The task brief's own caveat applies: this harness under-represents the real path (~10% untimed synthetic work vs ~33% real). ## Follow-ups - `polylogue-mznm`: the daemon's own whale-scale raw-materialization escalation pass (`_run_raw_materialization_whale_pass_once`) has the identical `prefetch_cache=None` gap against its sibling trickle pass — scoped out of this PR because it needs a *new* warm-before-writer-hold step (no equivalent variable exists in scope yet), not just threading an existing one. - `polylogue-q1at`: proposal to make this defect class — a capability adopted by one caller of a shared engine while sibling callers silently keep the disabled default — detectable by tooling, calibrated against this session's corpus of already-fixed instances. Co-authored-by: Claude <[email protected]>
Summary
Wires the previously-unused
prepare_session_rows/PreparedSessionRows(polylogue-623q, #3219) into the offline/CLI bulk-rebuild path so row-tuple
construction (message/block hashing, JSON encoding, enum lookups) runs on a
background thread concurrently with the single SQLite writer's own work,
instead of inline inside the writer's hold.
Problem
polylogue-fpid: this was the last unexplored performance lever for a full
index rebuild, which the archive needs to run to pick up 5,300 misclassified
sessions and every parser fix landed today. Concurrency (#p0pw/#8249),
FTS-trigger deferral, and delete-cascade skip (#3460) were already measured
and closed off; the remaining diagnosis was that bulk-build is INSERT-bound
and
prepare_session_rows/PreparedSessionRowsexisted complete, tested,and wired nowhere.
Instrumenting the real rebuild engine (
tests/infra/rebuild_cost_model.py's_run_one_rebuild_pass, not a microbenchmark) against the two largestpopulation strata (codex-session/d9: 7508 raws, claude-code-session/d9:
15954 raws — 57% of the 41,363-raw corpus by count) showed
index.full_replace.field_path_union's timer wrapping_union_with_existing_rows's call expression — whose arguments(
_build_message_rows/_build_block_rows) evaluate before the functionbody's own early return. On a from-empty bulk build (
existing_raw_id is None, always the early-return branch for this stratum shape) the entiremeasured cost of that stage is pure row construction, not the union it's
named for: 0.355s/40 raws (42% of
full_replace) on codex-d9, 0.072s/40(11%) on claude-code-d9.
Solution
polylogue/storage/sqlite/archive_tiers/revision_governance.py: threadsPreparedSessionRows/Future[PreparedSessionRows]throughapply_raw_revision_replay→_index_parsed_for_retained_raw→_write_parsed_precedence_result→write_parsed_session_to_archive'sexisting (previously unwired)
preparedparameter. Only ever resolved atchain position 0 (the sole full-replace write — every later position is
merge_append, which never accepts prepared rows).polylogue/sources/revision_backfill.py:backfill_historical_revision_ evidence's byte-proven replay loop submitsprepare_session_rowsforposition 0's session to a one-worker
ThreadPoolExecutorright whenparsed_by_raw_idis built, so it runs concurrently withapply_raw_revision_replay's own attachment-preacquisition/blob-flush/head-lookup preamble on the calling thread. Gated on
parallel_threads_effective()(same guard the existing parse-thread pooluses) — a GIL build gets
prepare_pool=Noneand is byte-for-byteunchanged.
polylogue/storage/sqlite/archive_tiers/archive.py: threads the newparameter through
ArchiveStore.apply_raw_revision_replay's wrapper.write_parsed_session_to_archive's existing validity gate(content-hash match, not
merge_append, not prefix-sharing) already madea stale/wrong
preparedargument always safe to pass — this change addsno new gating logic, only a new supplier.
literal_check(deleted by refactor: collapse duplicate implementations, dead shims, and split vocabularies #3458 despite live call sitesfeat(storage): wire literal_check into DDL, fix a drift CHECK gap #3451 added the same day — polylogue-7qfq, already fixed on another
branch as
3fc622ecb, cherry-picked here to unblock local verificationon this worktree's
origin/masterbase) and fixes a test double(
test_live_cursor_persistence.py's_lock_first_index_persistencefixture, which re-declares
_write_parsed_precedence_result's signature)to accept and forward the new
preparedparameter.Verification
Re-instrumented after wiring, same two strata, 4 repeated runs each under
host load 14–17 (contended, hence the repeats):
field_path_unioncollapsedfrom 0.355s/0.072s to a consistent ~0.0002s (99.9%+ eliminated) in every run.
full_replacedropped 25–45% (codex-d9: 0.85s → 0.46–0.63s; claude-code-d9:0.64s → 0.45–0.48s).
index_parsed_write(the full per-session writer hold)dropped 19–22%. Weighted by raw count across the two dominant strata (57% of
the corpus), this projects to roughly a 10–15% cut of writer apply time on
the majority of a full rebuild — an estimated 25–40 minutes off the
calibrated 4h20m baseline. Did not run the full ~40-pass population
projection benchmark (
test_full_population_projection) — a concurrentinstance of the same benchmark was already running in another worktree on
this host when this was measured; the per-stratum stage-level measurement
above uses the same real rebuild engine, just without the two-point
regression's fixed-cost stripping.
devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_revision_replay.py tests/unit/storage/test_raw_retention.py tests/unit/storage/test_prepared_session_rows.py tests/unit/storage/test_archive_tiers_write.py tests/unit/sources/test_live_cursor_persistence.py— 228 passed, 1 failed (test_parse_one_still_replays_real_claude_code_sessions_with_no_path_rule, confirmed pre-existing on unmodifiedorigin/mastervia a diff-free byte-for-byte rerun; filed as polylogue-6mpy, unrelated to this change).devtools verify --quick— exit 0 (ran twice: once pre-commit, once via the pre-push hook).mypy polylogue devtools— Success, no issues found in 1277 source files.devtools testselection above covers every touched call site).Ref polylogue-fpid, polylogue-623q, polylogue-7qfq