Skip to content

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

Merged
HananKavitzAmat merged 37 commits into
chunkhound:mainfrom
HananKavitzAmat:db_writter
Jul 19, 2026
Merged

HananKavitzAmat merged 37 commits into
chunkhound:mainfrom
HananKavitzAmat:db_writter

Conversation

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary

Replaces the Python serial executor's per-file write path with a native Rust RustDbWriter exposed via the existing chunkhound_native PyO3 crate. Python stays as orchestrator; the Rust writer is feature-flagged (CHUNKHOUND_USE_RUST, on by default when the native extension is present).

Runtime measurements — 4000 files, batch=20, real DB (best of 3 runs)

Cumulative improvements Python Rust Speedup
A — batch embedding inserts 431.1s 189.1s 2.3×
+H — HNSW bookend (drop once / rebuild once) 454.9s (440.4s writes + 14.5s HNSW) 215.3s (200.7s writes + 14.6s HNSW) 2.1×
+CF-1/2 + PF-1 — orphan fix + batch chunk inserts 428.0s (413.2s writes + 14.8s HNSW) 159.1s (144.2s writes + 14.8s HNSW) 2.7×
+G — PyO3 direct extraction (no json.dumps) ~504s 154.5s (138.6s writes + 15.8s HNSW) 3.3×
+PF-3 — batch pre-delete IN-list ~504s 115.8s (100.1s writes + 15.7s HNSW) ~4.4×

HNSW rebuild cost (~15s) is identical between paths — it's pure DuckDB VSS cost. All speedup is in batch writes. The bookend protocol (H) eliminates 199 per-batch drop/recreate cycles across 200 batches; HNSW drop itself takes ~0.002s.

Improvements shipped

ID Change Result
A Batch embedding inserts (100 rows/stmt) baseline
E Batch DELETE paths via IN (…) list −N round-trips per batch
F CHECKPOINT moved out of per-batch HNSW loop eliminates per-batch WAL flush
D HNSW DDL cache — skip catalog query after first batch O(1) catalog reads
H HNSW Bookend Protocol — drop once / rebuild once across all batches 2.1× alone
CF-1/2 Delete orphaned embeddings_N rows before chunk/file deletes correctness fix
PF-1 Batch chunk staging inserts (100 rows/stmt) 2.7× cumulative
G PyO3 direct extraction — eliminate json.dumps round-trip 3.3× cumulative
PF-3 Batch pre-delete IN-list — 2 grouped stmts instead of 2×N per-file DELETEs 4.4× cumulative

PF-4 (skip SELECT in upsert_file when existing_file_id known) was attempted and reverted — fallback SELECT still required for fresh-DB scenarios.

Files changed

  • src/db/duckdb_backend.rs — full DuckDB HNSW backend (NEW)
  • src/db/mod.rs — DbBackend trait + create_backend() factory (NEW)
  • src/db_writer.rs — RustDbWriter #[pyclass] (NEW)
  • src/types.rs, src/error.rs — shared types + PyErr conversion (NEW)
  • src/lib.rs — register RustDbWriter; keep scan_files
  • Cargo.toml — add duckdb, serde, serde_json, thiserror
  • chunkhound_native/__init__.py — export RustDbWriter
  • chunkhound/services/pipeline_bridge.py — feature-flag shim with graceful fallback (NEW)
  • scripts/bench_db_writer.py — benchmark harness, real-DB + synthetic modes (NEW)
  • tests/test_rust_db_writer.py — integration tests covering lifecycle, upsert, deletion, compaction counter, crash recovery, HNSW boundary, feature flag (NEW)

Known gaps (Phase 1)

  • CacheSnapshot / bloom filter not yet implemented — write_batch() still does 2 reads per batch (SELECT id FROM files WHERE path = ? per file; information_schema.tables per batch with pre-deletes). Zero-reads invariant lands in Phase 1.
  • run_compaction() is a stub (CHECKPOINT only) — full 3-phase EXPORT/IMPORT atomic swap deferred to Phase 1.

