Repository navigation
perf(sources): batch raw-authority census commits, keep large payloads off the parse pool - #3136
Conversation
…s off the parse pool Problem: polylogue-9p8x's own profiling (cProfile, synthetic 60-raw/1.7MB corpus) found sqlite3.Connection.__exit__ (per-write commit/fsync) at 42.6% of backfill_historical_revision_evidence's wall time, comparable to parse (40.6%) -- census-phase writes (replace_raw_membership_census/ bind_raw_revision) self-commit once per raw via `with conn:`. A direct throughput benchmark also found the process-pool parse path was a net LOSS (0.63x) on large payloads (~1.7MB avg) because pickling the returned ParsedSession list back across the process boundary exceeded the parse time saved, while it was a real win (1.22x) on small payloads (~50KB avg). What changed: - replace_raw_membership_census (archive.py) and bind_raw_revision/ bind_source_raw_revision (archive.py, source_write.py) gain manage_transaction=True (default, unchanged behavior) using the `with conn if manage_transaction else nullcontext()` pattern already established elsewhere in archive.py. - _census_historical_revision_evidence (revision_backfill.py) gains commit_batch_size: when set, census writes defer commit and a batch boundary fires archive.commit() every N raws (default None preserves per-raw commit for every existing caller). Threaded through census_historical_revision_evidence/backfill_historical_revision_evidence/ repair_raw_materialization; the daemon/CLI path resolves a default of 20 via RAW_MATERIALIZATION_COMMIT_BATCH_SIZE / POLYLOGUE_RAW_AUTHORITY_COMMIT_BATCH_SIZE. - _parse_retained_raws now partitions raws by payload size (_partition_raws_by_dispatch_size): raws under POLYLOGUE_REVISION_PARSE_DISPATCH_MAX_BYTES (default 256KiB) stay pool-eligible; raws at/above it parse sequentially in-process, avoiding the pickle-back cost that made large payloads a net loss. Deliberately NOT touched: apply_raw_revision_replay's per-cohort index.db commit and finalize_raw_parse_state's per-raw source.db commit. Two existing crash-recovery tests (test_backfill_resumes_after_index_receipt_ commits_before_source_terminal, test_backfill_resumes_after_only_some_ source_markers_commit) pin "index commits, then source terminal marker commits" as a load-bearing ordering invariant in the replay phase; batching across cohorts there would need the corresponding source-marker commits deferred to the same boundary or the invariant inverts. That's a bigger, riskier change (matches this bead's own "needs its own adversarial review" scoping note) left for a follow-up. Measured (tests/infra/revision_backfill_benchmark.py corpus, median of 3 runs, same-session/same-machine load): SMALL (200 raws/~50KB avg), commit_batch_size=20 workers=1: 1.34x. LARGE (80 raws/~1.7MB avg), same config: 1.12x; combined with parallel dispatch: 1.13x (size-aware dispatch is now neutral-to-positive on large payloads instead of the prior 0.63x net loss). This is a modest, honest ceiling for this safe scope -- well short of the originally-hypothesized 4x -- recorded in full on polylogue-amg1 along with the daemon-vs-CLI deployment caveat (repair_raw_ materialization calls backfill per-component, so the full benchmark gain applies most directly to the CLI rebuild-index full-archive scenario). Verification: new tests prove the crash-mid-batch guarantee (test_census_batch_crash_loses_at_most_one_batch_and_resumes_cleanly: exactly one committed batch survives an injected fault, a resume converges to the correct terminal state with zero duplication) and the size-aware dispatch split (test_partition_raws_by_dispatch_size_routes_small_to_pool_ large_sequential, test_size_aware_dispatch_keeps_large_raws_off_the_ process_pool). Both proven to fail against the pre-fix code before restoring the fix (anti-vacuity). devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_repair.py -- 78 passed. devtools test tests/unit/devtools/test_raw_authority_restart_proof.py tests/unit/devtools/test_raw_authority_scale_proof.py -- 25 passed (crash-recovery/ conservation invariants intact). Broader sweep -k "raw_authority or raw_materialization or revision_backfill or revision_replay" -- 187 passed, 1 pre-existing unrelated failure (test_live_multi_session_divergence_ reopens_raw_authority, confirmed via stash-and-rerun to fail identically on clean origin/master). devtools verify --quick -- exit 0. Ref polylogue-amg1 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: 29 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 (7)
✨ 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 |
…#3147) ## Summary Extends polylogue-amg1's commit-batching to the replay phase. amg1 (PR #3136) batched the CENSUS phase's per-raw source.db commits but deliberately left the REPLAY phase's per-cohort index.db commit + per-raw terminal source.db marker commit unbatched, because a naive multi-cohort batch risked inverting a pinned crash-recovery ordering invariant. This PR does the deferred redesign: `commit_batch_size` now also batches replay commits across multiple independent cohorts, while preserving the invariant at batch granularity. ## Problem `backfill_historical_revision_evidence`'s replay loop calls `ArchiveStore.apply_raw_revision_replay` (and `apply_raw_membership_classification`) once per logical-source cohort. Each call self-committed index.db immediately (`with self._conn:`), then looped over terminal raw ids calling `mark_raw_parse_succeeded` — an independent, immediate source.db commit per raw. For amg1's own benchmark shape (independent single-session raws, cohort size == 1), this meant the replay phase still committed once per raw on BOTH tiers — the larger lever amg1's own notes explicitly named and deferred to this bead (polylogue-oikv), pending its own adversarial review of the crash-recovery stakes. ## Solution - `ArchiveStore.apply_raw_revision_replay` / `apply_raw_membership_classification` gain a `manage_transaction: bool = True` parameter, following the exact `with conn if manage_transaction else nullcontext()` pattern amg1 already established for census (`replace_raw_membership_census`, `bind_raw_revision`). When `False`, the cohort's index.db writes stay in the caller's open transaction, and its terminal parse-state marker is pushed onto the existing `_pending_raw_parse_states` queue instead of committing immediately via `mark_raw_parse_succeeded`. - `backfill_historical_revision_evidence`'s existing `commit_batch_size` parameter now governs BOTH phases: a `commit_replay_unit()` closure (mirroring census's own) fires `archive.commit()` every `commit_batch_size` cohorts across the byte-cohort and membership-classification loops, plus a final flush commit after both loops. `None` (the default) preserves the exact original per-cohort commit behavior for every existing caller. - **Why the invariant still holds**: `ArchiveStore.commit()` already commits the index connection *before* flushing pending source markers (`_flush_pending_raw_parse_states`). Batching multiple cohorts into one shared `commit()` call means the ordering invariant now holds at BATCH granularity instead of per-cohort: a crash anywhere in an open (uncommitted) batch discards every cohort in that batch — index writes and terminal markers together, since neither side ever committed (SQLite implicitly rolls back an uncommitted transaction when the connection closes) — never a partial batch, and a resume reprocesses every lost cohort from scratch with zero duplication. - The rare non-terminal "incomplete cohort" NULL-reset branch in `apply_raw_membership_classification` (a sibling member still undecided) is left immediately-committing regardless of batching — it's a correction path, not a terminal marker, out of scope for this bead. - `repair_raw_materialization`'s docstring is updated to note its per-component call shape (`selected_raw_ids=[raw_id]`) means this daemon loop sees minimal cross-cohort benefit; the wider `selected_raw_ids=None` CLI `rebuild-index` path is where the batching pays off — same caveat lane I (polylogue-nh44) already documented for census. ## Acceptance criteria (polylogue-oikv) - Design decision recorded (this PR body): the new batch-boundary invariant is "index commits, then source terminal markers commit" at BATCH granularity, equivalent-or-stronger than the prior per-cohort invariant (still index-before-source, just deferred over N cohorts) — satisfied. - Both existing crash-recovery tests (`test_backfill_resumes_after_index_receipt_commits_before_source_terminal`, `test_backfill_resumes_after_only_some_source_markers_commit`) pass **unmodified** — satisfied; they call `backfill_historical_revision_evidence` with no `commit_batch_size`, so default (`None` → unbatched) behavior is byte-for-byte unchanged. - New crash-mid-batch test (`test_backfill_resumes_after_replay_batch_crash_discards_whole_batch_cleanly`) proves a fault between two cohorts in the same batch discards the whole batch cleanly — satisfied; also verified non-vacuous by temporarily forcing `replay_batched=False` and confirming the same assertion fails (`5 != 4`). - Benchmark shows measurable additional speedup beyond amg1's 1.05x-1.34x ceiling — satisfied (below). ## Verification - `devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_repair.py tests/unit/devtools/test_raw_authority_restart_proof.py tests/unit/devtools/test_raw_authority_scale_proof.py` — 105 passed. - Broader sweep `devtools test -k "raw_authority or raw_materialization or revision_backfill or revision_replay"` — 190 passed, 1 pre-existing unrelated failure (`test_live_multi_session_divergence_reopens_raw_authority` in `test_live_batch_support.py`, already documented by amg1's own notes as failing identically on clean master with none of this bead's/amg1's changes present). - `mypy --strict` clean on `archive.py`, `revision_backfill.py`, `repair.py`, and the test file. - `devtools verify --quick` (format+lint+mypy+render-all-check) — clean. - Ad-hoc before/after benchmark (`tests/infra/revision_backfill_benchmark.py` fixtures, not committed — same convention amg1 used), `commit_batch_size=None` vs `20` (production default `RAW_MATERIALIZATION_COMMIT_BATCH_SIZE`), median of 3 runs each: - `SMALL_PAYLOAD_SHAPE` (200 raws, ~50KB avg): 11.734s → 5.453s, **2.15x** - `LARGE_PAYLOAD_SHAPE` (80 raws, ~1.7MB avg): 9.743s → 7.492s, **1.30x** Ref polylogue-oikv Co-authored-by: Claude <[email protected]>
…er churn (#3149) ## Summary Pool dispatch in `_parse_retained_raws` now requires the pool-eligible aggregate payload to clear an amortization floor (default 48MiB, `POLYLOGUE_REVISION_PARSE_POOL_MIN_BYTES` override); 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 inside `importlib`** (`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_raws` creates a fresh `ProcessPoolExecutor` per call with `max_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 - New `_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 (#3136, keeps >256KiB payloads off the pool) is unchanged; genuinely large small-payload batches keep the pool path. - Deliberately NOT a shared long-lived executor: that would fix churn too but parks ~8 idle spawn workers (~0.5GB+ RSS with polylogue imported) inside the long-running daemon; the floor gets ~all of the win with zero idle cost. Recorded as a future option on polylogue-crd8 alongside the h1wt import-tax reduction which would lower the floor. ## Verification - `devtools test tests/unit/sources/test_revision_backfill.py` — 27 passed. - New tests: `test_pool_dispatch_floor_rejects_small_aggregate_batches` (decision thresholds, env override, invalid-env fallback) and `test_parse_retained_raws_small_batch_never_creates_a_pool` (end-to-end: a sub-floor batch must never construct a `ProcessPoolExecutor` — 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.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]>
Summary
Two safe, bounded performance levers for
polylogue-amg1: batch the raw-authority census phase's per-raw SQLite commits, and route large payloads off the parse process-pool (which was previously a net throughput loss for them). A real, deliberately-tested crash-recovery ordering invariant in the replay phase bounds this pass's scope — see below.Problem
polylogue-9p8x's own profiling (cProfile, synthetic 60-raw/1.7MB corpus) foundsqlite3.Connection.__exit__(per-write commit/fsync) at 42.6% ofbackfill_historical_revision_evidence's wall time — comparable to parse itself (40.6%). Census-phase writes (replace_raw_membership_census/bind_raw_revision) each self-commit viawith conn:, once per raw. A direct throughput benchmark also found the process-pool parse path was a net loss (0.63x) on large payloads (~1.7MB avg) — pickling the returnedParsedSessionlist back across the process boundary cost more than the parse time it saved — while it was a real win (1.22x) on small payloads (~50KB avg).Solution
replace_raw_membership_censusandbind_raw_revision/bind_source_raw_revisiongainmanage_transaction: bool = True(default unchanged), using thewith conn if manage_transaction else nullcontext()pattern already established elsewhere inarchive.py._census_historical_revision_evidencegainscommit_batch_size: when set, census writes defer commit and a batch boundary firesarchive.commit()every N raws (defaultNonepreserves per-raw commit for every existing caller — fully backward compatible). Threaded throughcensus_historical_revision_evidence/backfill_historical_revision_evidence/repair_raw_materialization; the daemon/CLI path resolves a default of 20 viaRAW_MATERIALIZATION_COMMIT_BATCH_SIZE/POLYLOGUE_RAW_AUTHORITY_COMMIT_BATCH_SIZE._parse_retained_rawsnow partitions raws by payload size (_partition_raws_by_dispatch_size): raws underPOLYLOGUE_REVISION_PARSE_DISPATCH_MAX_BYTES(default 256KiB) stay pool-eligible; raws at/above it parse sequentially in-process, avoiding the pickle-back cost that made large payloads a net loss.Deliberately NOT touched (and why)
apply_raw_revision_replay's per-cohortindex.dbcommit andfinalize_raw_parse_state's per-rawsource.dbcommit. Two existing crash-recovery tests (test_backfill_resumes_after_index_receipt_commits_before_source_terminal,test_backfill_resumes_after_only_some_source_markers_commit) pin "index commits, then source terminal marker commits" as a load-bearing ordering invariant in the replay phase. Batching across cohorts there would require deferring the corresponding source-marker commits to the same boundary, or the invariant inverts (source could become durable before its index counterpart — worse than today). That's a materially bigger, riskier change, matching this bead's own design note ("this is the hard part and needs its own adversarial review, not a quick change") — left for a follow-up rather than folded in here.Measured (honest ceiling, not a fabricated pass)
Benchmark fixture:
tests/infra/revision_backfill_benchmark.py(committed, reusable — matchespolylogue-amg1's two recorded corpus shapes). Median of 3 runs, same-session/same-machine load:commit_batch_size=20, workers=1commit_batch_size=20, workers=8commit_batch_size=20, workers=1commit_batch_size=20, workers=8This is a real, modest, consistent 1.05x–1.34x — well short of the originally-hypothesized 4x (or even the ~1.7x Amdahl estimate), which is the honest ceiling for this pass's safe scope. Full detail (including a deployment caveat:
repair_raw_materializationcallsbackfill_historical_revision_evidenceper-component, so the full benchmark gain applies most directly to the CLIrebuild-indexfull-archive scenario, not the daemon's per-component loop) recorded onpolylogue-amg1.Verification
test_census_batch_crash_loses_at_most_one_batch_and_resumes_cleanly: exactly one committed batch survives an injected fault, a resume converges to the correct terminal state with zero duplication) and the size-aware dispatch split (test_partition_raws_by_dispatch_size_routes_small_to_pool_large_sequential,test_size_aware_dispatch_keeps_large_raws_off_the_process_pool). Both proven to fail against the pre-fix code before restoring the fix.devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_repair.py— 78 passed.devtools test tests/unit/devtools/test_raw_authority_restart_proof.py tests/unit/devtools/test_raw_authority_scale_proof.py— 25 passed (crash-recovery/conservation invariants intact).-k "raw_authority or raw_materialization or revision_backfill or revision_replay"— 187 passed, 1 pre-existing unrelated failure (test_live_multi_session_divergence_reopens_raw_authority), confirmed via stash-and-rerun to fail identically on cleanorigin/master.devtools verify --quick— exit 0.testsuite (skipped per-PR by CI policy, runs post-merge).Ref polylogue-amg1