Skip to content

fix(project-detection): make Windows discovery survive CWD==home and locked-down parents - #362

Merged
ofriw merged 2 commits into
chunkhound:mainfrom
e91d82c73:win_user
Jul 14, 2026
Merged

ofriw merged 2 commits into
chunkhound:mainfrom
e91d82c73:win_user

Conversation

@e91d82c73

Copy link
Copy Markdown
Collaborator

Note: This PR was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


Windows project-detection fixes

find_project_root() had two latent bugs that only bite on Windows. First, when CWD equals Path.home() — the default landing directory on Windows (C:\Users\<name>) — the walk loop's condition (current != home) short-circuited before inspecting the current directory even once. A .chunkhound.json sitting right in the home directory was invisible. Second, on Python <3.12, Path.exists() propagates PermissionError instead of returning False; a single locked-down parent on the walk path (common with corporate C:\Users ACLs) aborted the entire discovery with a stack trace.

The fix inverts the loop to inspect current before evaluating the break condition, and wraps each Path.exists() call in a small _exists_or_false() helper that swallows OSError. Two regression tests cover the CWD-equals-home case and confirm the home-directory ceiling still holds. The CLI positional-arg error message picks up an "or is not accessible" clause so users can distinguish typos from ACL problems.

No behavior change on Linux/macOS or on any path where discovery already worked — this only unblocks previously-broken Windows setups.

AGENT_REVIEW.md

…locked-down parents

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary: Correct, minimal fix for two latent Windows bugs in find_project_root() with solid regression tests.


Strengths:

  1. Loop inversion is the minimal correct fix — no restructuring beyond what's needed; the if current == home or current == current.parent: break guard preserves both the home-ceiling and the filesystem-root stop.
  2. _exists_or_false is rightly narrow: it only swallows OSError, not all exceptions, and the inline comment explains the precise Python-version constraint and platform context.
  3. Both regression tests use monkeypatch on Path.home correctly, covering the positive case (marker found in home) and the negative case (marker above home is not found).

Issues:

Minor

  • chunkhound/utils/project_detection.py — the _exists_or_false docstring is a 4-line comment block. AGENTS.md mandates "one short line max" for comments. The WHY is non-obvious and warrants a comment, but it should be condensed to a single line, e.g.:
    ```python

    Python <3.12: Path.exists() raises PermissionError on inaccessible paths.

    ```
    The current text is genuinely informative, so this is a style-only note.

  • tests/test_project_detection.py:245 — test_finds_marker_when_cwd_is_home uses a 7-line docstring (multi-paragraph). Tests are conventionally more verbose, but AGENTS.md still applies; the second paragraph (the regression note) is the important part and could be the sole docstring sentence.


Reusability: No duplication introduced. _exists_or_false could theoretically be shared with future callers in the same file, but it's private by convention (_ prefix) and file-local — appropriate scope.


Decision: APPROVE — both bugs are real, fixes are correct, tests cover the exact regression scenarios. Style violations are cosmetic and don't affect correctness or architecture.

@HananKavitzAmat
HananKavitzAmat self-requested a review July 8, 2026 07:25

@HananKavitzAmat HananKavitzAmat 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.

Looks good. see my commnet

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


Thanks — the CWD == Path.home() fix looks right, but I don’t think the PR is ready to merge yet because the main Windows ACL regression it claims to fix is still unprotected by tests. The new helper in chunkhound/utils/project_detection.py:7-15 changes discovery to swallow OSError from Path.exists(), and that behavior is now used on all marker probes in find_project_root() (:62, :66, :70). But the tests added in tests/test_project_detection.py:208-246 only cover the home-directory loop bug and the home ceiling; they never exercise the PermissionError/OSError branch that motivated the helper.

Please add a regression test that monkeypatches Path.exists() to raise PermissionError for a probed ancestor path and verifies find_project_root() keeps walking instead of crashing. That would align the test coverage with the PR description and protect the Windows-specific behavior this change is introducing.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

@e91d82c73
e91d82c73 requested a review from ofriw July 8, 2026 10:47

@ofriw ofriw 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.

LGTM

