Repository navigation
fix(sources): parallelize raw-authority census parse; hjpx.2/yla8 evidence - #3122
Conversation
…cache Problem: maintenance/replay.py::rebuild_index_from_source accepted ingest_workers but deleted it, funneling the offline rebuild-index CLI path's parser census into one sequential asyncio.to_thread call. Its spill cache (_ParsedSessionSpill) also silently disabled caching because the CLI path passed max_payload_bytes=None, so every accepted revision was reparsed during replay after census already parsed it (measured live: ~204 sessions/35min single-core, polylogue-9p8x). Solution: _census_historical_revision_evidence now parses pending raws through a new _parse_retained_raws helper that spreads read-only blob->ParsedSession decode across a ProcessPoolExecutor (polylogue/sources/revision_backfill.py); archive writes still apply in fixed pending_rows order regardless of worker completion order, so parallel and sequential runs are byte-identical (proven by test_parallel_census_matches_sequential_archive_state). Introduced max_cached_payload_bytes as a spill-cache bound independent of max_payload_bytes (the resource-envelope block): the two were previously the same parameter, so passing a finite cache bound on the CLI's unbounded (selected_raw_ids=None) full-archive census would have immediately raised RawRevisionReplayResourceBlockedError, since raw_membership_census_rows(None) returns every raw in the archive in one selection. repair_raw_materialization (storage/repair.py) and rebuild_index_from_source both gained ingest_workers, defaulting to a new shared resolve_parse_worker_count() (process_pool.py), so the daemon convergence path and the hjpx.2 scale-proof harness (devtools/raw_authority_scale_proof.py, unmodified) get parallel census automatically. archive_ingest.py's existing worker-count helper now delegates to the shared resolver instead of duplicating it. Evidence-driven correction to the original AC: cProfile on a synthetic 60-raw/1.7MB-avg-payload corpus shows SQLite commit/fsync (sqlite3.Connection.__exit__) at 42.6% of wall time versus parse at 40.6% -- comparable, not parse-dominated. Parallelizing only the parse share caps realistic speedup near 1.7x (Amdahl), not the originally hypothesized 4x; measured 1.22x on 200 small (~50KB) payloads and 0.63x (worse) on 80 larger (~1.7MB) payloads, where cross-process pickling of parsed sessions exceeded the parse-time savings. Filed polylogue-amg1 for the remaining commit-batching/size-aware-dispatch levers rather than forcing that larger, transaction-boundary-touching change into this fix. Verification: - devtools test tests/unit/sources/test_revision_backfill.py: 18 passed - devtools test -k raw_materialization: 91 passed - devtools test -k raw_authority: 57 passed - devtools test tests/unit/storage/test_incremental_rebuild_equivalence.py tests/unit/cli/test_archive_maintenance_cli.py: 58 passed - devtools verify --quick: exit 0 (16/16 steps) Ref polylogue-9p8x Co-Authored-By: Claude <[email protected]>
Problem: yla8 needs a current live-archive preflight before the operator can decide whether to authorize the ordinary catch-up gate, but the archive is mid-restore from the same-day poisoned-index incident and its own authority proof (hjpx.2) has not completed at scale yet. Solution: read-only packet (no live mutation) comparing current population counts against the 2026-07-15 baseline, a backup-manifest currency verdict (most recent verified backup is 6 days stale), a blocker inventory citing polylogue-5jak/emx2/5vft/hjpx.2, and the exact apply command for reference. Recommendation is to hold authorization; ends with the single yes/no question for the operator. Verification: read-only commands only (`ops status --json --full`, `ops backup --check`); no archive mutation. Ref polylogue-yla8 Co-Authored-By: Claude <[email protected]>
Problem: hjpx.2 needs a proof-report artifact recording verdict per law (envelope/health/fairness/fixed-point/mutations) regardless of whether the July-15-scale execution itself completes this session. Solution: report distinguishes proven-at-small-scale (envelope, fairness, conservation, interruption/resume, pressure-gate mutations -- all verified passing this session, several inherited from prior PRs like #3080/#3029/#3031) from genuinely unproven (daemon-health responsiveness -- confirmed no harness runs an actual daemon process to probe; filed polylogue-agvo) and not-yet-executed-at-cardinality (the July-15-shaped run itself -- three self-aborts under sustained, genuine host I/O contention across 4+ concurrent warroom lanes, receipts recorded). Explicitly states hjpx.2 is not closable this session rather than forcing a close on unmet AC. Verification: cited tests re-run and confirmed passing (see report for exact node list); no archive mutation. Ref polylogue-hjpx.2 Co-Authored-By: Claude <[email protected]>
…us worker Problem: rebasing polylogue-9p8x's parallel census parse (8a1f827) onto master's #3113 (Hermes SQLite-detection fix to _parse_one) left _census_parse_worker calling _parse_one without payload_path/ archive_root, unlike the sequential parse_retained_raw_sessions. Functionally harmless (the bounded temp-file spill fallback in _sqlite_payload_path still parses correctly) but loses the "prefer the already-materialized blob path, no copy" optimization #3113 added, and the parallel path had no regression coverage proving it matches the sequential path's parameter threading for Hermes state.db/ verification_evidence.db raws specifically. Solution: thread payload_path (only computed for Provider.HERMES, verified to exist on disk first) and archive_root through the worker's _parse_one call, matching parse_retained_raw_sessions exactly. Added test_parallel_census_threads_hermes_sqlite_payload_path (two independent single-session state.db raws, forcing ingest_workers>1 to actually dispatch through the pool) and updated this report with the fourth self-abort receipt plus a diagnostic finding: attempts 3 and 4 both aborted at the identical code location right after generation began, despite attempt 4 requiring 5 minutes of sustained external quiet beforehand -- suggesting the generation phase's own I/O may be self-inducing the pressure gate, not purely external contention. Filed polylogue-cmw2 to investigate. Verification: - devtools test tests/unit/sources/test_revision_backfill.py: 18 passed - devtools test -k "raw_materialization or raw_authority": 148 passed - devtools verify --quick: exit 0 (16/16 steps) Ref polylogue-9p8x Ref polylogue-hjpx.2 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: 15 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 (10)
✨ 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 |
## Summary - `process_pool_context()` now unconditionally returns a `spawn` multiprocessing context instead of preferring `forkserver` when available. - Added a config-assertion test pinning the exact start method, and a regression test that dispatches a real pool from a worker thread (mirroring the production `asyncio.to_thread -> pool -> as_completed` shape) and asserts bounded-timeout completion. ## Problem Production `ops maintenance rebuild-index` sat 17+ minutes at 16% CPU with zero index-generation growth (2026-07-19). `py-spy` showed the parent process parked forever in `as_completed` (`revision_backfill.py:719`) while the forkserver process sat alive in its serve loop — the multiprocessing resource-tracker and forkserver were both running, but **zero pool workers were ever spawned**. Killing the run and resuming with `POLYLOGUE_INGEST_PARSE_WORKERS=1` (the sequential escape hatch) immediately went to 97% CPU and the generation resumed growing, confirming the pooled dispatch path itself was the failure, not the parse work. This pooled dispatch branch (`_parse_retained_raws` in `sources/revision_backfill.py`) had effectively been dead code before #3122 (merged 2026-07-18) — `ingest_workers` was previously accepted and immediately discarded. The very first real exercise of the newly-activated pool hit this hang within ~8 hours of that merge. ## Investigation `forkserver` forks every worker from a single process that preloads `__main__` once via `runpy.run_path(sys.argv[0], run_name="__mp_main__")` at forkserver boot. In production `sys.argv[0]` resolves to `.venv/bin/polylogue`, whose top-level code is `from polylogue.cli import main` — so the forkserver process runs polylogue's entire CLI import graph before ever forking a worker. Any thread or lock created as a side effect of that import would be inherited (already running/held) by every subsequently forked worker, which is a well-known forkserver hazard class. An extended repro that isolates exactly this shape — a real script file (so `sys.argv[0]` resolves like production), top-level `from polylogue.cli import main`, then dispatching `process_pool_executor()` from a worker thread under both `forkserver` and `spawn` — completed in 0.6s under **both** contexts. So the leading hypothesis from the initial triage does not reproduce synthetically in isolation; the exact trigger inside the live forkserver preload was not pinned down further within the investigation timebox. Full bisect trail is recorded on `polylogue-p0pw`. ## Solution Per the fix direction agreed in the bead notes, applied the unconditional-safe option rather than continuing to chase the exact trigger: `spawn` reruns `__main__` fresh per worker instead of forking one shared preloaded process, so no thread/lock state created during CLI import can ever be inherited by a worker. This structurally eliminates the whole class of inherited-state hazards forkserver is exposed to, independent of whether the precise trigger is later identified. The cost is ~1-2s import per worker, which is acceptable since pool workers here are long-lived and reused across many parse tasks, not spun up per task. Modules touched: `polylogue/pipeline/services/process_pool.py` (the fix + explanatory docstring), `tests/unit/pipeline/test_process_pool.py` (two new tests). ## Audit (report only, no code change) Per AC item 4 ("verify daemon census throughput with pooling active"), audited whether the daemon's convergence process pool or the #3122-wired census pool has ever actually parallelized in production: - `DaemonConverger.start()` logs `"started with N worker(s)"` when any `ConvergenceStage` is `cpu_bound=True`, else `"started without worker pool"`. `journalctl` across 30+ `polylogued` restarts (2026-07-16..19) shows **only** `"started without worker pool"` — zero exceptions. Every registered stage (`fts`, `embed`, `claude_workflow`, `insights`, `standing-queries`) sets `cpu_bound=False`, so this pool has never activated. This corroborates the independent finding on `polylogue-7uqr` (converger pool machinery is dead), which I cross-linked. - The #3122-wired census/replay pool is reachable from a live daemon via the HTTP `--daemon` bridge (`daemon/http.py`), but `journalctl` shows every `ops maintenance rebuild-index` invocation on this host was a direct CLI run, never with `--daemon` — so that variant has zero production exercise to date. - Filed `polylogue-7saq` as separate follow-up debt: `archive_ingest.py`'s `parse_sources_archive()` builds its `ProcessPoolExecutor` directly without going through `process_pool_context()`, so it uses the platform-default start method (`fork` on this host) — a strictly more dangerous hazard class than forkserver. Currently reached only by the public async API facade and demo seeding, not the daemon's normal ingest ticks (which already go through the now-fixed `process_pool_executor()` helper) — out of this PR's scope. ## Acceptance criteria 1. **Reproduce or conclusively explain the forkserver no-worker deadlock** — partially satisfied: mechanism explained (forkserver forks every worker from one preloaded process that runs the full CLI import graph in production), but not conclusively reproduced in isolation — the isolated import+dispatch repro passed under both contexts. Documented honestly on the bead. 2. **Switch to a start method that demonstrably spawns workers under a threaded parent** — satisfied: `spawn`, verified by the new regression test. 3. **Regression test that a pool dispatch from a worker thread completes** — satisfied (`test_process_pool_dispatch_from_worker_thread_completes`). Note: this test does not reproduce the pre-fix hang either, consistent with the repro gap above — it's a forward-looking guard, not proof the pre-fix code fails it. 4. **Verify daemon census throughput with pooling active** — answered via audit above: no production daemon-census throughput exists yet to measure (the pooled path has only run via direct CLI so far). 5. **Remove/keep the `workers=1` escape hatch documented** — kept as-is; `resolve_parse_worker_count()`'s existing `env_var` override remains the documented escape hatch. ## Verification - `devtools test tests/unit/pipeline/ -k process_pool` — 7 passed in 8.05s. - `devtools verify --quick` — all 16 steps green (ruff format/check, mypy --strict, render all --check, topology/layering/closure-matrix, schema roundtrip, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly). - Not run: full `devtools verify --all` / broad pytest suite (per-PR CI intentionally skips the heavy suite; will run post-merge on master per repo convention). Ref polylogue-p0pw 🤖 Generated with [Claude Code](https://claude.com/claude-code) 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]>
Summary
rebuild-indexpath's deadingest_workersparameter and silent double-parse (polylogue-9p8x).Problem
maintenance/replay.py::rebuild_index_from_sourceacceptedingest_workersbut immediatelydeleted it, funneling the CLIrebuild-indexcommand's parser census into one sequential call. Its spill cache also never activated on that path because it receivedmax_payload_bytes=None, so every accepted revision was reparsed during replay after census had already parsed it once (measured live: ~204 sessions/35min single-core).Separately, hjpx.2 needed a July-15-archive-shape proof of raw-authority replay convergence, and yla8 needed a current live-archive preflight before any operator authorization decision.
Solution
polylogue/sources/revision_backfill.py: new_parse_retained_raws/_census_parse_workerspread read-only blob→ParsedSessiondecode across aProcessPoolExecutor; archive writes still apply in fixedpending_rowsorder regardless of worker completion order, proven byte-identical to sequential (test_parallel_census_matches_sequential_archive_state). Newmax_cached_payload_bytesparameter decouples the spill-cache bound from the resource-envelope block (the two were previously the same parameter — passing a finite cache bound on the CLI's unboundedselected_raw_ids=Nonefull-archive census would otherwise immediately raiseRawRevisionReplayResourceBlockedError, sinceraw_membership_census_rows(None)returns every raw in the archive in one selection).polylogue/storage/repair.py,polylogue/maintenance/replay.py: both gainedingest_workers, defaulting to a new sharedresolve_parse_worker_count()(polylogue/pipeline/services/process_pool.py), so the daemon convergence path and the hjpx.2 scale-proof harness get parallel census automatically with no harness changes needed.#3113(Hermes SQLite-detection fix to_parse_one); added parity so the parallel worker threads the real on-disk blob path through for Hermes raws the same way the sequential path does..agent/reports/yla8-authorization-packet-2026-07-18.md: read-only live-archive audit (no mutation). Recommends holding authorization: no current verified backup (6 days stale), archive mid-restore (99.8% unmaterialized), and at observed throughput a full drain would take days-to-weeks withoutpolylogue-5jaklanding..agent/reports/hjpx2-july15-scale-proof-2026-07-18.md: verdict per law. Envelope/fairness/conservation/interruption-resume mechanisms are proven (via existing + this session's regression tests); daemon-health responsiveness is a confirmed harness gap (polylogue-agvofiled); the July-15-scale execution itself self-aborted 4 times under genuine, sustained host I/O contention (receipts included, plus a diagnostic finding that the generation phase may be self-inducing pressure —polylogue-cmw2filed).Alternatives rejected
max_payload_bytes=64MiBon the CLI path) was not applied as literally stated: it would have broken the unbounded full-archive rebuild by activating the resource-envelope block archive-wide. Introduced the separatemax_cached_payload_bytesparameter instead.polylogue-amg1as separately-scoped follow-up rather than force a larger, transaction-boundary-touching change into this PR.polylogue-agvo).Verification
devtools test tests/unit/sources/test_revision_backfill.py: 18 passeddevtools test -k "raw_materialization or raw_authority": 148 passeddevtools test tests/unit/devtools/test_raw_authority_scale_proof.py: 21 passeddevtools test tests/unit/devtools/test_raw_authority_restart_proof.py: 4 passeddevtools test tests/unit/storage/test_incremental_rebuild_equivalence.py tests/unit/cli/test_archive_maintenance_cli.py: 58 passeddevtools verify --quick: exit 0 (16/16 steps), green after every commitAC matrix
ingest_workers) and Fix 2 (decouple spill cache) — satisfied, tested. AC4 (≥4x measured speedup) — not satisfied, corrected by evidence to ~1.2-1.7x (Amdahl-limited); deferred topolylogue-amg1.polylogue-agvofiled. July-15-scale execution (AC1/AC6/AC7) — not achieved this session; 4 honest self-abort receipts recorded,polylogue-cmw2filed for the generation-phase self-induced-pressure finding. Bead remains open, not force-closed.Ref polylogue-9p8x
Ref polylogue-yla8
Ref polylogue-hjpx.2
Co-Authored-By: Claude [email protected]