Skip to content

fix(pipeline): an incremental run with nothing to write never takes the database from readers - #500

Merged
HananKavitzAmat merged 3 commits into
chunkhound:mainfrom
fstrasz:fix/rust-startup-reader-lock-upstream
Nov 11, 2026
Merged

HananKavitzAmat merged 3 commits into
chunkhound:mainfrom
fstrasz:fix/rust-startup-reader-lock-upstream

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Every incremental Rust run hands the database to Rust before Rust's own diff has decided whether there is anything to do. run_rust_indexing_phase() publishes set_rust_pipeline_in_progress(True), closes Python's connections, runs the pipeline and reconnects, and every DB-backed MCP call in that window fails with DatabaseRustPipelineInProgressError. An MCP server's start-up catch-up does this on every start. The most common start changes nothing: a fresh git worktree seeded from another checkout's index has new mtimes and identical bytes.

Measured on Windows against a copy of a real 1174-file index, starting chunkhound mcp on a fresh checkout and probing a regex search every 2 s:

  1. 0 content changes, first start: searches refused from 32.6 s to 78.0 s (46 s).
  2. 0 content changes, second start: refused from 31.0 s to 69.7 s (39 s).

The pipeline log for these runs reports files=0, chunks=0, embeds=0. Rust spent about 1.5 s diffing; the remaining ~35 s went to opening the file and compacting it, on a run that wrote nothing.

Fix

process_directory() now decides on Python's own connection, before any handoff, whether the Rust run has anything to write. The new chunkhound/services/rust_incremental_precheck.py:

  1. reads the same columns as the Rust differ's snapshot (FILE_STATE_SELECT, including the ::TIMESTAMPTZ mtime cast);
  2. classifies each discovered file by the rules of differ.rs::compute_diff: no row or a NULL mtime means changed; a different mtime means changed unless the xxh3_64 digest matches the stored content_hash; an equal mtime with a different known size means changed;
  3. runs in asyncio.to_thread, so hashing a fresh worktree never blocks the event loop;
  4. reads the mtime epsilon through pipeline_bridge.rust_mtime_epsilon(config), the same function that sets the value Rust receives, so the two can't disagree. (The Python pipeline's own reader stays separate: it turns an explicit 0.0 into 0.01, which Rust does not.)

plan_rust_run() in the same module turns that classification into the run Rust is given (or none), so the Rust-parity rules and the decision built on them live in one place.

Cost. Every start with stale mtimes hashes the files whose mtime differs, on a worker thread: in a fresh worktree that's the whole tree, about 16 s on the 1174-file index above. Searches keep answering during it; before this change, the same hashing happened inside Rust's diff while readers were refused.

Files Rust indexes with no chunks (an unknown file type matched by the include patterns, an empty file) still get a files row with their size and hash, so they count as unchanged on the next start and don't force a handoff. Checked with a repo containing both: the second and third runs logged Diff: 0/5 changed and never started Rust.

Then:

  1. Nothing changed and nothing to remove: Rust is not started. HNSW indexes that a crashed earlier run left missing are restored through the provider (ensure_all_hnsw_indexes_async), as Rust's open() would have done.
  2. Changes and no removals: Rust receives only the changed files, with cleanup off, so its own diff no longer stats and hashes the whole tree while it owns the file. Cleanup must be off on this path, because Rust treats every row missing from the list it receives as a deleted file.
  3. Removals: the full file list, unchanged.