@ofriw
ofriw added this pull request to the merge queue Jul 14, 2026
Merged via the queue into chunkhound:main with commit df512fb Jul 14, 2026
12 checks passed
@e91d82c73
e91d82c73 deleted the win_user branch July 20, 2026 10:57
ofriw pushed a commit that referenced this pull request Jul 22, 2026
…locked-down parents (#362)

* fix(project-detection): make Windows discovery survive CWD==home and locked-down parents

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(project-detection): cover walk continuing past ACL-denied ancestor

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
HananKavitzAmat added a commit to HananKavitzAmat/chunkhound that referenced this pull request Jul 24, 2026
… meta, and canonical URL support (chunkhound#379)

* fix(dot): correct social preview accent dot position cx:597→595

* feat(site): add enterprise architecture proposal page with local-first vs server comparison

* feat(site): make social meta tags configurable and add canonical url support

* Add green palette CSS variables for shipped/success badge states

* Replace manifesto-style path comparison with engineering roadmap on architecture page

* Update stale test assertions to match rewritten enterprise roadmap content

* Remove dead CSS selectors from enterprise architecture page

* Consolidate duplicate HTML test helpers into shared html_helpers.py

* ci: split test suite into 2 parallel groups per OS via pytest-split

The tests job runs the full 4392-test suite as one serial pytest
invocation per OS, with Windows alone budgeting 60 minutes. The suite
intentionally avoids -n auto for the full run since daemon/MCP/realtime
tests aren't safe to parallelize within one process. Splitting into two
independent CI job shards per OS sidesteps that constraint entirely,
cutting wall-clock time without touching in-process parallelism.

pytest-split balances shards by recorded test duration once a
.test_durations baseline exists; until then it falls back to an even
per-test-count split (verified 2196/2196 via --collect-only).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* ci: keep tests job green when only flaky-annotated tests fail

continue-on-error on the pytest step stops a persistent flaky failure
from hard-failing the job; the flaky-annotation check remains the real
gate and still fails the job on any unannotated failure.

* fix(project-detection): make Windows discovery survive CWD==home and locked-down parents (chunkhound#362)

* fix(project-detection): make Windows discovery survive CWD==home and locked-down parents

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(project-detection): cover walk continuing past ACL-denied ancestor

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* feat(native): Phase 0 Rust DB writer (chunkhound#375)

* feat(native): Phase 0 Rust DB writer with Python benchmark

Adds RustDbWriter PyO3 class to chunkhound_native, exposing a
batch-oriented DuckDB write path from Rust. Python stays as
orchestrator; Rust handles all DB writes via the native extension.

Key design points:
- Full HNSW invariant compliance: DROP before BEGIN, RECREATE after COMMIT
- DDL (ensure_embedding_table) runs outside transactions (Invariant 13)
- GIL released via py.allow_threads() for the entire DB operation
- Feature flag CHUNKHOUND_USE_RUST=0 disables the Rust path
- Crash recovery for .swap_intent files on open()

New files:
- src/error.rs, src/types.rs — shared error/batch types
- src/db/mod.rs — DbBackend trait + DbConfig
- src/db/duckdb_backend.rs — DuckDB HNSW-correct implementation
- src/db_writer.rs — PyO3 RustDbWriter class
- chunkhound/services/pipeline_bridge.py — feature-flag shim
- scripts/bench_db_writer.py — Python vs Rust benchmark

Benchmark (200 files × 50 chunks × 1536 dims, release build):
  Python: 102s, 98 chunks/s
  Rust:    75s, 133 chunks/s  →  1.4× faster, 40% less memory

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(bench): bulk-load real DB data and sample files with chunks

load_from_db was doing per-file queries and sampling LIMIT 200 from
the files table directly, which returned mostly files with 0 chunks
(gradle/build files). Fixed to:
- One bulk query for files that have at least one chunk
- One bulk query for all chunks of sampled files
- One bulk query per embedding table for all chunk embeddings
- Also fixed CURRENT_TIMESTAMP → now() in ON CONFLICT SET clause

Real-data benchmark (quest/mono, 256-dim, 200 files × 14 chunks):
  Python: 21.7s, 130 chunks/s
  Rust:   10.7s, 264 chunks/s  →  2.0× faster, stable across 3 runs

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(bench): use production batch size heuristic for both Python and Rust paths

Mirrors indexing_coordinator._determine_db_batch_size: budgets 10% of
available RAM against estimated bytes/file (code + embedding float32 + 512B
overhead), clamped to [100, 5000] files/batch.  Both run_python_path and
run_rust_path now iterate in these batches, preventing the +1.7 GB Rust RSS
spike observed when all 10k files were serialized as a single JSON payload.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(bench): add per-batch progress printouts with wall time, CPU%, and RSS

Prints a line after each batch for both Python and Rust paths showing
files, chunks, embeddings written, elapsed seconds, CPU utilization
(computed from getrusage utime+stime delta), and current RSS.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* test(native): add Rust DB writer integration tests; fix 3 DuckDB FK bugs

Adds tests/test_rust_db_writer.py with 21 Python tests covering lifecycle,
write round-trip, BatchResult schema, upsert idempotency, deletion, compaction
counter, all three crash-recovery intent states, HNSW 49-vs-50 boundary, and
the CHUNKHOUND_USE_RUST feature flag.

Tests exposed three real bugs in duckdb_backend.rs, all matching known DuckDB
FK constraint limitations documented in the Python provider:

1. delete_paths ran inside BEGIN/COMMIT — DuckDB rejects parent-row deletes in
   an explicit transaction after child-row deletes on FK-linked tables.
   Fixed: delete_paths() extracted and called before BEGIN.

2. upsert_file used ON CONFLICT DO UPDATE — DuckDB internally deletes the
   conflicting row before reinserting, firing the FK check against chunks that
   still reference that file_id. Fixed: replaced with SELECT + UPDATE-or-INSERT.

3. Re-indexing a file without existing_file_id left old chunks in place,
   causing chunk duplication on every write. Fixed: always delete old chunks by
   path lookup when existing_file_id is not provided.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(bench): add DB row count correctness check after each run

Queries the actual DB after Python and Rust writes complete and
compares files/chunks/embeddings counts, printing PASS/FAIL per row.
Catches reporter bugs (e.g. Python rowcount=-1 on ON CONFLICT DO UPDATE)
that the returned write counts miss.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* perf(native): batch embedding inserts 100-rows-per-statement for 3× speedup

Replaces per-row stmt.execute() loop (one SQL call per embedding) with
multi-row VALUE batching (100 rows per INSERT), cutting round-trips ~100×.
Benchmarked at 3.0× speedup on 10k real files vs Python direct path.

Also fixes bench rowcount guard (n >= 0) to handle drivers returning -1.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* perf(native): batch path deletes and remove per-batch CHECKPOINT

E: Replace per-path DELETE loop (2N SQL calls) with IN-list batching
   (500 paths/batch), cutting delete round-trips ~500× on re-index runs.

F: Remove CHECKPOINT from recreate_hnsw_indexes — it was flushing the WAL
   after every batch write. CHECKPOINT now only runs in run_compaction and
   close, yielding a measured 9% throughput improvement.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* perf(native): cache HNSW index DDL to skip per-batch catalog query

After the first successful discovery, store the index info on the struct
and reuse it for all subsequent batches, avoiding a duckdb_indexes()
catalog query on every write_batch call.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(db-writer): implement HNSW bookend protocol (drop once / rebuild once)

Replace N×(DROP+CREATE) per-batch HNSW lifecycle with a single drop before
the batch loop and a single rebuild after — eliminating per-batch HNSW
overhead entirely when bulk-loading.

- Add `hnsw_bulk_mode` flag to `DuckDbHnswBackend`; when true, `write_batch`
  skips the HNSW lifecycle step entirely
- Add `drop_all_hnsw_indexes` / `ensure_all_hnsw_indexes` trait methods with
  default no-ops so existing callers compile unchanged
- Expose both as PyO3 `#[pymethods]`; `ensure` releases the GIL via
  `py.allow_threads()` since HNSW build can take 10–80s
- `close()` auto-calls `ensure` as a safety net if bulk mode was never
  explicitly closed
- Wire forwarding methods through `RustWriterBridge` in `pipeline_bridge.py`
- Add `_python_ensure_hnsw_indexes` to benchmark for a fair comparison where
  both paths produce HNSW-equipped databases
- Add per-step timing (drop / rebuild / batch writes) to benchmark output

Benchmark (4000 files, batch=20, best of 3, real DB):
  Python: 454.9s (440.4s writes + 14.5s HNSW rebuild)
  Rust:   215.3s (200.7s writes + 14.6s HNSW rebuild)
  Speedup: 2.1× overall; HNSW rebuild cost identical between paths

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(db-writer): delete orphaned embeddings before chunk/file deletes

embeddings_N tables have no FK cascade from chunks, so deleting chunks
without first deleting their embeddings caused ghost embedding rows to
accumulate on every re-index. Ghost rows participate in HNSW searches
and silently corrupt recall quality.

Two call sites fixed:
- delete_paths(): deletes embeddings via subquery before chunk delete,
  batched in the same 500-path chunks as the existing path delete
- write_batch_txn(): per-file pre-delete loop now clears embeddings
  before chunks for both the existing_file_id and path-lookup branches

discover_embedding_tables() is called once per function call (not per
file/batch) to avoid repeated catalog queries.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* perf(native): batch chunk staging inserts 100-rows-per-statement

The per-file chunk insert loop in insert_chunks_for_file was issuing one
SQL round-trip per chunk (K+3 round-trips per file), violating Invariant 5
and regressing against the Python path which uses executemany.

Replace the single-row stmt.execute() loop with the same multi-row VALUES
batching already used by insert_embeddings_txn: build a (?,?,?,?,?,?,?,?,?,?)
placeholder string for up to 100 rows at a time and bind all params via
params_from_iter. For a typical file with 17 chunks this cuts the temp-table
staging from 17 round-trips to 1.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* perf(native): extract batch via PyO3 directly — eliminate json.dumps round-trip

Replace json.dumps(batch) → String → serde_json::from_str with direct PyO3
extraction of the Python dict. At 20 files × 17 chunks × 1536-dim embeddings
per batch, this eliminates ~4MB of JSON generation+parsing per call, or ~800MB
across a 4000-file session (200 batches).

The embedding Vec<f32> is now extracted natively from Python list[float] via
PyO3 — no intermediate string representation. The GIL is still released before
the DuckDB writes via allow_threads; extract_batch() runs inside the GIL where
the Python objects are still valid.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* perf(native): batch pre-delete IN-list per group — eliminate N statements per batch (PF-3)

Replace per-file DELETE loop in write_batch_txn with two grouped IN-list statements:
files with existing_file_id use BigInt IN-list; path-only files use Text IN-list with
subquery. Reduces 2×N statements per batch to 4 statements total (2 groups × 2 tables).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* perf(native): skip SELECT in upsert_file when existing_file_id is known (PF-4)

When the caller already has a valid file_id (incremental re-indexing), jump straight
to UPDATE and return the id — saves one SELECT round-trip per file. Falls through
to SELECT → INSERT/UPDATE if the id is stale (e.g., benchmark replay into a fresh DB).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* Revert "perf(native): skip SELECT in upsert_file when existing_file_id is known (PF-4)"

This reverts commit 9bacbaa.

* fix(native): resolve 7 critical blockers from PR review

- Remove `unsafe impl Send for WriterInner` — violates #![forbid(unsafe_code)]
  and is unnecessary since DbBackend: Send makes Box<dyn DbBackend> Send
- Propagate HNSW recreate errors after COMMIT (was silently `let _ =`)
- Replace assert guards with RuntimeError in pipeline_bridge.py — asserts
  are stripped by python -O
- Wrap open/close/drop_all_hnsw_indexes in py.allow_threads() — DDL can
  block 100ms+ and must not hold the GIL
- Guard RustDbWriter re-export in chunkhound_native/__init__.py with
  try/except ImportError so scan_files still works on older wheels
- Add __del__ to RustWriterBridge to close the Rust DuckDB connection on
  GC — prevents single-writer lock leak when caller raises before finalize()
- Reset hnsw_bulk_mode=false at entry of ensure_all_hnsw_indexes so any
  error path leaves bulk mode off (previously only reset on success path)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): resolve 13 PR review findings in RustDbWriter

- Replace all .unwrap() on Mutex at PyO3 boundary with
  .unwrap_or_else(|e| e.into_inner()) to avoid interpreter crash
  on mutex poison (C1)
- Use .expect("reason") for logically-unreachable conn/embedding
  unwraps (C2, C3)
- Add schema_version table to setup_schema for Python compaction
  round-trip compatibility (M1)
- Rename HNSW indexes to idx_hnsw_{dims} matching Python canonical
  convention (M2)
- Fix swap_intent/old path construction for chunks.db extension —
  replace set_extension() with format!() (M3)
- Add table_schema = 'main' filter in discover_embedding_tables (M5)
- Wrap needs_compaction in py.allow_threads (m1)
- Restore deleted gitignore normalization comment in scan_files (m2)
- Clarify FK delete-outside-transaction comment (m3)
- Remove unsafe __del__; add __enter__/__exit__ context manager (m4)
- Convert _USE_RUST module constant to _get_use_rust() function (m5)
- Export RustDbWriter cleanly (no None sentinel) in chunkhound_native
- Add .db-extension swap_intent regression test; rewrite feature
  flag tests to use monkeypatch.setenv without importlib.reload

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): fix HNSW cache staleness + drop bundled DuckDB compile

Two correctness/CI fixes identified in PR review:

1. HNSW cache staleness: when a new embedding dimension was introduced
   mid-session the per-batch bookend only managed pre-existing indexes,
   leaving the new embeddings_N table without an HNSW index permanently.
   Fix tracks known_dims per session (primed on open()), invalidates
   hnsw_cache on new dims, and creates idx_hnsw_{dims} post-commit for
   each genuinely new table (Step 5+). Regression test added.

2. Bundled DuckDB compile: features = ["bundled"] compiled DuckDB C++ from
   source on every clean build (~15-30 min in CI). Dropped in favour of
   DUCKDB_DOWNLOAD_LIB=1, which pulls a precompiled libduckdb .so from the
   official GitHub release for the exact crate-matched DuckDB version
   (v1.5.4). URLs verified live (HTTP 200 + ZIP magic bytes confirmed).
   CI gains a separate target/duckdb-download/ cache keyed on Cargo.lock
   so zip survives unrelated dep bumps.

Also fixes 7 pre-existing clippy warnings (repeat_n, type_complexity,
redundant_closure) and applies rustfmt to the whole file.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): address remaining PR review minor issues

- Remove hasattr guards in RustWriterBridge (RustDbWriter always has
  drop_all_hnsw_indexes and ensure_all_hnsw_indexes)
- Add Phase 0/TODO(Phase 1) comment to run_compaction
- Quote table names consistently in ensure_embedding_table_dims and
  insert_embeddings_txn (matching the quoting style in delete/HNSW paths)
- Add TODO(Phase 1) comment on discover_embedding_tables inside write_batch_txn
- Document RustWriterBridge as Phase 0 with wiring into IndexingCoordinator
  as explicit Phase 1 work

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): address PR review findings — schema parity + clippy + minor fixes

