Skip to content

perf: run numpy's OpenBLAS single-threaded unless the user sets otherwise - #488

Merged
ofriw merged 2 commits into
chunkhound:mainfrom
fstrasz:fix/single-thread-blas
Nov 13, 2026
Merged

ofriw merged 2 commits into
chunkhound:mainfrom
fstrasz:fix/single-thread-blas

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

ChunkHound imports numpy in every process: the CLI and MCP server import it early for DuckDB threading safety, and every parse-pool worker re-imports it under spawn. numpy's bundled OpenBLAS (scipy_openblas64) starts one thread per core at import, and each thread commits its own buffer. On a 10-core Windows box, a fresh process with numpy imported commits 308 MB with the default thread count and 18 MB with OPENBLAS_NUM_THREADS=1.

ChunkHound's own numpy work is small: vector math for clustering and gap detection in research. Scoring runs in DuckDB SQL, and embedding and reranking are HTTP calls. So the threads buy nothing, and the cost is paid once per process: the MCP front process, its daemon, and each parse worker. A server with the default pool of 5 workers (plus a spawned timeout child per file when per_file_timeout_min_size_kb is 0) commits several gigabytes before it indexes anything.

Measured on a real chunkhound mcp start against a copy of an index (cap 2):

Default threads OPENBLAS_NUM_THREADS=1
Peak commit, whole process tree 3,118 MB 1,025 MB
Per spawned worker 372 MB 83 MB
Idle commit after the scan 2,442 MB 649 MB

Fix

chunkhound.utils.blas_threads.limit_blas_threads() sets OPENBLAS_NUM_THREADS=1 with os.environ.setdefault. It runs at the top of chunkhound.api.cli and chunkhound.mcp_server, before anything there imports numpy. Spawned workers inherit the environment, so they need no separate call. An explicit value set by the user still wins.

OMP_NUM_THREADS and MKL_NUM_THREADS are not set: the numpy wheel ships OpenBLAS (threadpoolctl reports openblas only), and neither variable would change it.

Measurements

chunkhound search --single-hop, end to end (process start, query embedding, DuckDB scoring), against a copy of a 20k-chunk index, 3 queries, 9 runs per setting, interleaved:

Default threads OPENBLAS_NUM_THREADS=1
Median wall time 17,267 ms 17,317 ms
Range 15,434-18,795 ms 16,232-17,933 ms
Peak commit (median) 913 MB 327 MB

Latency is unchanged within run-to-run noise, with identical results for every query. On a live machine, restarting one long-running MCP server (front process, daemon and its idle pool) with the setting in its environment raised free commit from 7.8 to 11.2 GB. That is a single observation of old processes against new ones, not a controlled measurement.

Test

tests/test_blas_single_thread.py runs each entry module in a fresh subprocess, imports numpy, and reads the OpenBLAS thread count with threadpoolctl.

  1. chunkhound.api.cli.main and chunkhound.mcp_server.stdio report 1 thread. Before the fix they reported 10 (the core count).
  2. An explicit OPENBLAS_NUM_THREADS=2 is kept.

The test is skipped when threadpoolctl is not installed.

🤖 Generated with Claude Code, reviewed by FStrasz

…wise

numpy's wheels bundle OpenBLAS, which on import starts a thread per core
and commits a work buffer for each. On a 10-core Windows machine
`import numpy` alone committed 308 MB, against 18 MB with
OPENBLAS_NUM_THREADS=1. ChunkHound imports numpy in the CLI, the MCP
front process, the daemon and every spawned parse worker, so each paid
it: idle daemon parse workers measured ~370 MB each.

Both entry packages (chunkhound.api.cli for the chunkhound script and
python -m chunkhound.api.cli.main, chunkhound.mcp_server for
chunkhound-mcp) now setdefault OPENBLAS_NUM_THREADS=1 before anything
imports numpy. Spawned workers inherit the environment. An explicit
value still wins. ChunkHound's numpy work is small vector math
(embeddings come from the provider, vector search runs in DuckDB).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
macOS numpy wheels are built on Apple's Accelerate, so threadpoolctl
reports no OpenBLAS pool there and all three checks failed on the macOS
CI runner with `AssertionError: []`. OPENBLAS_NUM_THREADS does not apply
to Accelerate, so there is nothing to check: skip with the reason instead
of failing. Where OpenBLAS is loaded the assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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 #488

Verdict: ✅ Approve

Summary

NumPy's OpenBLAS worker threads and buffers were adding substantial per-process memory overhead to CLI/MCP processes and spawned parse workers. This PR defaults OPENBLAS_NUM_THREADS to 1 before entry-point dependency imports, while retaining an explicit user-provided value.

What's good

  • Using os.environ.setdefault preserves user thread-count choices instead of unconditionally overriding tuning, and the shared helper is called before NumPy-importing CLI/MCP dependencies.
  • The tests use fresh entry-point subprocesses and query OpenBLAS through threadpoolctl, checking the actual library thread count for both the default and an explicit value of 2.

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: bde3b09ac13a64a5763ac1aa665a2f6a262e8590

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: #488

Title: perf: run numpy's OpenBLAS single-threaded unless the user sets otherwise