Test plan

  • maturin develop --release builds cleanly
  • uv run pytest tests/test_rust_db_writer.py -v — 21 tests pass
  • uv run pytest tests/test_smoke.py -v -n auto — smoke suite passes
  • uv run pytest tests/ -v — full suite passes
  • Benchmark against a real DB confirms ~4× speedup

Hanan Kavitz and others added 30 commits July 7, 2026 14:25
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]>
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]>
…ust 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]>
…nd 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]>
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]>
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]>
…peedup

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]>
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]>
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]>
… 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]>
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]>
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]>
…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]>
…ents 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]>
…wn (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]>
Keep crate-level attributes (#![forbid(unsafe_code)], #![allow(clippy::useless_conversion)])
from main alongside the mod declarations added in this branch; adopt
py.allow_threads() GIL-release wrapper from main.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- 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]>
- 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]>
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]>
- 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]>
…nor 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]>
…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]>
…a 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]>
…mics, 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]>
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]>
…y, 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]>
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]>
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]>
@HananKavitzAmat
HananKavitzAmat marked this pull request as ready for review July 13, 2026 15:47
@VakninAriel

Copy link
Copy Markdown
Collaborator

Summary: Solid, well-documented Phase 0 Rust DB writer that achieves a measured 4.4× write speedup; safe to merge given it is explicitly not wired into any production code path yet.


Strengths:

  1. Exceptional inline documentation — the DuckDB FK-in-transaction limitation, atomicity gaps, and HNSW invariants are all precisely explained at the call sites, which is exactly what a future maintainer needs when pre_delete_for_upsert looks bizarre at first glance.
  2. Clean abstraction boundary — the DbBackend trait (src/db/mod.rs:8-10) isolates the DuckDB-specific code from the PyO3 surface; swapping backends later requires zero changes to RustDbWriter.
  3. Conservative Phase 0 scope — pipeline_bridge.py is explicitly unconnected, feature-flagged, and well-tested in isolation. Zero production risk at merge time. The schema-parity CI test catches DDL drift before it becomes invisible.

Issues:

Major

  • HNSW crash-loss gap — duckdb_backend.rs write_batch Step 2 drops HNSW indexes before BEGIN, and Step 5 recreates them after COMMIT. If the process terminates between those two points the HNSW indexes are permanently gone. open() crash recovery only handles the compaction swap-intent file, not this case. The next session would open successfully, find no HNSW indexes, populate known_dims from the still-present embeddings_N tables, and never trigger Step 5+ (those dims aren't in new_dims). Result: permanent silent fallback to brute-force vector scan with no log message. Low probability in Phase 0, but must be fixed before Phase 1 wires this into production. Suggested fix: add an hnsw_rebuild_needed flag written to disk (analogous to swap_intent), or call ensure_all_hnsw_indexes() unconditionally in open() when VSS is available.

Minor

  • discover_embedding_tables called twice per batch when both delete_paths and upsert files are present (Steps 0a and 0b both invoke it). At 200 batches this is up to 400 extra information_schema.tables catalog scans. The Phase 1 caching TODO in pre_delete_for_upsert (~line 704) doesn't cover delete_paths. Track alongside the other Phase 1 caching work.

  • try_load_vss swallows all errors silently (duckdb_backend.rs:218-223). A VSS failure due to a corrupt extension binary or version mismatch is indistinguishable from "extension not installed." At minimum, log at debug level so it appears in --verbose output.

  • compaction_batch_threshold extracted as u64 then silently cast to u32 (db_writer.rs:1226-1228). Prefer extract_opt::<u32> directly, or add an explicit checked cast.

  • pipeline_bridge.py docstring typo: "db_writter branch" (line 36) — double-t.


Reusability:

  • discover_hnsw_indexes in Rust duplicates is_hnsw_index logic from schema_constants.py:120-128. Both must be updated if the HNSW naming convention changes; the schema-parity test covers columns but not index naming.
  • extract_opt/extract_req in db_writer.rs are good utilities — if Phase 1 adds more PyO3 dict extraction, pull them into a shared pyutil.rs.

Decision: APPROVE — Phase 0 scope is well-controlled, all CI green, the HNSW crash-loss gap is a Phase 1 concern (tracked in Known Gaps), and the performance measurements are reproducible via the benchmark harness.

- 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]>

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