force_reindex is unchanged. A file is called unchanged only when its bytes are: either its hash matches, or its mtime and size both match (the same trust Rust's mtime fast path already places in them).

One behaviour changes deliberately: an otherwise-empty run no longer gives Rust a chance to compact. Python-side writes are still compacted by the provider's sampled compact_if_needed, and Rust still checks after every run that writes. Note that Rust's waste metric currently reports compaction as due on every run for an index with embeddings (compaction_stats counts the FLOAT[N] column's list-child segment as rows: 2,095,104 "stored" against 20,547 live, ratio 0.981). That is a separate fix to the native crate, which is tracked separately.

Alternative considered: Python deletes removed rows and Rust always gets the changed subset

Rejected. The provider's batch delete refuses to run while a realtime transaction is open, which would fail the start-up scan. It also snapshots every deleted row for rollback, and it would leave a removal-only run uncompacted. Removals are rare at start-up, and today's full path already handles them correctly.

After

The same harness and inputs:

  1. 0 content changes, first start: 0 refusals across 53 probes; the initial scan took 15.9 s instead of 58.8 s.
  2. 0 content changes, second start: 0 refusals.
  3. 20 edited files: unchanged (53 s, against 54 s before). The window is now the native compaction above plus parse and embed while Rust holds the file. Narrowing that needs native changes.

Tests

tests/contracts/test_rust_startup_reader_access.py:

  1. test_unchanged_reindex_never_takes_the_database_from_readers indexes a repo, gives every file a new mtime without changing its bytes, re-runs, and asserts the run never published Rust ownership, a search answers, and every row survives.
    a. Before the fix it fails (assert True not in [True, False]).
    b. After, it passes.
  2. test_editing_one_file_reindexes_it_and_keeps_every_other_file guards the cleanup-off requirement of the narrowed run. Deleting that line makes it fail, because the unedited files' rows are removed.
  3. test_precheck_agrees_with_the_rust_differ is the parity contract: for each case it takes the precheck's verdict, then hands the real Rust pipeline the full file list (precheck bypassed) and asserts Rust re-indexes exactly what the precheck called changed. Cases: a NULL stored mtime, the same mtime with a different size, a new mtime with no stored hash (all re-indexed), a new mtime with identical bytes, and an untouched file (neither re-indexed). Deleting the size check from the precheck fails only the size case; treating a NULL mtime as unchanged fails only that case.
  4. test_unchanged_reindex_restores_an_hnsw_index_a_crash_left_missing drops the HNSW index, runs an unchanged incremental run, and asserts Rust was never started and the index is back. Replacing the skip path's ensure_all_hnsw_indexes_async() with pass makes it fail.

On this branch (on main), run serially on Windows: both new tests, the Rust contract tests (orphan-cleanup parity, HNSW kept on empty diff, skipped/filtered, unknown files, disk usage), the runner unit tests, skip-unchanged, the LanceDB fallback and smoke. Result: 45 passed and 5 failed. All 5 failures are test_cli_help_commands hitting its 5 s limit on uv run chunkhound ... --help.

The same commits were also tested on my fork, whose base carries some of my other open PRs. There the full suite ran serially. Every file with a failure was then re-run with and without this change under identical settings: 32 failed with it, 36 without it, and 65 errors each. No failure appears only with the change. The failures are environment-bound (site build packages, CLI subprocess timeouts, MCP handshake timeouts). test_cli_help_commands times out at its 5 s subprocess limit on a different parameter from run to run.

Two tests in tests/integration/test_directory_indexing_hnsw.py ([ensure_all_hnsw_indexes]) fail on this machine identically with and without this change. They run the Python pipeline (CHUNKHOUND_USE_RUST=0) and wait 5 s for ensure_all_hnsw_indexes to start. With the wait raised to 60 s, both pass.

Related: #238, #83 (worktree support): a worktree seeded from another checkout's index is the start this makes cheap.

🤖 Generated with Claude Code

fstrasz and others added 2 commits November 9, 2026 10:45
…he database from readers

Every incremental Rust run handed the database to Rust before Rust's own
diff ran: set_rust_pipeline_in_progress(True), close Python's connections,
run, reconnect. Every search in that window is refused with
DatabaseRustPipelineInProgressError. An MCP server's start-up catch-up does
this on every start, and the common start changes nothing -- a fresh
worktree seeded from another checkout's index has new mtimes and identical
bytes. Measured on a 1174-file index (real `chunkhound mcp`, regex search
every 2 s): a start with 0 content changes refused searches for 46 s, and
39 s on the next start. Rust spent ~1.5 s diffing and the rest opening the
file and compacting it on a run that wrote nothing.

process_directory() now decides on Python's own connection, before any
handoff, whether the Rust run has anything to write. The new
rust_incremental_precheck reads the same file-state columns as the Rust
differ's snapshot and classifies files by its rules (mtime, then xxh3_64
against the stored content_hash, then size), off the event loop:

- nothing changed or removed: Rust is not started; HNSW indexes a crashed
  run left missing are restored through the provider, as Rust's open()
  would have done;
- changes and no removals: Rust gets only the changed files with cleanup
  off, so its own diff no longer hashes the whole tree while it owns the
  file;
- removals: unchanged, the full list as before.

A file is called unchanged only when Rust would call it unchanged; a
matching hash means identical bytes. force_reindex is unchanged.

An otherwise-empty run no longer gives Rust a chance to compact. Python-side
writes are still compacted by the provider's sampled compact_if_needed, and
Rust still checks after every run that writes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sh; guard the narrowed run

compute_file_hash raises ValueError for a path that stopped being a regular file after stat(); count that file as changed, as Rust does, instead of failing the scan. The docstring now states the unchanged rule exactly.

New contract test: editing one file with nothing removed reindexes it and keeps every other file. It guards the cleanup-off requirement of the narrowed Rust run; removing that line deletes the unedited rows and fails the test.

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

Copy link
Copy Markdown
Collaborator

Summary: The fix is sound and its classification matches the Rust differ, but there are two small duplications and a few coverage gaps that I'd like addressed or acknowledged before merge.

Strengths:

  • Conservative design. Every ambiguous case (no row, NULL mtime, stat failure, hash failure, unreadable file) is
    classified as changed. removed is computedsagreement with Rust sends the run down thefull path.
  • Correct cleanup handling. The changed-substest_editing_one_file_reindexes_it_and_keeps_every_other_file guards that requirement.
  • No regression in stale mtimes. differ.rs dme for hash-matched files either, so skipping Rust leaves the DB in the same state.
  • Contract-style tests. They assert user-visr handed to Rust and search still works)instead of internal calls, in line with the project's testing philosophy.
  • Fits the existing concurrency model. It ru DB thread, off the event loop.

