Skip to content

fix(pipeline): switch process pool to spawn, pin start method - #3143

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/process-pool-spawn
Jul 19, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/process-pool-spawn

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner

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 fix(sources): parallelize raw-authority census parse; hjpx.2/yla8 evidence #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

Problem: production ops maintenance rebuild-index sat 17+ minutes at 16%
CPU with zero index-generation growth. py-spy showed the parent parked
forever in as_completed while the forkserver process sat alive in its
serve loop with zero workers ever spawned. A minimal repro isolating
"import the CLI graph, then dispatch a pool from a thread" does not
reproduce the hang synthetically, so the exact inherited-state trigger
inside forkserver's __main__ preload could not be pinned down further
within the investigation timebox.

What changed: process_pool_context() now unconditionally returns a
spawn context instead of preferring forkserver when available. spawn
reruns __main__ fresh per worker instead of forking a single shared
preloaded process, so no thread/lock state created during CLI import
can be inherited by a worker — this eliminates the entire class of
inherited-state hazards forkserver is exposed to, regardless of
whether the exact trigger is later identified. Workers are long-lived
here, so the ~1-2s per-worker spawn import cost is amortized.

Added a config-assertion test pinning the start method explicitly
(not just "not fork"), and a regression test that dispatches a pool
from a worker thread and asserts completion within a bounded timeout,
mirroring the production asyncio-thread -> pool -> as_completed shape.

Ref polylogue-p0pw

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: 53 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: 7699c48a-eb50-4415-bfad-c0a8ea877810

📥 Commits

Reviewing files that changed from the base of the PR and between c826dd7 and 8ee753e.

📒 Files selected for processing (2)
  • polylogue/pipeline/services/process_pool.py
  • tests/unit/pipeline/test_process_pool.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/process-pool-spawn

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 5e794ac into master Jul 19, 2026
3 checks passed
@Sinity
Sinity deleted the feature/perf/process-pool-spawn branch July 19, 2026 03:10
Sinity added a commit that referenced this pull request Jul 19, 2026
…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]>
Sinity added a commit that referenced this pull request Jul 27, 2026
…helper (#3339)

## Summary
`archive_ingest.parse_sources_archive()` built its parallel-parse
process pool via a bare `ProcessPoolExecutor(max_workers=workers)`
instead of the shared, safety-hardened `process_pool_executor()` helper.
This PR routes it through the shared helper, matching every other
production process-pool call site.

## Problem
`archive_ingest.py` imported `ProcessPoolExecutor` directly from
`concurrent.futures` and constructed the pool with no explicit
`mp_context`, so it picked up whatever multiprocessing start method the
platform default happened to be — "fork" on this host/Python 3.13.
Forking a live, potentially multi-threaded async process is
unconditionally unsafe if any other thread holds a lock at fork time
(CPython's own docs call this out explicitly). This is a strictly worse
hazard class than the forkserver-preload deadlock fixed in
polylogue-p0pw (#3143): forkserver at least forks from a distinct
preloaded process, whereas bare fork() forks the calling process at the
exact moment `pool.submit()` runs.

Every other production process-pool call site already avoids this:
`pipeline/services/ingest_batch/_core.py` and
`sources/revision_backfill.py` both call
`process_pool.process_pool_executor()`, which pins the "spawn" start
method (see that function's docstring, added by p0pw) precisely to
eliminate this hazard class. `archive_ingest.py` was the one call site
that never got migrated.

Reachability: `parse_sources_archive()` is called by the public async
API facade (`Polylogue.parse_sources()`/`parse_file()`) and demo seeding
— not the live daemon's normal ingest ticks or the standard `polylogue
import` CLI flow (both of which stage through the already-safe path). So
current exposure is scripts/tests/demo-seeding with `workers > 1`, not
the daemon hot path — lower urgency than p0pw, but a real latent bug for
any future caller (e.g. an MCP tool or automation script) invoking the
async API directly with `POLYLOGUE_INGEST_PARSE_WORKERS > 1` from an
async/threaded context.

## Solution
- `polylogue/pipeline/services/archive_ingest.py`: drop the direct
`ProcessPoolExecutor` import (keep `as_completed`, still needed); import
and call `process_pool_executor()` from
`pipeline/services/process_pool.py` instead of constructing the pool
inline.
- Grepped `polylogue/` for other direct `ProcessPoolExecutor(`
constructions outside `process_pool.py` itself — this was the only one;
no further call sites needed fixing.
- `tests/unit/pipeline/test_archive_ingest_commit_batching.py`: the two
existing tests that monkeypatched `archive_ingest.ProcessPoolExecutor`
(an attribute that no longer exists after this change) now monkeypatch
`archive_ingest.process_pool_executor` instead, with an equivalent
forced-fork-context wrapper for the process-route observability test and
an equivalent spy wrapper for the worker-count override test. Added a
new `test_parallel_ingest_pool_uses_shared_safe_process_pool_executor`
regression test that exercises the real (unmonkeypatched) production
path and asserts the constructed pool's `mp_context` resolves to
`"spawn"`, plus that `archive_ingest` no longer exposes a
`ProcessPoolExecutor` attribute at all.

## Verification
- `devtools test
tests/unit/pipeline/test_archive_ingest_commit_batching.py
tests/unit/pipeline/test_process_pool.py
tests/unit/pipeline/test_ingest_batch_resource_bounds.py
tests/unit/sources/test_revision_backfill.py` → `66 passed`
- `mypy --strict polylogue/pipeline/services/archive_ingest.py
tests/unit/pipeline/test_archive_ingest_commit_batching.py` → `Success:
no issues found in 2 source files`
- `ruff check` / `ruff format --check` on both changed files → clean
- `devtools render all --check` → no drift
- `devtools verify --quick` → 17/17 steps green (also ran automatically
via the pre-push hook)

Ref polylogue-7saq

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