- setup_schema: add idx_files_language, idx_chunks_type, idx_chunks_symbol to
  match Python canonical schema (schema_constants.py)
- ensure_embedding_table_dims: add idx_{dims}_chunk_id (with 1536 legacy compat)
  and idx_{dims}_provider_model so Rust-created DBs match Python-created ones;
  chunk_id index is required for performant delete subqueries
- write_batch_txn: add inline comment to #[allow(clippy::type_complexity)] per
  AGENTS.md rule
- close(): surface ensure_all_hnsw_indexes and CHECKPOINT errors via eprintln!
  instead of silently dropping them
- hnsw_cache: cache empty discovery result (Some(vec![])) to avoid re-querying
  the catalog every batch when no HNSW indexes exist yet
- pipeline_bridge: document intentional no-op semantics of HNSW bookend methods
- chunkhound_native/__init__.py: replace bare pass with RustDbWriter = None stub

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): fix schema DDL triplication + pipeline_bridge dead-code note

- Add TestSchemaParity test that cross-checks Rust-created column names
  against schema_constants.py at CI time — catches drift between
  duckdb_backend.rs::setup_schema and the Python canonical source
- Derive bench_db_writer.py _CREATE_SCHEMA from schema_constants.py
  (_FILES_TABLE_COLUMNS / _CHUNKS_TABLE_COLUMNS) instead of a third
  hardcoded DDL copy