Issues:

  • Major – duplicated classification logic in two languages. rust_incremental_precheck.py:57-110 re-implements
    differ.rs::compute_diff, and the only guarg. If Rust's rules change (a new gate, adifferent hash), Python could call a file unchanged and skip a run Rust would have done, which silently loses
    updates. The tests cover only one "hash malease add a parity contract test. It shouldcover a NULL stored mtime, a size mismatch with an equal mtime, and a file with no stored hash. If possible it
    should compare against Rust's diff on the
  • Minor – indexing_coordinator.py:1648-1654. The epsilon is read through _cfg_or, imported locally from
    pipeline_bridge, which is a private helperd across modules. The coordinator alreadyparses mtime_epsilon_seconds separately at about line 1461 for the Python path, so there are now three readers of
    the same config value with the same 0.01 dcessor.
  • Minor – indexing_coordinator.py skip branch. The PR's own comment says HNSW recovery was "kept" for the skipped run.
    ensure_all_hnsw_indexes_async is a no-op och is fine, but the branch has no test. Acrashed-run HNSW recovery test on the skip path would protect the one behavior the PR deliberately preserves.
  • Minor – limited effect for some repos. Filzed, unknown) never get a DB row. Theprecheck will therefore report them as changed on every start, so the no-handoff win won't apply to repos containing
    such files. That is no worse than before, ts the optimization as general. Pleaseconfirm with the author, or add a test that includes a skipped file.
  • Minor – whole-tree hashing on every start.r stale mtime, so each start re-hashes thewhole tree on a to-thread worker (16 s in the author's measurement). This is acceptable and mentioned only
    indirectly. It would be worth a note in th
  • Minor – style. has_work and RustIncrementalWork have no docstring on the method, and find_rust_incremental_work's
    docstring has no summary line, which PEP 2tor block adds roughly 40 lines to an already very long process_directory. A helper such as _plan_rust_run(...) -> (files, do_cleanup, skip) would keep the
    function readable.
  • Note. The author's "Alternative considered" section is well reasoned. The remaining native compaction cost is
    explicitly out of scope.

Reusability:

  • Reuse the existing mtime_eps parsing instead of adding a third _cfg_or read.
  • Consider moving the "plan the Rust run" de skip) out of process_directory into the newmodule, so the Rust-parity logic and its decision rules live together.
  • Have the Python path's change detection (tund line 1560) share the stat/size/mtimecomparison with classify_files. They implement near-identical rules.
    Decision: REQUEST CHANGES (light). I'd approve once the parity test is added and the epsilon accessor is deduplicated. The rest are nits and can be follow-ups.

…lives with the precheck

- pipeline_bridge.rust_mtime_epsilon(config) is now the single reader of
  indexing.mtime_epsilon_seconds for the Rust pipeline and the precheck; the
  coordinator no longer imports the private _cfg_or.
