Skip to content

perf(parse): shut the parse pool down after 60 s with no batch in flight - #492

Merged
HananKavitzAmat merged 7 commits into
chunkhound:mainfrom
fstrasz:fix/parse-pool-idle-shrink
Nov 24, 2026
Merged

HananKavitzAmat merged 7 commits into
chunkhound:mainfrom
fstrasz:fix/parse-pool-idle-shrink

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Updated after #487 merged. main is merged into this branch, so the diff is now this PR's change alone. #487's initializer=exit_when_parent_dies is kept on every pool this PR creates.

Problem

The parse pool in chunkhound/pipeline_bridge.py is a process-wide ProcessPoolExecutor. It is used only by bulk parsing (start-up scans, resyncs, chunkhound index), through parse_batch_callback(), but it is never shut down. So a long-lived MCP server or daemon that has scanned anything keeps indexing.max_concurrent workers (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.

  1. _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 s threading.Timer that carries a fresh token.
  2. _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.
  3. parse_batch_callback() reads the whole pool.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.
  4. One atexit hook replaces the per-pool atexit.register(pool.shutdown, ...).
  5. A comment in rust_pipeline_runner.py argued 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_lock is held.

  1. If a batch takes the lock before the timer callback, it cancels the timer and clears the token. The callback then finds a stale token, or a held lease, and returns.
  2. If the callback takes the lock first, it sees no lease and detaches the pool. The batch that follows creates a new pool.
  3. The callback detaches a pool only when no lease is held, so no task is running on it. Overlapping batches (a start-up scan and a resync in one process) each hold a lease, so the pool outlives the last of them.

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.py adds two tests.

  1. test_idle_parse_pool_is_shut_down_and_recreated uses 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 if parse_batch_callback uses a pool of its own per batch.
  2. test_parse_pool_is_never_shut_down_while_leased keeps the default 60 s idle time and calls the timer callback directly, so no real timer decides the result. It checks three things:
    1. Overlapping leases share one pool.
    2. A stale timer callback leaves the pool alone, both while a newer lease is held and after it ends.
    3. The current timer's callback shuts the pool down.
      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.py and test_parse_pool_parent_death.py now take leases instead of calling the removed accessor.

After merging main, serially on Windows: tests/contracts 134 passed and 4 skipped (the platform-specific native-install and rpath tests); tests/test_smoke.py 14 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 needs main merged 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 fork on Python 3.13 and earlier unless ChunkHound has already set it.

🤖 Generated with Claude Code, reviewed by FStrasz

fstrasz and others added 4 commits November 7, 2026 12:16
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]>
fstrasz and others added 2 commits November 11, 2026 10:06
…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]>
@fstrasz

fstrasz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

#487 is merged, so I merged main into this branch (38e13fe, an ordinary merge; nothing rebased). The Files tab now shows only this PR's change. The first commit listed, 9284a90, is #487's pre-squash commit and is already on main as 4a03648.

Two follow-up commits tighten the tests; the production change is the same:

  • 8cbfb1f: test_parse_pool_is_never_shut_down_while_leased now also fires the stale timer callback while a newer lease is held. Before, removing both guards (the token clear at lease entry and the lease-count check) went unnoticed, and the test left a live 60 s timer behind.
  • 6fe5978: test_idle_parse_pool_is_shut_down_and_recreated asserts that the batch ran on the shared pool, and it can no longer race the idle timer on a slow machine.

The description is updated, including a new section on the overlap with #493.

🤖 Generated with Claude Code

@VakninAriel VakninAriel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}

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]>
@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 24, 2026
Merged via the queue into chunkhound:main with commit 00f4421 Nov 24, 2026
27 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 24, 2026
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]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 24, 2026
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]>
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.

3 participants