PR #375 Review: RustDbWriter — PyO3 DuckDB write path

Executive Summary

This is a high-quality, extensively-reviewed PR adding a Rust-native DuckDB writer as a PyO3 extension. Phase 0 (not wired to production). The FK constraint workarounds for DuckDB's limitations are well-researched and correctly implemented. The HNSW index lifecycle management and crash recovery are thorough. Schema parity tests protect against DDL drift. Build infrastructure (CI split, precompiled DuckDB) is clean.

The PR has already gone through multiple rounds of internal review (commits like "resolve 13 PR review findings", "resolve 7 critical blockers"). What follows focuses on remaining issues.


🔴 Issues

1. pre_delete_for_upsert — atomicity gap comment claims self-healing, but gap window is larger than described

File: src/db/duckdb_backend.rs, pre_delete_for_upsert() doc comment

The comment says:

"Atomicity gap: if the process crashes after this commits but before the write transaction below commits, the old chunks are absent but new ones were not written. Recovery is self-healing: on the next index run the files are found in the DB and re-indexed from disk"

This is correct for the upsert path (files already in the DB). However, the code also runs pre_delete_for_upsert for all files in the batch, including brand-new files that happen to have existing_file_id=None. For truly brand-new files, the subquery returns no rows, so the DELETE is a no-op — correct but wasteful (unnecessary BEGIN/COMMIT + catalog query for discover_embedding_tables).

More importantly: if a crash happens after pre_delete_for_upsert's COMMIT but before the main write transaction, the delete_paths deletes (step 0a, also committed) have already removed files. The write transaction never runs, so deleted files are permanently gone from the DB (not "self-healing" — the indexer has no way to know they were meant to be deleted, because the delete was explicitly requested by the caller). This is an inherent limitation of the two-phase commit approach, but the "self-healing" claim should be qualified to note that the delete_paths gap is not self-healing.

Recommendation: Split the atomicity gap doc into two cases — upsert gap (self-healing) vs delete_paths gap (caller must re-request).

2. duckdb_backend.rs — discover_embedding_tables called redundantly across multiple call sites per batch

Locations:

  • delete_paths() — once
  • pre_delete_for_upsert() — once

Each write_batch call can trigger up to 2 separate information_schema.tables catalog queries (delete_paths + pre_delete_for_upsert). The TODO in pre_delete_for_upsert acknowledges this caching gap but notes it's non-trivial because new dims can appear mid-session. Since Phase 0 is explicitly not wired to production, this is acceptable. Consider adding a cross-reference between the delete_paths TODO and the pre_delete_for_upsert TODO so the same fix addresses both call sites.

3. pipeline_bridge.py — finalize() swallows all exceptions, even RuntimeError

def finalize(self) -> None:
    if self._writer is not None:
        try:
            self._writer.close()
        except Exception as exc:
            _log.warning("Error closing Rust DB writer: %s", exc)
        self._writer = None

While close() in the Rust backend does propagate errors now (per the review fix that replaced eprintln!), the Python shim silently swallows them. If close() fails because ensure_all_hnsw_indexes failed (HNSW rebuild error), the caller has no way to know the DB was left in a degraded state (HNSW indexes missing). Consider having finalize() re-raise on critical errors, or at minimum log at ERROR level instead of WARNING.


🟡 Suggestions

4. duckdb_backend.rs — delete_paths batch constant is duplicated

const DELETE_BATCH: usize = 500;  // in delete_paths()