- plan_rust_run / RustRunPlan move the narrow-or-skip decision out of
  process_directory into rust_incremental_precheck.py, unchanged in behaviour.
- PEP 257 docstrings for has_work and find_rust_incremental_work.
- Contract tests: the precheck agrees with the Rust differ (NULL stored mtime,
  same mtime with a new size, no stored hash, same bytes, untouched), and an
  unchanged run that skips Rust still recreates a missing HNSW index.

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

fstrasz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@HananKavitzAmat thanks. Both items you asked for before merge are in bb53735, a new commit on top of a1eff26; nothing was rebased.

Major: logic duplicated across two languages.

  • New parity contract test, test_precheck_agrees_with_the_rust_differ, parametrized over five cases:
    • a NULL stored mtime;
    • the same mtime with a different size;
    • a new mtime with no stored hash;
    • a new mtime with identical bytes;
    • an untouched file.
  • For each case it takes the precheck's verdict, then hands the real Rust pipeline the full file list with the precheck bypassed. It asserts that Rust re-indexes exactly the files the precheck called changed, and that the count matches the case.
  • I couldn't call differ.rs::compute_diff directly: it's pub(crate), and CI runs against the published chunkhound-native wheel, so a new binding wouldn't reach CI until a native release. Comparing behaviour through the real pipeline tests the same rules without that.
  • Proof that the test bites:
    • deleting the precheck's size check fails only [same-mtime-new-size] (precheck called [] changed; the Rust differ re-indexed 1 file(s));
    • treating a NULL mtime as unchanged fails only [null-stored-mtime];
    • on the unmodified code all five cases agree.

Minor: the epsilon accessor.

  • pipeline_bridge.rust_mtime_epsilon(config) is now public. It sets the value Rust receives (config_dict["mtime_epsilon_seconds"]) and is the value the precheck uses, so the two read through one function. The coordinator no longer imports _cfg_or.
  • I deliberately did not reuse the Python pipeline's reader (around indexing_coordinator.py:1480). Its float(... or 0.01) turns an explicit 0.0 into 0.01, while Rust honours 0.0, so sharing it would break parity at epsilon 0. Unifying the Python path's reading is a behaviour change of its own; I left it out of this PR.

The other minors:

  1. HNSW recovery on the skip path. New test, test_unchanged_reindex_restores_an_hnsw_index_a_crash_left_missing. It drops the HNSW index, runs an unchanged incremental run, and asserts Rust never started and the index is back. Replacing the skip path's ensure_all_hnsw_indexes_async() with pass makes it fail.
  2. Files Rust skips. Checked, and they do get a row. A repo with an unknown-type file matched by the include patterns and an empty .py: both got files rows with size and hash. The second and third runs logged Diff: 0/5 changed … Rust pipeline not started. So they don't force a handoff on every start. I couldn't exercise the size gate: a 51 KB .json was indexed by the native pipeline despite the 20 KB config-file threshold, which looks like a separate question about the native path. Parse-error and timed-out files weren't reproduced.
  3. Whole-tree hashing on every start. Now stated in the description: about 16 s on the 1174-file index, on a worker thread, with searches answering meanwhile. Before, the same hashing ran inside Rust's diff while readers were refused.
  4. Style.
    • has_work has a docstring.
    • find_rust_incremental_work starts with a summary line.
    • The plan block is out of process_directory: plan_rust_run() and a frozen RustRunPlan live in rust_incremental_precheck.py, as you suggested, so the parity rules and the decision built on them sit together. The coordinator's block is now a short call. Behaviour is unchanged: same gate, narrowing rule, cleanup-off rule and skip rule.

Reusability:

Checks (serial, Windows):

  • test_rust_startup_reader_access.py: 2 → 8 passed.
  • tests/contracts: 126 passed / 4 skipped → 132 / 4.
  • tests/test_smoke.py: only test_cli_help_commands failed, on its 5 s subprocess timeout. chunkhound map --help takes about 4.2 s here with and without the change.
  • ruff check: the same 69 findings on the changed files as at a1eff26.
  • mypy: the same 17 on the changed chunkhound files.

🤖 Generated with Claude Code

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

looks good. Thanks!

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 11, 2026
Merged via the queue into chunkhound:main with commit 5a01b27 Nov 11, 2026
25 checks passed
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.

2 participants