Repository navigation
perf(parse): shut the parse pool down after 60 s with no batch in flight - #492
Conversation
A ProcessPoolExecutor worker blocks on its call queue, whose pipe it holds both ends of, so it never notices its parent dying. A killed ChunkHound process left every parse worker running, each holding hundreds of MB of commit, until killed by hand. Every multiprocessing child already has a sentinel for its parent (multiprocessing.parent_process()): a process handle on Windows, a pipe on POSIX. exit_when_parent_dies() waits on it from a daemon thread and exits the process when the parent is gone. It is the initializer of the parse pool and of both indexing_coordinator pools, and the first call in both per-file timeout children. A Windows job object with KILL_ON_JOB_CLOSE was the alternative: it is Windows-only (the same orphaning happens on POSIX), and each worker would have to be assigned to the job after ProcessPoolExecutor spawns it, which the executor gives no hook for. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The parse pool is a process-wide singleton used only by bulk parsing (start-up scans, resyncs, `index`), and it lived for the whole process. A long-lived MCP server therefore kept indexing.max_concurrent idle workers for its session after a single start-up scan: measured on Windows with the default 5 workers, 5 x 83-85 MB held after every scanned start. parse_batch_callback() now takes a lease on the pool for each batch. The lease count, the idle timer and the pool reference change only under _parse_pool_lock. When the last lease ends, a 60 s timer starts; a lease that begins first cancels it and clears its token, and the timer callback re-checks the token and the lease count under the lock, so the pool is never shut down while a batch is in flight, including when a scan and a resync overlap. The next batch creates a new pool, which costs about 1.5 s for 5 workers (14-file batch: 4.6 s cold vs 3.2 s warm). One atexit hook replaces the per-pool registration. The rust_pipeline_runner comment that relied on the pool never being re-created is updated: a new pool is still created only from a parse-phase call, after that run released Python's DuckDB connections. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…istic idle-shrink tests Remove the unleased _get_parse_pool(): a caller holding a pool without a lease could have it shut down by the idle timer mid-task. The reuse and parent-death tests now take leases. The overlap/stale-timer test invokes the timer callback directly instead of waiting on a real timer, and the idle test uses a 2 s idle time so its reads cannot race the timer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This branch was stacked on the pre-squash commit of chunkhound#487, which main now carries as the squash 4a03648. The five files chunkhound#487 touched are byte-identical in both, so there were no review changes to carry over; the conflicts come only from this branch rewriting chunkhound#487's lines. chunkhound/pipeline_bridge.py: the conflict was main's chunkhound#487 body of _get_parse_pool() against this branch's lease design. Kept the branch side: _get_parse_pool() stays removed, and pool creation lives in _new_parse_pool_locked(), called only from _leased_parse_pool(), with chunkhound#487's arguments (max_workers=max(1, max_workers), initializer=exit_when_parent_dies). The per-pool atexit.register(pool.shutdown, cancel_futures=True) is replaced by the single _shut_down_parse_pool_at_exit() hook, which still shuts down with cancel_futures=True. Main's auto-merged rust_mtime_epsilon() helper and its use in run_rust_pipeline() (chunkhound#500) are kept. tests/contracts/test_parse_pool_parent_death.py (add/add): main's file and this branch's differ only in the child script, where the branch takes a lease with _leased_parse_pool(1) instead of calling the removed _get_parse_pool(1). Kept the lease form; the rest of the file is main's. The diff against main is now exactly this branch's own two commits. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…olds a lease test_parse_pool_is_never_shut_down_while_leased called the stale timer callback only after the newer lease had ended, so it never tested the case in its name. Removing both guards (the token clear at lease entry and the lease-count check), which lets a timer whose callback is already waiting on the lock shut the pool down mid-batch, went unnoticed. The stale callback now also runs inside a lease, and the test cancels the real timer it stands in for, which it used to leave running. test_idle_parse_pool_is_shut_down_and_recreated read the pool without a lease while a 2 s idle timer ran, so a machine that stalled for 2 s could fail it. Every read of the pool now holds a lease. The fallback that let the test run against the code before this PR is gone. Also: the lock comment counts the guarded variables correctly, the idle shutdown comment says wait=True covers a task a failed batch left running, _shut_down_parse_pool_at_exit has a docstring, and test_parse_pool_reused drops a monkeypatch parameter this PR left unused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit read the pool only inside a fresh lease, which lost the test's one check that parse_batch_callback runs on the shared pool: a parse_batch_callback that opened its own pool per batch passed every test. The first batch now runs with an hour of idle time, so reading _parse_pool right after it cannot race the timer; the test asserts the batch's pool is the shared one, snapshots its workers, and then restarts the idle timer at 2 s with one lease on that same pool. Also: the leased-shutdown test captures the real idle timer before the stale call that could detach it, so a failing run cannot leave it running into later tests, and _shut_down_parse_pool_at_exit's docstring says what it actually leaves behind. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
#487 is merged, so I merged Two follow-up commits tighten the tests; the production change is the same:
The description is updated, including a new section on the overlap with #493. 🤖 Generated with Claude Code |
VakninAriel
left a comment
There was a problem hiding this comment.
Code Review — PR #492
Verdict: ✅ Approve
Summary
Long-lived MCP and daemon processes retained their bulk-parse worker pool indefinitely after scans, consuming memory while idle. Stacked on parent-death cleanup work, this PR leases the shared pool for each batch, retires it after 60 seconds without an active batch and recreates it on demand.
What's good
- Lease counts and timer tokens are checked under the pool lock, and parse_batch_callback consumes the complete map result inside its lease, protecting active work from idle retirement.
- The lifecycle contracts cover both real worker exit/recreation and a stale timer callback after a newer lease, rather than checking only that a shutdown method was called.
Freshness warning: Package freshness checked 2026-11-11T15:38:58.574960+00:00: STALE: included heads/eligibility changed; see overview and freshness audit before posting. This report applies only to its pinned SHA.
| Severity | Count |
|---|---|
| 🔴 Critical | 0 |
| 🟠 High | 0 |
| 🟡 Medium | 0 |
| 🟢 Minor | 0 |
Findings
No retained findings. This is not a guarantee that the code is defect-free.
Review metadata and audit
Draft review for human approval. Nothing has been posted to GitHub.
Pinned head SHA: c8605e091a1014a4d8d9cdce1e3f92d3f38d5290
Package freshness checked 2026-11-11T15:38:58.574960+00:00: STALE: included heads/eligibility changed; see overview and freshness audit before posting. This report applies only to its pinned SHA.
PR: #492
Title: perf(parse): shut the parse pool down after 60 s with no batch in flight
Author: fstrasz · Branches: fix/parse-pool-idle-shrink → main
Diff merge base: 42c5711
Review scope: Full main...HEAD contribution, merge base 42c5711 through pinned head c8605e0; all eight changed files against main, including inherited #487 parent-death commit 9284a90 and idle-shutdown commits 5a268cf/c8605e09. Traced lease/map consumption, timer races, shutdown and multiprocessing dependencies. Inherited parent-death code was read as part of the full diff; no actionable candidate against it was supplied or substantiated.
Eligibility: Resource fix: release idle parse-worker memory after 60 seconds without batches.
Overall assessment (audit only)
No actionable introduced defect substantiated. Lock-protected leases and timer tokens prevent idle retirement of an active pool; detached retirement permits safe replacement. Isolated lifecycle checks passed, while native-backed contracts were blocked.
Strength evidence
- {"strength_index": 0, "path": "chunkhound/pipeline_bridge.py", "source": "pr-492.pinned.diff", "detail": "_leased_parse_pool cancels the timer and clears its token under _parse_pool_lock; _shut_down_idle_parse_pool requires a current token and zero leases, then shuts down the detached pool outside the lock."}
- {"strength_index": 1, "path": "tests/contracts/test_parse_pool_idle_shrink.py", "source": "pr-492.pinned.diff", "detail": "test_idle_parse_pool_is_shut_down_and_recreated joins workers and compares the next parsed output; test_parse_pool_is_never_shut_down_while_leased exercises overlapping leases and stale/current tokens. No native-backed local test pass is asserted."}
Verification
- Reconciler: git -C /tmp/chunkhound-pr-reviews-20261111/pr-492 rev-parse HEAD matched manifest; git diff --check 42c5711 c8605e0 and git status --short exited 0 with no output. Both completed reports were read. All assistant-message provider/model/responseModel identities, successful runner statuses, valid provenance, pinned heads and report SHA256 values were checked; two distinct response models confirmed.
- Astra: timeout 120s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync mypy chunkhound --cache-dir=/tmp/chunkhound-pr-492-astra-a1-2pyv_f4s/mypy-cache -> exit 1, 993 errors in 89 files (374 checked). Repeat with --shadow-file chunkhound/pipeline_bridge.py /tmp/chunkhound-pr-492-astra-a1-2pyv_f4s/pipeline_bridge.parent.py --shadow-file chunkhound/services/rust_pipeline_runner.py /tmp/chunkhound-pr-492-astra-a1-2pyv_f4s/rust_pipeline_runner.parent.py --cache-dir=/tmp/chunkhound-pr-492-astra-a1-2pyv_f4s/mypy-parent-cache, using 9284a90 versions -> exit 1; cmp exit 0, byte-identical diagnostics.
- Astra: timeout 100s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync pytest -p no:cacheprovider --basetemp=/tmp/chunkhound-pr-492-astra-a1-2pyv_f4s/pytest-pool --timeout=40 tests/contracts/test_parse_pool_idle_shrink.py tests/contracts/test_parse_pool_parent_death.py tests/contracts/test_parse_pool_reused.py -> exit 2, two native-import collection errors, no tests executed.
- Astra and reconciler: timeout 40s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync python /tmp/chunkhound-pr-492-astra-a1-2pyv_f4s/check_idle_join.py -> exit 0. Reconciler observed premature is_alive assertions: 0/8, plus lease survival, worker reuse, stale-token rejection, idle shutdown/recreation, 80 overlapping leases and cleanup passing with real processes.
- Astra disclosed an initial inline worker-liveness assertion while shutdown was still concurrent; the final probe waits for the timer thread to finish. This was a probe-observation race, not a demonstrated lifecycle defect.
- Sonnet: prescribed mypy command with cache /tmp/chunkhound-pr-492-sonnet-a1-4348wrnd/mypy-cache -> exit 1, 993 errors in 89 files; no diagnostics in new lease/timer code. Its same three contract-file selection was blocked at collection by two native import errors; parent-death test was not separately run.
Limitations
- Native-dependent tests did not execute successfully: the shared environment lacks chunkhound_native.chunkhound_native. No native build, dependency installation, network call, source edit or environment repair was performed. CI is only the captured green snapshot, not a fresh run.
- Supplemental probes extract production definitions and use real external libraries/processes with simplified surrounding state. They are not end-to-end native indexing or MCP verification.
- No Windows runtime or full native integration verification. Baseline typecheck comparison isolates idle-shutdown changes against inherited parent-death commit, not every inherited change against main.
- CI is a captured snapshot, not a fresh run or a guarantee of current branch status.
- Model identities are verified declarations supplied by the reconciler; the renderer does not inspect raw reports or provenance events.
Disposition of discarded / merged findings
- Discarded Sonnet’s repeated-fork observation as an unconfirmed amplification of a preexisting default-context hazard, not a demonstrated newly introduced failure. First pool creation already occurs in a threaded server. PR #493 independently fixes explicit spawn; preserve that fix if combining branches, but do not count the same preexisting problem as a new Minor defect here.
- Discarded Sonnet’s global lease-counter observation: it requires forcibly replacing a pool with an outstanding lease through test reset/at-exit cleanup. Normal production idle retirement checks leases under the lock, so this replacement cannot occur in the active service path. No supported user-visible trigger was established.
- No independent parent-death or shutdown-outside-lock finding retained: the former is inherited stack context; the latter deliberately detaches under lock and waits outside it, allowing new callers a replacement pool.
Independent reviewer provenance
- sonnet — provider: amat-tfy; requested model: standard-chat-dev/claude-sonnet-5.5; verified response model: aws-aidev-models/us.anthropic.claude-sonnet-5-5. Identity evidence · Raw report
- astra — provider: amat-tfy; requested model: frontier-chat-dev/gpt-6-astra; verified response model: gpt-6-astra. Identity evidence · Raw report
CI snapshot
Captured: 2026-11-11T14:18:23.581921+00:00. Eligibility green: True. Counts: {"SKIPPED": 2, "SUCCESS": 23}
- site-build: SUCCESS (COMPLETED)
- site-build-validation (ubuntu-latest): SUCCESS (COMPLETED)
- site-build-validation (macos-latest): SUCCESS (COMPLETED)
- site-build-validation (windows-latest): SUCCESS (COMPLETED)
- rust-checks (ubuntu-latest): SUCCESS (COMPLETED)
- rust-checks (macos-latest): SUCCESS (COMPLETED)
- rust-checks (windows-latest): SUCCESS (COMPLETED)
- native-wheel-smoke-arm64: SUCCESS (COMPLETED)
- native-dev-macos: SUCCESS (COMPLETED)
- watchman-runtime-validation (ubuntu-latest, 3.14): SUCCESS (COMPLETED)
- watchman-runtime-validation (windows-latest, 3.14): SUCCESS (COMPLETED)
- tests (ubuntu-latest, 3.14, 1): SUCCESS (COMPLETED)
- tests (ubuntu-latest, 3.14, 2): SUCCESS (COMPLETED)
- tests (ubuntu-latest, 3.14, 3): SUCCESS (COMPLETED)
- tests (macos-latest, 3.14, 1): SUCCESS (COMPLETED)
- tests (macos-latest, 3.14, 2): SUCCESS (COMPLETED)
- tests (macos-latest, 3.14, 3): SUCCESS (COMPLETED)
- tests (windows-latest, 3.14, 1): SUCCESS (COMPLETED)
- tests (windows-latest, 3.14, 2): SUCCESS (COMPLETED)
- tests (windows-latest, 3.14, 3): SUCCESS (COMPLETED)
- old-linux-wheel-smoke (Ubuntu 20.04 (glibc 2.31), UBUNTU_20_04_IMAGE, ca-certificates curl, 3.12): SUCCESS (COMPLETED)
- old-linux-wheel-smoke (Ubuntu 22.04 + Python 3.10, UBUNTU_22_04_IMAGE, ca-certificates curl pytho...: SUCCESS (COMPLETED)
- watchman-rollout-gate: SUCCESS (COMPLETED)
- pages-artifact: SKIPPED (COMPLETED)
- deploy: SKIPPED (COMPLETED)
Reviewed by Ariel Vaknin via pi.dev
Brings in the 10 commits merged to main since this branch was last updated, including chunkhound#534's rust-checks fix. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the conflict with chunkhound#492 (parse-pool idle shrink, 00f4421) in chunkhound/pipeline_bridge.py. chunkhound#492 removed _get_parse_pool() in favour of _leased_parse_pool(), so this PR's change to _get_parse_pool() is dropped (the lease already reads the pool under _parse_pool_lock), and the BrokenProcessPool handling in parse_batch_callback() now runs inside the batch's lease. _discard_broken_parse_pool() is unchanged apart from one docstring sentence: it clears _parse_pool, so the ending lease starts no idle timer for the broken pool. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the conflict with chunkhound#492 (parse-pool idle shrink, 00f4421) in chunkhound/pipeline_bridge.py. chunkhound#492 removed _get_parse_pool(); the pool is now created only in _new_parse_pool_locked(), so this PR's spawn mp_context and its comment move there, and the lease code is upstream's. tests/contracts/test_parse_pool_spawn_context.py called the removed _get_parse_pool(): it now creates the pool through a lease and resets it with _shut_down_parse_pool_at_exit(), as upstream's parse-pool tests do. Its assertions are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Problem
The parse pool in
chunkhound/pipeline_bridge.pyis a process-wideProcessPoolExecutor. It is used only by bulk parsing (start-up scans, resyncs,chunkhound index), throughparse_batch_callback(), but it is never shut down. So a long-lived MCP server or daemon that has scanned anything keepsindexing.max_concurrentworkers (default 5) for the rest of its life. They do nothing, and each holds about 84 MB of commit (measured on Windows, with numpy's OpenBLAS single-threaded as in #488, which is still open). On a machine running several sessions, that idle memory adds up.Fix
The pool is now leased. It is shut down after 60 s with no parse batch in flight, and the next batch creates a new one.
_leased_parse_pool(max_workers)is a context manager. On entry it cancels any pending idle timer, creates the pool if there is none, and counts a lease. On exit it drops the lease, and the last lease out starts a 60 sthreading.Timerthat carries a fresh token._shut_down_idle_parse_pool(token)does nothing unless its token is still the current one and no lease is held. Otherwise it detaches the pool and then shuts it down outside the lock.parse_batch_callback()reads the wholepool.map(...)result inside the lease. The old unleased accessor_get_parse_pool()is removed. With no lease, the idle timer could shut a pool down under a caller still using it.atexit.register(pool.shutdown, ...).rust_pipeline_runner.pyargued that releasing Python's DuckDB connection is safe because "the pool is created once". It now gives the reason that still holds. A pool is created only by a parse-phase call, which runs after that run's release. That includes a pool re-created after an idle shutdown.Why the timer cannot race a batch
The lease count, the timer, the token and the pool reference change only while
_parse_pool_lockis held.Cost
Re-creating the pool costs about 1.5 s for 5 workers. Measured on a 14-file batch, the first batch took 4.6 s with a new pool and 3.2 s with a warm one. That cost is paid at most once per 60 s of parse inactivity, which for a live server usually means once per resync.
Tests
tests/contracts/test_parse_pool_idle_shrink.pyadds two tests.test_idle_parse_pool_is_shut_down_and_recreateduses a 2 s idle time. After one batch the pool is detached and its worker processes exit. The next batch creates a new pool and returns the same output. It also asserts that the batch ran on the shared pool: the first batch runs with an hour of idle time, so reading the pool cannot race the timer, and one lease then restarts the timer at 2 s. With the idle timer never started, it fails with "idle parse pool was never shut down", and it fails ifparse_batch_callbackuses a pool of its own per batch.test_parse_pool_is_never_shut_down_while_leasedkeeps the default 60 s idle time and calls the timer callback directly, so no real timer decides the result. It checks three things:It fails with the token check removed, and with both guards removed (the token clear at lease entry and the lease-count check), which would let a callback already waiting on the lock shut the pool down mid-batch. It cancels the real timer its direct call stands in for.
test_parse_pool_reused.pyandtest_parse_pool_parent_death.pynow take leases instead of calling the removed accessor.After merging
main, serially on Windows:tests/contracts134 passed and 4 skipped (the platform-specific native-install and rpath tests);tests/test_smoke.py14 passed. Upstream's CI test matrix (Ubuntu, macOS, Windows) passed on this head on my fork before I pushed it here.Overlap with #493
#493 adds
mp_context=multiprocessing.get_context("spawn")to_get_parse_pool(), which this PR removes. Whichever of the two merges second needsmainmerged in: the spawn context moves into_new_parse_pool_locked, and #493's test takes a lease instead of calling_get_parse_pool(). I'll do that merge.This PR makes #493 matter more on Linux. The pool is now re-created after every idle period, from a process that runs threads. Without an explicit spawn context, each re-creation uses the process-wide start method, which is
forkon Python 3.13 and earlier unless ChunkHound has already set it.🤖 Generated with Claude Code, reviewed by FStrasz