- Fix schema_version description from 'initial schema (rust writer)' to
  'Initial schema' to match Python's insert
- Add SCHEMA PARITY comment block above setup_schema directing maintainers
  to schema_constants.py as canonical source
- Clarify RustWriterBridge docstring: intentionally unwired in Phase 0,
  Phase 1 targets SerialDatabaseExecutor

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): address PR review findings — MSRV, extension NULL, schema type parity, bench portability

- Cargo.toml: add rust-version = "1.82" (repeat_n MSRV) so older toolchains get a clear error
- duckdb_backend.rs: store NULL (not "") for extension on extensionless files, matching the nullable column
- test_rust_db_writer.py: add TestSchemaParity::test_column_types_match_python_schema — creates a
  reference DB from Python canonical DDL and compares data_type via information_schema, catching
  type/constraint drift that the column-names-only test cannot detect
- bench_db_writer.py: guard `import resource` with try/except for Windows portability; replace all
  resource.getrusage() call sites with a _getrusage() helper that returns zero values on Windows

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): address PR review findings — close() propagation, ergonomics, co-location

- close() now propagates ensure_all_hnsw_indexes / CHECKPOINT errors instead of
  swallowing them with eprintln; connection is always dropped regardless
- Document delete_paths atomicity gap and self-healing recovery in write_batch
- needs_compaction: &mut self → &self in trait and impl
- write_batch_txn renamed to write_batch_inner with clarifying comment
- BatchInner named struct replaces #[allow(clippy::type_complexity)] tuple return
- conn_or_err() helper eliminates 5 repeated ok_or_else("not open") chains
- RustDbWriter::new() uses direct PyO3 extract_req/extract_opt — no json round-trip
- bench_db_writer: _create_embedding_table delegates to schema_constants helpers
- pipeline_bridge.py moved to chunkhound/providers/database/ next to serial_executor
- AGENTS.md: document local (air-gapped) and CI maturin develop build procedures

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* docs(native): fix air-gapped build instructions in AGENTS.md