The same 500-path batching is also used in pre_delete_for_upsert. Consider hoisting to a const at the impl level.

5. write_batch method is ~130 lines — consider extracting HNSW lifecycle into a helper

The method is well-commented with Step labels, but the HNSW discovery/drop/recreate logic is interleaved with the core write transaction. Extracting step_hnsw_drop(), step_hnsw_recreate(), and step_hnsw_new_dims() would make the flow read at a higher level while keeping the detailed logic in focused helpers.

6. db_writer.rs — extract_batch does not validate delete_paths type early

let delete_paths: Vec<String> = batch_dict
    .get_item("delete_paths")?
    .ok_or_else(|| PyKeyError::new_err("delete_paths"))?
    .extract()?;

If a Python caller passes delete_paths=42 (int instead of list), the error is PyKeyError("delete_paths") which is misleading — the key exists but has the wrong type. The actual error from .extract() would be a TypeError, but it's shadowed. This is minor since the caller is always internal Python code.

7. pipeline_bridge.py — __enter__ returns self but available() return could be False

with RustWriterBridge(config) as bridge:
    bridge.write_batch(...)  # RuntimeError if available() is False

If the bridge initialized but the Rust writer failed to open (self._writer = None), entering the context manager succeeds silently but the first write_batch raises RuntimeError. Consider adding available() check in __enter__ or documenting this pattern explicitly. For Phase 0 this is acceptable.


🟢 Positive Findings

  • FK constraint handling: Pre-txn deletes + separate commits + SELECT/UPDATE-or-INSERT pattern is the correct battle-tested approach for DuckDB's limitations. Well-documented.
  • HNSW lifecycle: DROP before BEGIN, RECREATE after COMMIT, new-dims mid-session detection — all correct.
  • Crash recovery: Three-phase swap_intent handling + HNSW recreation on open() is thorough.
  • Schema parity: Both column-name and column-type cross-checks against schema_constants.py. This is excellent defensive engineering.
  • GIL release: Consistently applied via py.allow_threads() for all DB operations.
  • No unsafe code: Complies with #![forbid(unsafe_code)].
  • Mutex poison handling: .unwrap_or_else(|e| e.into_inner()) everywhere at the PyO3 boundary.
  • CI optimization: Separate rust-checks job (parallel, no gate on pytest), DUCKDB_DOWNLOAD_LIB, targeted DuckDB cache key.
  • Multi-row batching: 100 rows/chunk insert, 100 rows/embedding insert, 500 paths/delete — consistent pattern.
  • Test coverage: Lifecycle, write round-trip, upsert idempotency, deletion, compaction, crash recovery (all 3 intent states), HNSW 49-vs-50 boundary, new-dims-mid-session, feature flag, schema parity (names + types), db-extension swap_intent regression.

📋 Summary

Severity Count Details
🔴 Issues 3 Atomicity gap doc clarity, redundant catalog queries, finalize() error swallowing
🟡 Suggestions 4 Duplicated batch constant, method length, error type, context manager contract
🟢 Positive N/A Solid engineering: FK handling, HNSW lifecycle, crash recovery, schema parity, GIL management, CI

Verdict: ✅ Approve with minor suggestions. The issues are documentation and optimization notes appropriate for a Phase 0 implementation. No correctness bugs found in the data path.

Hanan Kavitz added 2 commits July 14, 2026 16:51
… doc, finalize error level, const hoist, __enter__ guard
…el + 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.
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator Author

@ofriw can you take a swing at this?

Hanan Kavitz added 2 commits July 15, 2026 15:39
… 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.
@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Jul 19, 2026
Merged via the queue into chunkhound:main with commit f9ae0bf Jul 19, 2026
17 checks passed
ofriw pushed a commit that referenced this pull request Jul 22, 2026
* 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 #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 #375 review — atomicity gap doc, finalize error level, const hoist, __enter__ guard

* fix(native): address PR #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]>
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.

2 participants