Repository navigation
feat(duckdb): implement database compaction with atomic swap, HNSW bookend protocol, and MCP-safe logging - #339
Conversation
…un_batch_compaction_boundary
…n stderr in MCP mode
grzegorznowak
left a comment
There was a problem hiding this comment.
Summary: No ticket key was provided; PR #339 aligns with the stated compaction/MCP/realtime value, but several in-scope correctness gaps can break those guarantees.
Business / Product Assessment
Verdict: REQUEST CHANGES
Strengths
- The PR adds the requested fixed indexing compaction boundaries and a documented threshold knob for automatic maintenance. Sources:
chunkhound/services/directory_indexing_service.py:102,chunkhound/services/directory_indexing_service.py:114,chunkhound/core/config/database_config.py:70 - MCP stdout protection is addressed with an explicit MCP-mode environment marker and a shared guarded logging helper. Sources:
chunkhound/mcp_server/stdio.py:420,chunkhound/utils/logging_guard.py:19
In Scope Issues
-
Read-only startup can still mutate compaction artifacts before opening DuckDB read-only. Sources:
chunkhound/core/config/database_config.py:54,chunkhound/providers/database/duckdb/connection_manager.py:98,chunkhound/providers/database/duckdb/connection_manager.py:198High severity · Medium likelihood
Why: MCP read-only access is expected to reject writes, but startup recovery can unlink/replace the DB and delete compaction files before the read-only connection is attempted.
Assumptions / Preconditions: A read-only open sees
.compact_backup,.compact_new, or backup WAL artifacts from a prior or concurrent compaction.Downgrade Factors: Impact is lower if read-only mode is never used against shared DB files that may contain recovery artifacts.
Code Trail:
DatabaseConfig.read_onlypromises writes are rejected.ConnectionManager.connect()skips parent creation and WAL cleanup in read-only mode, but still calls_recover_interrupted_compaction()unconditionally. That recovery path performsunlink,os.replace, and stale artifact deletion.Reproduction: Create a DB path with live missing/empty plus
chunks.duckdb.compact_backup, then open through DuckDB MCP read-only. Startup attempts filesystem recovery instead of failing with a recovery hint. -
DB-backed MCP calls during active compaction can trigger interrupted-compaction recovery and undo the in-progress swap. Sources:
chunkhound/mcp_server/base.py:1217,chunkhound/providers/database/duckdb_provider.py:352,chunkhound/providers/database/duckdb_provider.py:1167,chunkhound/providers/database/duckdb/connection_manager.py:198High severity · Medium likelihood
Why: The PR promises MCP tools skip reconnect while compaction owns the DB, but the reconnect path can run file recovery before the compaction guard fires.
Assumptions / Preconditions: A DB-backed MCP request arrives after compaction has closed connections and moved the live DB to
.compact_backup.Downgrade Factors: Lower likelihood if MCP never receives DB-backed calls during long compactions.
Code Trail:
_connect_provider()catchesDatabaseCompactionInProgressErroraroundprovider.connect().DuckDBProvider.connect()calls_connection_manager.connect()beforesuper().connect(), and the executor compaction guard is only reached through the serial executor path. During compaction,_compact_prepare()has already moved the DB to the backup path, which_recover_interrupted_compaction()interprets as a crashed prior compaction.Reproduction: Start compaction, let
_compact_prepare()rename live DB to.compact_backup, then call a DB-backed MCP tool whileprovider.is_connectedis false. The reconnect path can restore the backup over the active compaction state. -
Realtime
embedmutations are not retried when compaction owns the database. Sources:chunkhound/providers/database/serial_executor.py:140,chunkhound/services/realtime/pipeline.py:1455,chunkhound/services/realtime/pipeline.py:1462,chunkhound/services/realtime/pipeline.py:1476Medium severity · Medium likelihood
Why: Realtime work that hits compaction should be delayed and retried; embed-only work is currently logged as a warning and dropped from the retry path.
Assumptions / Preconditions: An
embedmutation runs while the provider fast-fails due to active compaction.Downgrade Factors: Impact is lower if embed mutations are always followed by later full scans that regenerate the same missing embeddings.
Code Trail: The serial executor raises
DatabaseCompactionInProgressErrorbefore submitting DB work. The realtime process loop special-casesmutation.operation == "embed"and catches all exceptions locally, records warning/error state, calls_record_processing_finished, andcontinues before the outer compaction retry handler can run.Reproduction: Queue an
embedmutation while compaction is active. The exception is swallowed in the embed branch and no_schedule_compaction_retry()mutation is registered.
Out of Scope Issues
- None.
Technical Assessment
Verdict: REQUEST CHANGES
Input Boundary Shape Risk Assessment
Status: Triggered
Boundary: persisted DuckDB catalog table/index names -> stricter ChunkHound embedding-table and HNSW lifecycle assumptions.
Evidence / mitigation: Compaction reads raw information_schema.tables names with LIKE 'embeddings_%%', then interpolates those names into SQL and classifies them as known tables; HNSW helpers also classify existing indexes by name pattern in some paths while other catalog helpers detect USING HNSW. Sources: chunkhound/providers/database/duckdb_provider.py:1230, chunkhound/providers/database/duckdb_provider.py:1239, chunkhound/providers/database/duckdb_provider.py:1251, chunkhound/providers/database/duckdb_provider.py:2064, chunkhound/providers/database/duckdb_provider.py:2271
Strengths
- The compaction implementation uses a checkpoint, backup swap, and explicit reconnect/restore testing around failure cases. Sources:
chunkhound/providers/database/duckdb_provider.py:1154,chunkhound/providers/database/duckdb_provider.py:1167,tests/test_duckdb_compaction.py:757 - Test coverage includes important user-visible invariants such as sequence reseeding, HNSW survival, no-op compaction skipping, and realtime compaction retry basics. Sources:
tests/test_duckdb_compaction.py:394,tests/test_duckdb_compaction.py:437,tests/test_duckdb_compaction.py:1082,tests/unit/test_realtime_compaction_retry.py:34
In Scope Issues
-
Persisted embedding-table discovery is over-broad and uses unsafe identifier interpolation. Sources:
chunkhound/providers/database/duckdb_provider.py:1230,chunkhound/providers/database/duckdb_provider.py:1239,chunkhound/providers/database/duckdb/schema_constants.py:109High severity · Medium likelihood
Why: A database with an unexpected but legal table name can either abort compaction or be preserved as “known” when the design says non-ChunkHound tables are dropped.
Assumptions / Preconditions: The persisted DB contains a table such as quoted
embeddings-bador unquotedembeddingsXfoo.Downgrade Factors: Lower impact if ChunkHound is guaranteed to own the entire DB file and no external tables ever exist.
Code Trail: SQL
LIKE 'embeddings_%%'treats_as a wildcard, so it matches more than canonicalembeddings_<dims>tables. When_embedding_dims_from_table_name()returnsNone, compaction emitsCREATE TABLE {tname}andsrc.{tname}without quoting. The same discovered names are added toknown, bypassing the unknown-table warning/drop path.Reproduction: Add a quoted DuckDB table named
embeddings-badbefore compaction. The discovery query includes it, thenCREATE TABLE embeddings-bad ...is parsed as an invalid unquoted identifier expression. -
HNSW bookend helpers miss valid nonstandard HNSW indexes. Sources:
chunkhound/providers/database/duckdb_provider.py:2064,chunkhound/providers/database/duckdb_provider.py:2243,chunkhound/providers/database/duckdb_provider.py:2271,tests/unit/test_reindexing_workflow.py:497Medium severity · Medium likelihood
Why: The PR’s “drop all before bulk writes, ensure after” protocol does not actually cover every HNSW index shape the code and tests already recognize.
Assumptions / Preconditions: A table has a valid
USING HNSWindex whose name does not start withhnsw_oridx_hnsw_.Downgrade Factors: Impact is lower if production never creates custom HNSW names.
Code Trail:
_is_hnsw_index_definition()correctly treatsUSING HNSWas authoritative. However,_executor_hnsw_index_exists()and_executor_drop_all_hnsw_indexes()use only name patterns, while a test createsalt_live_idx ON embeddings_3 USING HNSW. That index survives the drop-all phase and can make later ensure/drop decisions inconsistent.Reproduction: Create
alt_live_idx ON embeddings_3 USING HNSW, then calldrop_all_hnsw_indexes(). The helper’s name filter excludes it, so bulk indexing still carries that HNSW maintenance cost. -
The public provider protocol advertises LanceDB HNSW no-ops that the shared base does not implement. Sources:
chunkhound/interfaces/database_provider.py:83,chunkhound/interfaces/database_provider.py:90,chunkhound/providers/database/serial_database_provider.py:646,chunkhound/providers/database/lancedb_provider.py:159Low severity · High likelihood
Why: Callers typed against
DatabaseProvidercan reasonably call these methods, but LanceDB instances do not inherit no-op implementations.Assumptions / Preconditions: External or future internal code calls
drop_all_hnsw_indexes()orensure_all_hnsw_indexes()on aDatabaseProviderthat is actually LanceDB.Downgrade Factors: The current canonical directory service uses
hasattr, so this does not break that path today.Code Trail: The protocol says both HNSW methods are no-ops for providers without HNSW support.
LanceDBProviderinheritsSerialDatabaseProvider, whose nearby default optimization method is a no-op, but no equivalent HNSW defaults exist.Reproduction: Instantiate/use a LanceDB provider through the public protocol and call
ensure_all_hnsw_indexes(). The method is absent at runtime.
Out of Scope Issues
- None.
Reusability
run_batch_compaction_boundary()centralizes the compaction status contract for canonical and legacy indexing paths. Sources:chunkhound/services/indexing_coordinator.py:168,chunkhound/services/indexing_coordinator.py:174compact_database_with_metrics()provides a reusable metrics wrapper instead of making callers compute file-size deltas. Sources:chunkhound/services/indexing_coordinator.py:1720,chunkhound/services/indexing_coordinator.py:1747
review generated with CURe v. 0.8.0 · multi-stage - stages: 5 · sha eac78e0 · model gpt-5.5/high · tok 19m/135k/19m · session chunkhound-chunkhound-pr339-20260623-102044-5bc4 · 25m27s
VakninAriel
left a comment
There was a problem hiding this comment.
Review: feat(duckdb) — database compaction with atomic swap, HNSW bookend, MCP-safe logging
Summary: Solid compaction infrastructure with good crash recovery, but two correctness bugs in the MCP compaction guard, a 10× too-aggressive auto-compact sampling rate, and inline MCP env guards left scattered while the new log_if_not_mcp utility that should replace them all was introduced.
Difference from stack/1-compaction
The two branches started from the same compaction idea but diverged:
| Feature | PR #339 | stack/1-compaction |
|---|---|---|
| Compaction guard type | DatabaseCompactionInProgressError (executor-level, before submit) |
CompactionError (connection-level, inside executor thread) |
| MCP log guard | log_if_not_mcp() utility (logging_guard.py) |
8 inline os.environ.get("CHUNKHOUND_MCP_MODE") checks in duckdb_provider.py |
| HNSW bookend | DirectoryIndexingService drops HNSW before bulk, rebuilds after |
_force_defer_hnsw flag + coordinator-driven rebuild |
| Realtime retry | Exponential backoff + ±25% jitter + budget exhaustion | _compaction_deferred_files accumulation only, no retry budget |
realtime_indexing_service.py |
sys.modules shim removed, 18 callers wired directly |
Compatibility shim retained |
| Embedding migration | Not present | Full matryoshka migration, truncation, drop_embedding_table |
| Read-only mode | Not present | --read-only MCP flag (from #329) |
| Chunk batch cap | Not present | _CHUNK_INSERT_BATCH_SIZE=5000 |
| Compaction test coverage | 2350-line test file + 148-line realtime retry tests | Minimal |
Strengths
-
Three-phase crash recovery with intent files (
PHASE_PRE_SWAP→PHASE_1→PHASE_2) is well-designed._recover_from_intent()handles every failure permutation — missing backup, failed integrity probe, partial swap — with appropriate fallbacks. -
log_if_not_mcp()centralization (logging_guard.py) is architecturally correct.logger.opt(depth=1)preserves caller attribution in log output — something the scattered inline guards completely miss. -
Pre-submission compaction guard in
SerialDatabaseExecutor._raise_if_compacting_before_submit()is superior to a connection-time check: fails before the operation enters the executor queue.
Issues
Critical
1. tool_requires_services() will KeyError on any unregistered tool — mcp_server/tools.py
tool = TOOL_REGISTRY[tool_name] # KeyError if tool_name not in registryTOOL_REGISTRY is populated lazily via @register_tool decorators. Any tool called before its module is imported, or a name typo from the MCP client, crashes the entire MCP handler. Fix: TOOL_REGISTRY.get(tool_name) with a fallback of True (conservative: assume DB needed).
2. _connect_provider() swallows DatabaseCompactionInProgressError, then returns a disconnected provider — mcp_server/base.py
try:
await loop.run_in_executor(None, self.services.provider.connect)
except DatabaseCompactionInProgressError:
log_if_not_mcp("info", "DB compaction in progress ...")
# ← returns None silentlyensure_tool_services() then returns self.services with provider.is_connected = False. The tool implementation hits a disconnected provider and raises a confusing second error. Fix: re-raise from _connect_provider(), catch in ensure_tool_services(), and return a structured MCP error response to the client.
Major
3. COMPACT_SAMPLE_INTERVAL = 10 is 10× too aggressive — serial_executor.py
COMPACT_SAMPLE_INTERVAL = 10 # 1-in-10 write ops trigger a compaction checkAt N=10, a typical 5000-write indexing run triggers 500 measure_fragmentation() calls, each running PRAGMA database_size + pragma_storage_info() queries. The parallel branch uses N=100 for this reason and benchmarked it. Default should be 100.
4. sys.modules shim removed without deprecation path — If any external plugin imports chunkhound.services.realtime_indexing_service, this is a silent runtime break on upgrade. The shim should survive at least one release or be called out explicitly as a breaking change in the PR notes.
Minor
5. The 8 inline os.environ.get("CHUNKHOUND_MCP_MODE") guards remaining in duckdb_provider.py (lines 554, 557, 568, 577, 927, 4356, 4372, 4377) defeat the purpose of introducing log_if_not_mcp. They should all be replaced in this PR — leaving half the old pattern behind creates maintenance confusion and misses the logger.opt(depth=1) caller-attribution benefit.
6. tool_requires_services() uses function-signature introspection to decide if a tool needs DB access. A requires_db: bool field on the Tool dataclass would be simpler and not sensitive to parameter renaming.
7. Verify consistency between the HNSW bookend in DirectoryIndexingService (always drops/rebuilds) and _compact_finalize in duckdb_provider.py ("only recreated if they existed before") for the case where no HNSW indexes existed pre-compaction.
Decision: REQUEST CHANGES
Fix items 1 and 2 (correctness), tune COMPACT_SAMPLE_INTERVAL to 100, replace remaining inline MCP env guards with log_if_not_mcp, and either restore the shim or explicitly flag the shim removal as a breaking change.
SpiGAndromeda
left a comment
There was a problem hiding this comment.
I based the review primarily on the experiences with the problems in the compactor during development that I solved or mitigated.
| # Only recreate HNSW if the original DB had it before compaction. | ||
| # During batch CLI indexing, HNSW is dropped at the start (bookends) | ||
| # and intermediate compactions must not recreate it mid-pipeline. | ||
| if had_hnsw: |
There was a problem hiding this comment.
had_hnsw gating aside, this rebuilds the HNSW eagerly in the live process with no size gate, no memory_limit, and no skip/defer path.
The compactor's benchmarks put full-rebuild peak RAM at 3–4× the source HNSW's pragma_hnsw_index_info().approx_memory_usage (11.8 GiB for a 2.12 GiB HNSW on a 1.25 TB index), and it added --skip-hnsw plus a separate-machine restore because the HNSW build dominates peak memory (benchmarks.md; architecture.md §RAM cost asymmetry).
This is not a new ceiling: ChunkHound already rebuilds the entire HNSW on every write batch over the 50-row threshold (commons architecture.md §ChunkHound compatibility: "a rebuild reproduces that property; it does not introduce a new one"), so a machine that indexes at this scale already survives the peak.
The residual concern is timing: compaction can hit that peak at an arbitrary point inside a long-lived MCP server rather than during an explicit index run, and can hit it cold when triggered by MVCC delete/update bloat with no recent HNSW rebuild. Consider gating auto-compaction by index/HNSW size or available RAM, or offering a deferred-rebuild path mirroring the compactor's --skip-hnsw/restore split.
There was a problem hiding this comment.
_extract_hnsw_metric regexes metric='…' out of the CREATE INDEX SQL from duckdb_indexes(), but DuckDB strips the entire WITH (...) clause from that catalog DDL, so the regex never matches and always falls back to cosine.
The compactor hit this exact case and recovers the metric from pragma_hnsw_index_info() instead (commons architecture.md §HNSW metric recovery, which verifies the WITH-stripping on DuckDB 1.5.2). This doesn't bite the compaction path today because _executor_ensure_all_hnsw_indexes hardcodes WITH (metric = 'cosine') (:2306) and every create_vector_index caller uses cosine. But _SUPPORTED_HNSW_METRICS advertises ip and l2sq, and _executor_recreate_vector_index_from_info routes the extracted metric back into a rebuild, so a non-cosine index would be silently rebuilt as cosine — the index goes dead and cosine-distance queries fall back to a brute-force scan with no error, the failure mode the compactor documents.
Either recover the metric via pragma_hnsw_index_info(), or drop the ip/l2sq support so the cosine-only invariant is explicit. Separately, compaction recreates the index under the canonical name from _embedding_hnsw_index_name(dims), renaming any custom-named index.
| if advance_by <= 0: | ||
| return | ||
|
|
||
| conn.execute(f"SELECT nextval('{sequence_name}') FROM range({advance_by})") |
There was a problem hiding this comment.
Both reseed paths advance the sequence with SELECT nextval(seq) FROM range(N), which materializes N rows and issues N nextval calls — O(max_id) on every compaction.
On an aged index whose id counter has climbed into the millions (ids are monotonic and never reused), that is a multi-second stall on a path that runs automatically and often. The compactor does this in O(1) by replaying the sequence DDL, whose START value already preserves the cursor (architecture.md §Compaction pipeline, step 7: "their START value preserves the cursor; no setval needed").
The inline comment attributes the loop to "DuckDB 1.4 can't ALTER/setval/DROP", but the codebase's own _executor_recreate_sequence runs DROP SEQUENCE …; CREATE SEQUENCE … START n; the real blocker is the column DEFAULT nextval(...) dependency that makes DROP SEQUENCE fail, not a missing primitive. Low priority because the HNSW rebuild in the same _compact_finalize dominates wall time, but the comment's stated reason is wrong.
|
|
||
| Returns (embedding_table_names, had_hnsw). | ||
| """ | ||
| tgt_conn = duckdb.connect(str(compacted_path)) |
There was a problem hiding this comment.
The rebuild connection never sets preserve_insertion_order = false, though three other bulk-write paths do (:831, :2624, duckdb/embedding_repository.py:494).
The compactor sets it before its streaming INSERT … SELECT to keep the copy memory-flat on large tables (architecture.md §Compaction pipeline, step 8). For the embeddings copy — potentially millions of 1024-dim vectors — preserving insertion order forces DuckDB to buffer and inflates peak memory during the copy phase for no benefit, since the rows land in a fresh file regardless.
Set it on tgt_conn before the inserts.
| """ | ||
| tgt_conn = duckdb.connect(str(compacted_path)) | ||
| try: | ||
| tgt_conn.execute("INSTALL vss") |
There was a problem hiding this comment.
INSTALL vss requires the extension to be cached locally or fetched over the network. The compactor avoids this by bundling the vss binary from the duckdb-extension-vss wheel and LOAD-ing it from disk, keeping compaction offline-safe (commons architecture.md §Bundled vss extension). Low risk here because ChunkHound already depends on vss for HNSW, so it is normally installed, but an auto-compaction firing on a disconnected machine with a cold extension cache would fail. _compact_copy_data builds no HNSW (create_hnsw=False); the actual build happens later in _compact_finalize.
| live_missing_or_empty = True | ||
|
|
||
| if backup_path.exists() and live_missing_or_empty: | ||
| log_if_not_mcp( |
There was a problem hiding this comment.
Recovering a live DB from an interrupted compaction backup logs via log_if_not_mcp, so under CHUNKHOUND_MCP_MODE=1 the event is silent.
Compare _compact_copy_data, which routes the destructive "dropped non-ChunkHound tables" warning to stderr even in MCP mode (duckdb_provider.py:1268-1271) because loguru sinks are disabled there.
A crash-recovery swap is at least as significant — the previous process died mid-compaction and the DB was restored from .compact_backup — and currently leaves no trace in the MCP case. Route it to stderr for parity.
| f"INSERT INTO {tname} ({elist}) SELECT {elist} FROM src.{tname}" | ||
| ) | ||
|
|
||
| known = {"schema_version", "files", "chunks"} |
There was a problem hiding this comment.
Compaction preserves only schema_version, files, chunks, and embeddings_* and drops everything else by design.
This inverts the compactor's front-gate stance, which refuses any source shape it cannot faithfully reproduce rather than dropping objects (README and out-of-scope.md: "fails hard rather than silently dropping anything it cannot reproduce"). The drop is loud today via the stderr warning, but the allowlist is hardcoded: if a future ChunkHound version adds a canonical table and this set is not updated in lockstep, that table is silently destroyed on the next auto-compaction — and auto-compaction fires probabilistically during normal use, so the loss would surface far from the schema change that caused it.
Add a guard that fails compaction on an unrecognized non-empty table, or a test that breaks when the canonical schema grows.
…olidate SQL patterns in schema_constants
VakninAriel
left a comment
There was a problem hiding this comment.
Code Review — PR #339
Verdict:
| Severity | Count |
|---|---|
| 🔴 Critical | 0 |
| 🟠 High | 2 |
| 🟡 Medium | 3 |
| 🟢 Minor | 1 |
The compaction architecture is well-designed — crash recovery, atomic swap, HNSW bookend protocol, and the MCP logging guard are solid. The three-phase guard (set flag → close connections → rename file) correctly prevents reconnects from corrupting in-progress compaction state, and the pre-submit compaction check in the executor is the right place for it.
Two high-severity bugs need fixing before merge. Three medium issues are straightforward one-liners each.
Findings
🟠 [High] HNSW metric extraction regex never matches — always rebuilds as cosine
Location: chunkhound/providers/database/duckdb_provider.py:2080–2088 · _extract_hnsw_metric
_extract_hnsw_metric tries to recover the HNSW similarity metric by regex-matching metric='...' from the CREATE INDEX SQL stored in duckdb_indexes(). DuckDB silently strips the entire WITH (...) clause when persisting CREATE INDEX DDL to its catalog, so create_sql never contains metric=. The regex never matches and the function always returns "cosine".
Any HNSW index created with metric='l2' or metric='ip' is silently rebuilt as cosine after compaction. This corrupts search ranking without any error, warning, or indication that the metric changed. SpiGAndromeda's inline comment at line 2080 confirmed this and cited pragma_hnsw_index_info() as the fix used by the external compactor.
# DuckDB catalog DDL (what the code actually receives):
CREATE INDEX idx_hnsw_1536 ON embeddings_1536 USING HNSW (embedding)
# WITH (metric = 'l2') ← stripped by DuckDB catalog storage
# regex looks for: metric='...' → no match → always "cosine"Suggested fix:
def _extract_hnsw_metric(self, conn: Any, index_name: str) -> str:
try:
row = conn.execute(
"SELECT metric FROM pragma_hnsw_index_info(?) LIMIT 1",
[index_name]
).fetchone()
if row:
return row[0]
except Exception:
pass
return "cosine"Callers at lines 2173 and 2243 must pass conn and the index name alongside create_sql.
🟠 [High] _executor_reseed_sequence runs O(max_id) work — stalls compaction and normal writes on large DBs
Location: chunkhound/providers/database/duckdb_provider.py:665–720 · _executor_reseed_sequence
Also: _compact_finalize:1354, _executor_materialize_embedding_table:1712
duckdb_sequences().last_value is a binary flag (NULL = never used, 1 = used at least once), not the actual sequence counter. The code comment acknowledges this but calls the consequence "just a gap." The actual consequence is advance_by = max_id - 1 on every invocation, executing SELECT nextval(seq) FROM range(max_id - 1) — O(max_id) work.
Compaction path: _compact_finalize calls _executor_reseed_sequence for files and chunks tables. On a database with 2M rows, compaction stalls for several seconds. The comment at line 1360 says embeddings "can't use DROP" and uses a direct range(max_id) path — but _executor_recreate_sequence (which already uses DROP + CREATE with an explicit START value, O(1)) exists in this same class and is used in _executor_rebuild_embedding_tables.
Normal operation path: _executor_materialize_embedding_table calls _executor_reseed_sequence for existing embedding tables on every call from _executor_ensure_embedding_table_exists. This is called per embedding upsert batch, so large databases accumulate O(max_id) overhead per write batch.
# The bug:
current_value = last_value # last_value is 1 (binary flag), not the actual counter
advance_by = max_id - 1 # e.g., 1,999,999 for a 2M-row DB
conn.execute(f"SELECT nextval('{seq}') FROM range({advance_by})") # O(max_id)Suggested fix: Use _executor_recreate_sequence (O(1) via DROP + CREATE):
def _executor_reseed_sequence(self, conn, table_name, sequence_name):
max_result = conn.execute(
f"SELECT COALESCE(MAX(id), 0) + 1 FROM {self._quote_duckdb_identifier(table_name)}"
).fetchone()
next_value = int(max_result[0]) if max_result else 1
self._executor_recreate_sequence(conn, sequence_name, next_value)For the embeddings sequence in _compact_finalize, use _executor_recreate_sequence(conn, "embeddings_id_seq", max_embedding_id + 1) instead of the range(max_id) loop.
🟡 [Medium] INSTALL vss in _compact_copy_data requires network — breaks offline compaction
Location: chunkhound/providers/database/duckdb_provider.py:1208 · _compact_copy_data
The rebuild connection calls INSTALL vss on the new DB. On an offline machine (air-gapped CI, disconnected dev environment, network failure during a long indexing run), this fails with a network error, aborting compaction and triggering _compact_restore. ChunkHound cannot run without vss already installed, so LOAD vss is sufficient here.
# Before (fails offline):
tgt_conn.execute("INSTALL vss")
tgt_conn.execute("LOAD vss")
# After:
tgt_conn.execute("LOAD vss") # vss is always installed before indexing begins🟡 [Medium] SET preserve_insertion_order = false missing from rebuild connection — peak memory risk
Location: chunkhound/providers/database/duckdb_provider.py:1206 · _compact_copy_data
Three other bulk-write paths set SET preserve_insertion_order = false before large INSERT ... SELECT operations (duckdb_provider.py:831, :2624, embedding_repository.py:494). The _compact_copy_data rebuild connection — which copies all files, chunks, and every embedding table — doesn't set this flag, causing DuckDB to buffer full results in insertion order. SpiGAndromeda's inline comment at line 1206 cites the external compactor's benchmarks: peak RAM is 3–4× source table size without this setting.
tgt_conn = duckdb.connect(str(compacted_path))
tgt_conn.execute("LOAD vss")
tgt_conn.execute("SET hnsw_enable_experimental_persistence = true")
tgt_conn.execute("SET preserve_insertion_order = false") # ← add this🟡 [Medium] Crash-recovery warning silenced in MCP mode — significant event goes unlogged
Location: chunkhound/providers/database/duckdb/connection_manager.py:596–600 · _recover_interrupted_compaction
When a .compact_backup file is found with a missing/empty live DB, the DB is restored from backup (a previous process crashed mid-compaction). This uses log_if_not_mcp("warning", "Recovering DuckDB database...") — completely suppressed under CHUNKHOUND_MCP_MODE=1 because loguru sinks are disabled in stdio mode.
Compare _compact_copy_data at lines 1290–1293, which explicitly prints the "dropped non-ChunkHound tables" warning to sys.stderr even in MCP mode: "Destructive operation — surface to stderr even in MCP mode." Crash recovery is at least as significant and should receive the same treatment.
msg = f"WARNING: Recovering DuckDB database from interrupted compaction backup: {backup_path}"
if os.environ.get("CHUNKHOUND_MCP_MODE") == "1":
print(msg, file=sys.stderr)
else:
logger.warning(msg)🟢 [Minor] Redundant log_if_not_mcp in the non-MCP else-branch at line 1295
Location: chunkhound/providers/database/duckdb_provider.py:1290–1295
The if os.environ.get("CHUNKHOUND_MCP_MODE") == "1" branch handles MCP mode; the else branch only runs in non-MCP mode, making log_if_not_mcp("warning", msg) there redundant — it never suppresses. A plain logger.warning(msg) is clearer. The intentional pattern (surface to stderr in MCP, loguru otherwise) is correct — this is a clarity nit only.
Verified — Prior review findings already addressed
- ✅
COMPACT_SAMPLE_INTERVALis 100 in current code (not 10 as flagged) - ✅
tool_requires_db()uses.get()with a conservativeTruefallback — noKeyError - ✅
_connect_provider()re-raisesDatabaseCompactionInProgressErrorafter logging - ✅
_recover_interrupted_compaction()gated onif not self._read_only— read-only mode safe - ✅ Realtime
embedmutations catchDatabaseCompactionInProgressErrorand call_handle_compaction_busy()for retry
Reviewed by Ariel Vaknin via Claude Code
…dexes, and MCP recovery
PR #339 — Reviewer PushbackThis document explains why five items raised during the review are not bugs and should not be changed. ❌ Feedback We Disagree With1. "Sequence
|
| Variant | Result |
|---|---|
DROP SEQUENCE seq (no CASCADE) |
Dependency Error: table "files" depends on sequence "files_id_seq" |
DROP SEQUENCE seq CASCADE |
Drops the dependent table too (verified) |
This fix would silently destroy data on a live database. The correct fix is different: in _compact_copy_data, where fresh sequences are created on a brand-new empty DB file before any tables exist, use CREATE SEQUENCE ... START {max_id + 1}. This eliminates reseeding entirely from the compaction path — no range(N) and no DROP needed.
3. "is_windows() removal is a breaking change" — @VakninAriel 1st review
Claim: Removing the is_windows() wrapper function is a breaking change that external callers may depend on.
Reality: All 6 callers in the codebase were migrated to use IS_WINDOWS directly. Zero remaining usage. The function was an internal utility with no external API contract. Removing dead code after cleaning up all callers is standard maintenance, not a regression.
4. "sys.modules shim removal needs a deprecation path" — @VakninAriel 1st review
Claim: Deleting chunkhound.services.realtime_indexing_service without a deprecation window will silently break external plugins that import from the legacy path.
Reality: The PR body explicitly documents this as a breaking change:
The compatibility module
chunkhound.services.realtime_indexing_servicehas been deleted (both the file and thesys.modulesshim). External code importing from this path will getImportError.
An ImportError is loud, immediate, and actionable — far better than silent breakage.
5. "MCP reads blocked during compaction" — @SpiGAndromeda inline
Claim: Reads are fast-failed by the compaction guard with no read-side retry, making DB-backed MCP tools unavailable during compaction.
Reality: This is by design. During compaction the database file is:
- Moved to
.compact_backup(no live DB at the original path) - A new compacted DB is built at
.compact_new - The compacted file is atomically swapped into place
There is no DB file to read from during steps 1-2. The compaction guard correctly surfaces DatabaseCompactionInProgressError to the MCP tool layer, which returns a structured error to the MCP client:
except DatabaseCompactionInProgressError:
log_if_not_mcp("info", "Database compaction in progress — DB-backed MCP tools will be "
"unavailable until compaction finishes. "
"Non-DB tools (daemon_status, websearch) are unaffected.")
raiseNon-DB tools (daemon status, web search) remain fully functional. This is correct behavior that follows the compaction guard's design contract.
Summary
| Feedback | Verdict | Rationale |
|---|---|---|
Sequence last_value is binary flag |
❌ Incorrect | Verified: it's the actual counter |
| Use DROP+CREATE instead of range(N) | ❌ Unsafe | DROP SEQUENCE CASCADE drops tables |
is_windows() removal is breaking |
❌ Not a bug | Internal API, 0 callers remain |
sys.modules shim needs deprecation |
❌ Intentional | Documented, ImportError is immediate |
| MCP reads blocked during compaction | ❌ By design | No DB to read during rebuild |
VakninAriel
left a comment
There was a problem hiding this comment.
Code Review — PR #339
Verdict: ✅ Approve
| Severity | Count |
|---|---|
| 🔴 Critical | 0 |
| 🟠 High | 0 |
| 🟡 Medium | 0 |
| 🟢 Minor | 2 |
Great work on the fixes — the HNSW metric regex → pragma_hnsw_index_info(), INSTALL vss → LOAD vss in _compact_copy_data, preserve_insertion_order, crash-recovery surfacing, and O(max_id) compaction reseeding are all addressed. Approving with two minor observations for follow-up.
Findings
🟢 F2 — Compaction finalize hardcodes metric = 'cosine' for restored HNSW indexes
Location: chunkhound/providers/database/duckdb_provider.py — _compact_finalize / _executor_ensure_all_hnsw_indexes
The pragma fix is correctly applied to _extract_hnsw_metric and used in _executor_get_existing_vector_indexes_from_catalog(catalog='src') during _compact_copy_data. However, _compact_copy_data returns only (emb_tables, had_hnsw: bool) — discarding the per-index metric infos. _compact_finalize then calls _executor_ensure_all_hnsw_indexes, which always creates indexes with metric = 'cosine'.
No current ChunkHound user is affected (we only ever create cosine indexes), but the regression gate is incomplete — the pragma fix benefits the HNSW-guarded-mutation path but not compaction finalize.
Suggested fix:
# _compact_copy_data — return index infos alongside had_hnsw:
- return emb_tables, had_hnsw
+ return emb_tables, had_hnsw, hnsw_index_infos
# _compact_finalize — use preserved metrics:
if had_hnsw:
- self._executor_ensure_all_hnsw_indexes(new_conn, state)
+ for index_info in hnsw_index_infos:
+ self._executor_recreate_vector_index_from_info(new_conn, state, index_info)🟢 F3 — _executor_reseed_sequence remains O(max_id) for live schema-migration path
Location: chunkhound/providers/database/duckdb_provider.py — _executor_reseed_sequence
The compaction path correctly uses CREATE SEQUENCE ... START N (O(1)), and the comment in _executor_reseed_sequence documents why DROP SEQUENCE CASCADE is unsafe on live databases. The method exists as a latent footgun — on a large DB with max_id ≫ 1M, any future caller would stall.
Note: _executor_rebuild_embedding_tables correctly calls _executor_recreate_sequence (not _executor_reseed_sequence) since the tables are already dropped at that point, so DROP+CREATE is safe there. The risk is future misuse.
Suggested fix (low priority): Add a docstring warning or rename to _executor_reseed_sequence_live_db_only to make the O(max_id) constraint explicit for future callers.
Reviewed by Ariel Vaknin via Claude Code
Fixed review comments, dismissing since you guys aren't available and we need to get this merged
…CP read-only, and fixes Merge main into matryoshka-fix-6-26. main changes incorporated: - DuckDB compaction with atomic swap (#339) - PowerShell (#350) and Metal (#351) language parsers - MCP --read-only flag (#329) - Research per-step timing (#355) - Various fixes: websearch late-completion guard, quickresearch orphan cleanup, token literal counting, claude-cli auto-updater - openai_compatible in factory's supported_providers() Conflict resolution: chunkhound/services/realtime_indexing_service.py was deleted on main (dead code, no production callers). The branch's ModuleType __class__ hack + its test were removed to match.
Note: This PR was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!
What & Why
Production-grade database compaction for DuckDB with atomic swap, plus supporting changes across MCP, realtime, configuration, and HNSW index lifecycle.
Changes
Compaction Protocol
duckdb_provider.py— Canonical rebuild + atomic swap with crash recovery. Backup-then-swap model: live DB → backup → stage new DB → atomic swap → delete backup. Handles Windows file locking, stale artifact cleanup, and HNSW index recreation.serial_executor.py— Compaction guard (DatabaseCompactionInProgressError) to fast-fail during rebuild. Auto-compaction sampling (1/N after writes, N=10 default). Extended timeout for compaction ops (660s).serial_database_provider.py— Base interfaces:compact_database,compact_if_needed,measure_fragmentation.indexing_coordinator.py—compact_database_with_metrics()andcompact_if_needed(). Sharedrun_batch_compaction_boundary()used by both legacy and canonical indexing paths.database.py— Legacyprocess_directorynow runs two batch compaction boundaries.HNSW Bookend Protocol
directory_indexing_service.py— Drop HNSW indexes before bulk processing, rebuild after final compaction boundary. Avoids per-batch maintenance overhead.duckdb_provider.py— HNSW index lifecycle management:drop_all_hnsw_indexes,ensure_all_hnsw_indexes, catalog-aware detection. Only recreated in_compact_finalizeif they existed before.Realtime Pipeline
pipeline.py— Compaction conflict handling: exponential backoff + jitter (0.75–1.25×), configurable retry budget. Files not surviving the budget are marked failed.random,log_if_not_mcp,DatabaseCompactionInProgressError.MCP Integration
logging_guard.py(new) —log_if_not_mcp()suppresses logs whenCHUNKHOUND_MCP_MODE=1. Used across all compaction paths, disconnects, and the realtime pipeline.Configuration
database_config.py— Newfragmentation_threshold_pctfield (default 30.0). CLI arg--fragmentation-threshold-pct, env var support.configuration.md— Documented compaction behavior, batch boundaries, and the unknown-table warning.Import Restructuring & Cleanup
RealtimeIndexingServicemoved fromchunkhound.services.realtime_indexing_service→chunkhound.services.realtime.service. All 18 callers updated.sys.modulescompatibility shim. Removed unusedis_windows()wrapper. Unused imports pruned across modules.Testing
test_duckdb_compaction.py(2350 lines) — Covers fragmentation measurement, compaction mechanics, crash recovery (copy failure, finalize failure, reconnection failure, stale artifacts), compaction guard, threshold boundaries, index flow, coordinator contract, data integrity, auto-compaction dispatch, concurrent compaction, Windows atomic replace.test_realtime_compaction_retry.py(new) — Retry logic, budget exhaustion, delete path retry.Breaking Changes
compact_database()renamed tocompact_database_with_metrics()— callers updated.chunkhound.services.realtime_indexing_servicehas been deleted (both the file and thesys.modulesshim). External code importing from this path will getImportError. Update imports tochunkhound.services.realtime.service.is_windows()function removed — useIS_WINDOWSconstant instead.Value
chunkhound index.Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md