Use $(pwd) in the find command so OUT is always an absolute path —
the relative-path form produced a broken symlink target. Also add
RUSTFLAGS=-C link-arg=-lstdc++ (required for static DuckDB) and
explain why (__gxx_personality_v0 lives in libstdc++.so).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(native): address remaining PR review issues — atomicity, FK safety, docs

- delete_paths: split into two commits (emb+chunks atomic, then files
  auto-commit) so DuckDB's FK check sees the committed chunk deletes
  before the parent-row DELETE; wrapping all three in one txn caused a
  spurious FK constraint error because DuckDB reads committed state, not
  in-progress transaction state.

- pre_delete_for_upsert (new): extract upsert pre-deletes from
  write_batch_inner and run them before BEGIN for the same reason —
  UPDATE on files inside a txn where child chunks were deleted earlier
  in that same txn was rejected by DuckDB's FK engine. Fixes
  test_upsert_idempotent_no_duplication and test_upsert_replaces_chunks.

- tests: quote table name in _count() helper to prevent SQL injection.

- pipeline_bridge.py: document the intentional error-behaviour asymmetry
  between write_batch/needs_compaction/run_compaction (raise RuntimeError
  when unavailable) and drop/ensure_all_hnsw_indexes (silent no-op).

- duckdb_backend.rs: expand TODO(Phase 1) comment to explain why caching
  emb_tables is non-trivial (new dims can appear mid-session).

