Repository navigation
perf(sources): sequential parse below aggregate pool floor, stop worker churn - #3149
Conversation
…er churn Problem: a 25s py-spy capture of the live bulk-rebuild census (2026-07-19) showed 20 spawned pool workers, each alive ~1.5-2.0s, spending ~95% of their lifetime inside importlib. Census calls dispatch per-cohort batches of 1-2 sub-256KiB raws, _parse_retained_raws creates a fresh ProcessPoolExecutor per call, and every spawn-method worker pays the full interpreter + polylogue import (~1.4s) before its first task — so the "parallel" census path was nearly 100% spawn/import overhead and strictly slower than sequential. The daemon's per-component census (#3122 wiring) has the same shape. What changed: pool dispatch now requires the pool-eligible aggregate payload to clear a floor (default 48MiB, override POLYLOGUE_REVISION_PARSE_POOL_MIN_BYTES) sized so that, at ~20MB/s sequential small-payload parse and ~2s worker spawn+import, the pool genuinely beats sequential. Below the floor the batch parses in-process with zero spawn cost. Large batches keep the existing pool path; the size-based per-raw partition (#3136) is unchanged. Verification: devtools test tests/unit/sources/test_revision_backfill.py (27 passed). New tests: floor decision function (thresholds + env override + invalid-env fallback) and an end-to-end guard asserting a sub-floor batch never constructs a ProcessPoolExecutor. Both fail against pre-fix code (verified via stash: 2 failed). devtools verify --quick exit 0. Ref polylogue-crd8 Co-Authored-By: Claude <[email protected]>
|
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: 34 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 Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
…rce_path) (#3151) ## Summary `_parse_retained_raws` now groups its batch by `(blob_hash, source_path)`, parses one representative per group, and fans the outcome out to duplicate rows (with each row's own `revision_kind` re-attached). Byte-identical raw rows — 17% of the live archive's newest-only bytes — stop paying repeated full parses. ## Problem Live evidence (2026-07-19, source.db): newest-revision-per-logical-key = 87,177 rows / 52.1GB, but only 85,066 distinct `blob_hash`es / 43.4GB — 8.7GB of parse work is byte-identical duplicates. Worst case: one 442MB codex rollout acquired **8 times within 2.3 seconds** (acquisition stampede; 8 raw rows, same blob, same path), each row fully parsed by census. The blob store dedups storage by hash; the parse layer did not. ## Solution - `_parse_retained_raws` becomes a dedup wrapper: group by `(blob_hash, source_path)`, delegate representatives to `_parse_unique_retained_raws` (the previous body, unchanged sequential/pool logic including the #3149 amortization floor), fan out outcomes. `source_path` stays in the key deliberately — some parsers derive identity from the path (beads workspace-scoped native ids), so cross-path duplicates of the same bytes still parse separately. Exceptions fan out to every row of the failed group. - Forward-looking: current `write_raw_payload` is idempotent for identical (payload, path) — verified by probe — so new stampedes can't recreate the shape; this covers the historical rows and any future writer regression. ## Verification - `devtools test tests/unit/sources/test_revision_backfill.py` — 29 passed. - New: `test_parse_retained_raws_dedupes_identical_blob_and_path` (parse-call sequence is exactly one per distinct (blob, path); duplicate rows get their own `revision_kind`; different path with same bytes still parses) and `test_parse_retained_raws_fans_out_exceptions_to_duplicate_rows`. Anti-vacuity via patch-revert of the implementation file (not `git stash` — `refs/stash` is shared across worktrees): both fail on pre-fix code (`2 failed`). - `devtools verify --quick` — exit 0. Ref polylogue-869u 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ Co-authored-by: Claude <[email protected]>
#3161) ## Summary `_parse_unique_retained_raws` in `sources/revision_backfill.py` gains a `ThreadPoolExecutor`-based parse path, gated on a new `parallel_threads_effective()` probe (`sys._is_gil_enabled()`). The path engages only under a genuinely free-threaded interpreter (3.14t); the standard GIL-build `ProcessPoolExecutor` fallback is unchanged. ## Problem polylogue-7mtf's control-run measurement (recorded on the epic) proved two things about threads under the current standard (GIL) build: - CPU-bound `ThreadPoolExecutor` parse gives **zero speedup** (0.93x-0.96x, pure lock overhead) — confirmed by the exact same code under 3.14t measuring 3.9x-9.6x (w=4..16) instead. - A concurrent SQLite writer thread's commit latency **inflates ~5000x** (208ms vs an ~5ms cadence) when CPU-bound parse threads run alongside it under the GIL; under 3.14t there is zero interference (0.04ms). The process-pool parse path also carries two GIL-only amortization costs that don't apply to threads at all: pickle-back of `ParsedSession` graphs across the process boundary (#3136, measured 0.63x/net-loss above 256KiB) and per-worker spawn+import tax (#3149, ~1.5-2s floor). Threads share one already-imported interpreter, so neither cost exists for them. ## Solution - `polylogue/pipeline/services/process_pool.py`: add `parallel_threads_effective() -> bool`, resolving `sys._is_gil_enabled` via `getattr` (so mypy --strict needs no per-Python-version `type: ignore`); its absence (pre-3.13 interpreters) is treated as "GIL enabled" — the safe default. - `polylogue/sources/revision_backfill.py`: `_parse_unique_retained_raws` routes to a new `_parse_unique_retained_raws_via_threads` whenever the probe is true. That path applies **no size partition and no amortization floor** — both exist solely to protect the process pool's two named costs. The `ProcessPoolExecutor` branch below it is byte-for-byte unchanged; it stays the deployed daemon's fallback until the daemon itself migrates to 3.14t (a separate, later step per the epic's deployment ordering — CLI/ offline rebuild adopts 3.14t first). - The thread path dispatches the existing `_census_parse_worker` function, **not** `_parse_retained_raw(archive, raw_id)` directly. `ArchiveStore` lazily opens its `source.db` connection with the default `check_same_thread=True`; calling `archive.raw_revision_descriptor` from a worker thread other than the connection's owning thread raises `sqlite3.ProgrammingError` — confirmed empirically (see PR discussion / commit message). `_census_parse_worker` never touches the shared `ArchiveStore` at all — it reconstructs a stateless `ArchiveBlobPublisher` from primitive strings, whose blob reads are plain filesystem I/O. - Two pre-existing tests asserted process-pool-specific size-partition/floor mechanics without pinning which branch they exercise; they now force `parallel_threads_effective() -> False` so their claims hold regardless of which interpreter runs the suite (one of them, `test_size_aware_dispatch_ keeps_large_raws_off_the_process_pool`, was found failing under a real 3.14t smoke run precisely because it wasn't pinned — see Verification). ## Verification - `devtools test tests/unit/sources/test_revision_backfill.py tests/unit/pipeline/test_process_pool.py`: **41 passed** (standard GIL build, Python 3.13.13). - Anti-vacuity (patch-revert): temporarily made `_parse_unique_retained_raws_via_threads` drop the first `raw_id` from dispatch (`for raw_id in raw_ids[1:]:`) — all 4 new thread-path tests failed (`KeyError` / missing session rows). Reverted; all 41 pass again. - `mypy --strict` on all 4 touched files: clean. `ruff check` / `ruff format --check`: clean. `devtools verify --quick`: exit 0. - **Real 3.14t smoke** (per the task brief): built a scratch venv via `nix shell nixpkgs#python314FreeThreading` + `uv`, with `orjson` deliberately excluded (polylogue-xikl.3's `core/json.py` facade falls back to `msgspec`, no shim needed — confirms polylogue now genuinely runs on 3.14t today). Ran the same two test modules: **41/41 pass**, with `parallel_threads_effective()` naturally `True` (unforced — this is a real free-threaded interpreter). A broader `tests/unit/sources` + `tests/unit/pipeline` sweep under the same interpreter found 14 pre-existing failures in unrelated modules (live/batch watcher timing, `validation_flow` decode-error-message text, `parsing_service` / `quarantine_fixtures` mock specs, drive mocks) plus one collection error from a test file that imports `orjson` directly outside the facade (`test_validation_parallelism_contracts.py`, excluded from this run) — all pre-existing 3.14t-migration gaps outside this PR's scope. Spot-verified one (`test_ingest_empty_sources_returns_empty_result`) reproduces identically on the standard GIL 3.13.13 devshell, confirming pre-existing/unrelated rather than caused by this change. - Full-suite `devtools verify --seed-testmon --skip-slow` bootstrap attempt hit `sqlite3.OperationalError: database is locked` inside an unrelated CLI-snapshot fixture (`tests/unit/cli/test_plain_cli_snapshots.py`) — transient contention from other concurrent agent sessions' full-suite pytest runs on this shared host (confirmed via `ps aux` at the time: 3+ concurrent `devtools verify --seed-testmon` processes across other worktrees), not a regression from this change. Not retried given ongoing host contention; the targeted + `--quick` + real-3.14t verification above stands in its place. ## Follow-ups - polylogue-xikl.4 (this PR's tracking bead) recommends **re-scoping, not closing**, polylogue-9as9 (the GIL-world pass-scoped-executor design): the daemon has not yet migrated to 3.14t, so that bead's warm-pool/ worker-side-lowering design retains narrow, near-term value for the still-deployed GIL-build daemon specifically. Recorded on both beads. Ref polylogue-xikl.4, polylogue-xikl 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <[email protected]>
…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]>
Summary
Pool dispatch in
_parse_retained_rawsnow requires the pool-eligible aggregate payload to clear an amortization floor (default 48MiB,POLYLOGUE_REVISION_PARSE_POOL_MIN_BYTESoverride); below it the batch parses sequentially in-process. This stops the worker-churn pathology where "parallel" census was nearly 100% spawn/import overhead.Problem
Measured live on the 2026-07-19 bulk rebuild (py-spy
--subprocesses, 25s at 150Hz): 20 pool workers spawned in 25 seconds, each alive ~1.5-2.0s, spending ~95% of their lifetime insideimportlib(spawn_main → _find_and_load → exec_module), with visible gaps where no workers existed at all. Mechanics: census dispatches per-cohort batches of 1-2 sub-256KiB raws;_parse_retained_rawscreates a freshProcessPoolExecutorper call withmax_workers=min(workers, len(pool_raw_ids))(=2); every spawn-method worker (#3143) re-imports the full polylogue CLI graph (~1.4s — the polylogue-h1wt import tax, now paid per worker per call) before parsing for milliseconds. Sequential mode was strictly faster. The daemon's per-component census path (#3122) has the same call shape.Solution
_pool_dispatch_amortizes(pool_raw_ids, payload_sizes): pool only when the pool-eligible aggregate clears_parse_pool_min_aggregate_bytes()(default 48MiB — derived in the docstring from ~20MB/s sequential small-payload parse vs ~2s worker spawn+import at 8 workers; env-overridable). The existing per-raw size partition (perf(sources): batch raw-authority census commits, keep large payloads off the parse pool #3136, keeps >256KiB payloads off the pool) is unchanged; genuinely large small-payload batches keep the pool path.Verification
devtools test tests/unit/sources/test_revision_backfill.py— 27 passed.test_pool_dispatch_floor_rejects_small_aggregate_batches(decision thresholds, env override, invalid-env fallback) andtest_parse_retained_raws_small_batch_never_creates_a_pool(end-to-end: a sub-floor batch must never construct aProcessPoolExecutor— monkeypatched constructor raises). Anti-vacuity verified via stash of the implementation file: both fail on pre-fix code (2 failed), pass with it restored.devtools verify --quick— exit 0.Ref polylogue-crd8
🤖 Generated with Claude Code
https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