Repository navigation
perf: run numpy's OpenBLAS single-threaded unless the user sets otherwise - #488
Conversation
…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
left a comment
There was a problem hiding this comment.
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}
- 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 chunkhound#489, chunkhound#474, chunkhound#488, chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in chunkhound#489, chunkhound#474, chunkhound#488, chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 withOPENBLAS_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_kbis 0) commits several gigabytes before it indexes anything.Measured on a real
chunkhound mcpstart against a copy of an index (cap 2):OPENBLAS_NUM_THREADS=1Fix
chunkhound.utils.blas_threads.limit_blas_threads()setsOPENBLAS_NUM_THREADS=1withos.environ.setdefault. It runs at the top ofchunkhound.api.cliandchunkhound.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_THREADSandMKL_NUM_THREADSare not set: the numpy wheel ships OpenBLAS (threadpoolctl reportsopenblasonly), 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:OPENBLAS_NUM_THREADS=1Latency 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.pyruns each entry module in a fresh subprocess, imports numpy, and reads the OpenBLAS thread count withthreadpoolctl.chunkhound.api.cli.mainandchunkhound.mcp_server.stdioreport 1 thread. Before the fix they reported 10 (the core count).OPENBLAS_NUM_THREADS=2is kept.The test is skipped when threadpoolctl is not installed.
🤖 Generated with Claude Code, reviewed by FStrasz