- Cargo.toml: add comment explaining that build mode is env-var-driven,
  not feature-flag-driven (duckdb default-features = []).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* style(native): apply cargo fmt to fix CI formatting check

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* ci: move Rust checks into a parallel job to unblock Python test budget

cargo fmt, clippy, and cargo test were bundled in the `tests` job,
consuming up to 15 min of its 30-min budget before pytest even started.
The new `rust-checks` job runs these in parallel on ubuntu+macos, with no
`needs` dependency, so it starts immediately and doesn't gate pytest.
`maturin develop` stays in `tests` since Python tests need the native .so.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* ci: remove invalid job-level hashFiles guard from rust-checks

hashFiles() is only available in step-level if expressions, not job-level.
Cargo.toml is permanent in this repo so the guard is unnecessary anyway.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* test: update pages-artifact needs contract to include rust-checks

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(rust-db-writer): address PR chunkhound#375 review findings

- Crash recovery: call ensure_all_hnsw_indexes() in open() so HNSW
  indexes lost between Step 2 (DROP) and Step 5 (RECREATE) are rebuilt
  on the next session instead of silently falling back to brute-force scan
- Log VSS load failures at debug level instead of swallowing them silently
- Extract compaction_batch_threshold directly as u32, removing the u64→u32
  silent truncation cast
- Add Phase 1 caching TODO to delete_paths to match pre_delete_for_upsert
- Fix typo: db_writter → db_writer in pipeline_bridge.py docstring

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(rust-db-writer): address PR chunkhound#375 review — atomicity gap doc, finalize error level, const hoist, __enter__ guard