Author: fstrasz · Branches: fix/single-thread-blas → main

Diff merge base: 42c5711

Review scope: Entire pinned merge-base 42c5711..bde3b09 diff: CLI initializer, MCP initializer, new utils/blas_threads.py, and test_blas_single_thread.py. Verified parent-package import behavior, pyproject console scripts and daemon environment forwarding. No stacked-PR overlap in this four-file change.

Eligibility: Resource fix: prevent excessive OpenBLAS memory/thread usage unless explicitly user-configured.

Overall assessment (audit only)

Both independent models found no actionable introduced bug. The CLI/MCP package initializers set the OpenBLAS thread default before dependency imports, preserve explicit user settings, and allow daemon/worker inheritance. Full entry-point tests remain blocked by the missing native extension.

Strength evidence

  • {"strength_index": 0, "path": "chunkhound/utils/blas_threads.py; chunkhound/api/cli/__init__.py; chunkhound/mcp_server/__init__.py", "source": "pr-488.pinned.diff", "detail": "limit_blas_threads sets only OPENBLAS_NUM_THREADS with setdefault; both package initializers call it before their subsequent dependency imports."}
  • {"strength_index": 1, "path": "tests/test_blas_single_thread.py", "source": "pr-488.pinned.diff", "detail": "test_entry_points_run_openblas_single_threaded covers CLI and stdio entry modules; test_an_explicit_openblas_setting_wins checks 2. The subprocess probe reads threadpool_info and skips non-OpenBLAS builds; local entry-point execution remains subject to existing native-extension limitations."}

Verification

  • Reconciler verified both runner jobs succeeded, valid/error-free settled provenance, pinned worktree HEAD and metadata head, SHA256 of each complete report, and all captured assistant-message provider/model/responseModel identities; the two backend response models are distinct.
  • Reconciler verified the complete four-file diff, import-light parent packages, pyproject.toml:149-150 entry points and daemon/discovery.py:1072,1087,1109 environment inheritance against pinned source.
  • 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-488-astra-a1-k0jemw2s/mypy-cache exited 1: 993 errors in 89 files (374 checked). Shadow baseline run with --cache-dir=/tmp/chunkhound-pr-488-astra-a1-k0jemw2s/mypy-baseline-cache --shadow-file chunkhound/api/cli/__init__.py /tmp/chunkhound-pr-488-astra-a1-k0jemw2s/base-cli-init.py --shadow-file chunkhound/mcp_server/__init__.py /tmp/chunkhound-pr-488-astra-a1-k0jemw2s/base-mcp-init.py also exited 1; diagnostics identical after normalizing the MCP line shift. Baseline copies came from git show 42c5711 and retained the new helper; not a separate baseline checkout.
  • Sonnet reported timeout 120s env UV_PROJECT_ENVIRONMENT=… uv run --no-sync mypy chunkhound --cache-dir=<tmp>/mypy-cache: 993 errors in 89 files; no baseline comparison. Ellipses reflect the abbreviated command in that report, not a reconstructed exact invocation.
  • Astra: timeout 150s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync pytest tests/test_blas_single_thread.py -p no:cacheprovider --basetemp=/tmp/chunkhound-pr-488-astra-a1-k0jemw2s/pytest-blas exited 1: 3 failed in 0.45s before thread assertions, because subprocess entry imports cannot load chunkhound_native.chunkhound_native. Sonnet’s corresponding -q run reported 3 failed in 0.47s for the same reason.
  • Astra: timeout 30s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync python -c 'import chunkhound.api.cli.main' and the same command for import chunkhound.mcp_server.stdio each exited 1, confirming missing native extension on unchanged dependency paths.
  • Astra isolated probe command (run with env -u OPENBLAS_NUM_THREADS and then env OPENBLAS_NUM_THREADS=2, plus UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1): uv run --no-sync python -c 'import chunkhound.api.cli; import os, numpy; from threadpoolctl import threadpool_info; pools = [p["num_threads"] for p in threadpool_info() if p.get("internal_api") == "openblas"]; expected=int(os.environ["OPENBLAS_NUM_THREADS"]); print({"expected":expected,"pools":pools}); assert pools and set(pools)=={expected}'. Both exited 0: [1] default, [2] explicit setting. Sonnet independently reported [1] after CLI-package import versus 8 for plain NumPy.

Limitations

  • The three full entry-point regression tests did not pass locally: missing chunkhound_native.chunkhound_native prevents subprocess imports. No environment repair, builds or network access performed. Isolated package probes establish thread configuration only, not full CLI/MCP startup or process-tree memory savings.
  • Linux-only verification; real Windows behavior and reported memory benchmarks not independently measured. Full suite not run. Mypy remains failing at the documented baseline level.
  • 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

  • Neither model proposed an actionable finding. Sonnet’s programmatic-import environment side-effect note matches the intentional entry-package policy and preserves existing user values; not retained as a defect.
  • The missing-native pytest failures occur before thread-count assertions through unchanged dependency imports; treated as verification limitations, not introduced bugs or grounds to claim tests passed.

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

@ofriw
ofriw added this pull request to the merge queue Nov 13, 2026
Merged via the queue into chunkhound:main with commit 8756391 Nov 13, 2026
25 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
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