* fix(native): address PR chunkhound#375 review — try_load_vss warn level + HNSW crash-recovery test

- Upgrade try_load_vss failure log from debug! to warn! so VSS
  degradation is visible at default RUST_LOG levels.
- Add test_hnsw_crash_recovery_restores_missing_indexes: simulates
  crash between write_batch Step 2 (DROP HNSW) and Step 5 (RECREATE)
  then verifies open() restores missing HNSW indexes.

* feat(native): 3-phase EXPORT/IMPORT atomic compaction with two-signal fragmentation detection

Replace CHECKPOINT-only compaction with a full EXPORT/IMPORT atomic swap:
- Phase 1: EXPORT DB to Parquet, CHECKPOINT, close connection
- Phase 2: fsynced intent markers, rename old DB, IMPORT into
  fresh DB, rebuild HNSW indexes
- Phase 3: atomic rename of compacted DB to active path, cleanup

Add two-signal fragmentation detection (compaction_stats):
- free_ratio from pragma_database_size
- row_waste_ratio from pragma_storage_info vs live COUNT(*)
- Falls back to write-count threshold when stats unavailable

Crash recovery via intent markers (pre-swap/phase1/phase2) that
restore the original DB if compaction is interrupted.

New DbConfig fields: compaction_threshold (default 0.30),
compaction_min_size_bytes (default 50MB), wired from Python
via compaction_min_size_mb.

* fix(native): remove trailing blank line (cargo fmt)

---------

Co-authored-by: Hanan Kavitz <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[email protected]>

* feat(config): make DB execute timeout configurable via JSON/env/CLI (chunkhound#377)

Lift serial executor timeout into DatabaseConfig so it can be set from
.chunkhound.json, CHUNKHOUND_DATABASE__EXECUTE_TIMEOUT_SECONDS, CLI
--db-execute-timeout, or the legacy CHUNKHOUND_DB_EXECUTE_TIMEOUT env
var, instead of only a runtime os.getenv in the executor.

* feat(mcp): add HTTP transport to the MCP server (chunkhound#378)

* feat(mcp): add HTTP transport to the MCP server

Adds a Streamable HTTP transport alongside stdio, built on the official
mcp SDK's StreamableHTTPSessionManager so remote and browser-based MCP
clients (including Claude Code's "type": "http" option) can connect
without spawning a local subprocess.

- Hoist shared tool-dispatch logic from stdio.py into MCPServerBase so
  both transports stay in sync.
- New HttpMCPServer (chunkhound/mcp_server/http_server.py): /health
  (unauthenticated) + /mcp endpoints, bearer-token auth via raw ASGI
  middleware (SSE-safe), optional CORS, uvicorn run loop.
- CLI: --transport/--host/--port/--auth-token/--cors flags; HTTP mode
  bypasses the daemon/ClientProxy since it already multiplexes clients.
- Refuse to start with a non-loopback --host and no --auth-token.
- Bump mcp>=1.16.0; add starlette/uvicorn as direct deps.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* docs: document MCP HTTP transport flags

AGENTS.md's mcp_http command referenced a nonexistent `mcp http`
subcommand; the real invocation uses --transport http. Also add the
missing --transport/--host/--port/--auth-token/--cors/--read-only
flags to the cli-reference mcp section.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(mcp): correct HTTP transport setup output, middleware order, and test cleanup

- Skip printing irrelevant stdio launch configs when running in HTTP
  transport mode, and copy the actually-relevant client config to clipboard
- Register CORSMiddleware outermost so it can answer preflight OPTIONS
  requests before the bearer-auth middleware would otherwise 401 them
- Terminate the full descendant process tree in test_smoke's MCP HTTP
  tests so `uv run`'s child process doesn't leak a locked DB/port on Windows

* fix(mcp): require --auth-token when --cors is enabled on HTTP transport

Enabling --cors without --auth-token let any website open in the same
browser read from the MCP HTTP transport via CORS, even on the default
loopback host — this is now a validation error at startup, mirroring the
existing non-loopback-host check. Adds fast in-process validator tests
plus end-to-end smoke coverage for the rejection and the allowed
(cors + token) path, and documents the requirement in cli-reference.md.

* fix(mcp): address PR chunkhound#378 review findings on HTTP transport

- Recognize any loopback IP literal (not just exact string match) when
  validating --host for the HTTP transport, via a new _is_loopback_host
  helper built on ipaddress.ip_address(...).is_loopback.
- Fix the printed client config URL for bind-all hosts (0.0.0.0/::) and
  bracket IPv6 literals so the copy-pasted config is actually reachable;
  note when the displayed host was substituted.
- Warn instead of silently ignoring --stdio when combined with
  --transport http.
- Avoid re-validating config a second time when the HTTP transport is
  launched from mcp_command, which already validated it once.
- Construct the shared MCP SDK Server object lazily in
  _register_common_tool_handlers instead of unconditionally in
  MCPServerBase.__init__, so subclasses whose _register_tools() is a
  no-op (the daemon) never allocate one.
- Harden HTTP smoke tests: fail fast in _wait_for_http_ready if the
  spawned server process exits early instead of spinning for the full
  timeout; use the full process-tree terminate (not a bare kill) on the
  negative-path startup-rejection tests so a regressed validation gate
  can't leak an orphaned server process; add coverage for CORS preflight
  and an authenticated CORS request against /mcp itself, not just the
  auth-exempt /health endpoint.
- Extract shared JSON-RPC envelope building/unwrapping and exception
  types into tests/utils/jsonrpc_envelope.py, reused by both
  SubprocessJsonRpcClient and HttpMcpClient instead of being duplicated.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(mcp): document DELETE session teardown, address remaining PR chunkhound#378 review nits

Keeps StreamableHTTPSessionManager stateful as requested. DELETE /mcp
teardown already worked (the raw-ASGI Route has no method restriction and
the MCP SDK handles DELETE itself); documented that behavior instead of
adding redundant routing, and added a smoke test proving a terminated
session is actually rejected afterward.

Also: verified mcp>=1.16.0 already hard-requires starlette/uvicorn
unconditionally, so making them optional extras would save no install
weight — left them as direct deps with a comment explaining why. Plus
smaller review nits: moved _is_loopback_host to mcp_config.py, added
port bounds, fixed a stale docstring and a test-utils import path, and
documented the /health and CORS allow_credentials tradeoffs.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(mcp): add WWW-Authenticate header on HTTP transport 401 responses

RFC 7235 requires it; without it some compliant clients won't
automatically retry with credentials. Flagged in PR chunkhound#378 review.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(mcp): address latest PR chunkhound#378 review round on HTTP transport tests

Fixes the test-resilience findings from Ariel Vaknin's follow-up review:
HttpMcpClient now honors the Content-Type instead of assuming SSE,
_get_free_port() sets SO_REUSEADDR to narrow its TOCTOU window, the
session-teardown test asserts a 404 specifically, MCPConfig.__repr__
surfaces HTTP fields, and the misleadingly-named SubprocessJsonRpcError
is renamed to McpClientError (old name kept as an alias).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(mcp): address final PR chunkhound#378 review nits on HTTP transport

Rename the misleading SubprocessJsonRpcError alias to McpClientError in
the HTTP test client, and clarify is_loopback_host's docstring on
non-IP hostnames always requiring auth.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>

* fix: update MCP transport label to show stdio and HTTP

* fix: update HTTP MCP notes to reflect native transport

* fix: add phase numbering to roadmap cards (LSM-Vec)

* fix: improve contrast of loser cells in comparison table

* refactor: extract shared meta_tag_content helper to html_helpers

* fix: correct false 4.4x speedup and 256-dim claims

* fix: add phase numbering to roadmap cards

* fix: clarify overstated gap claims (DB deps, gap 5)

* fix: prevent mobile overflow on gap grid below 480px

* chore: add site/test-results to gitignore

* chore: prettier reformat enterprise architecture page

* docs: decompose Phase 2 into index/executor cards, sharpen post-Phase-2 server vision

* Replace vague thesis with concrete mechanism

* Clarify stateless HTTP MCP deployment requires session work

* Add concrete distribution mechanism with generic HTTP endpoints

* Fix stale aria-labelledby reference

* Correct stale scale note numbers

---------

Co-authored-by: Hanan Kavitz <[email protected]>
Co-authored-by: Claude Sonnet 5 <[email protected]>
Co-authored-by: e91d82c73 <[email protected]>
Co-authored-by: HananKavitzAmat <[email protected]>
Co-authored-by: Hanan Kavitz <[email protected]>
Co-authored-by: Robert Gero <[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