Skip to content

fix(compaction): preserve non-cosine HNSW metrics during auto-compaction rebuilds - #464

Open
3431481073 wants to merge 3 commits into
chunkhound:mainfrom
3431481073:fix/456-hnsw-metric-compaction
Open

3431481073 wants to merge 3 commits into
chunkhound:mainfrom
3431481073:fix/456-hnsw-metric-compaction

Conversation

@3431481073

Copy link
Copy Markdown

Sampled auto-compaction could silently rewrite any non-cosine HNSW index as cosine. That changes search quality with no error and no log line.

The cause is three small gaps in the DuckDB provider:

  • _compact_copy_data recorded only a had_hnsw boolean, discarding the per-index metric the source catalog scan already returned.
  • _compact_finalize then called _executor_ensure_all_hnsw_indexes, which created every canonical index WITH (metric = 'cosine').
  • _extract_hnsw_metric also fell back to cosine silently when pragma_hnsw_index_info() raised.

This carries the discovered source index records through compaction and reuses each table's metric when rebuilding, and makes metric extraction failures loud.

Fixes #456.

Changes

  • _compact_copy_data returns the source catalog's HNSW index records (source_hnsw_indexes) instead of had_hnsw.
  • _compact_finalize passes those records to _executor_ensure_all_hnsw_indexes, which maps table to metric and uses it in CREATE INDEX ... WITH (metric = ...).
  • _extract_hnsw_metric logs a warning with the index name and error when the pragma raises or returns no row, instead of defaulting silently.
  • test_non_cosine_hnsw_metric_survives_index_rebuild now forces the sampled auto-compaction path deterministically (COMPACT_SAMPLE_INTERVAL = 1, forced fragmentation measure) and asserts the l2sq metric survives.

Testing

  • Target test passes with the fix; fails on the previous code with assert 'cosine' == 'l2sq'.
  • Related HNSW/copy/threshold compaction tests: 10 passed.
  • Full tests/test_duckdb_compaction.py: 131 passed.

uv run pytest tests/test_smoke.py -v -n auto cannot pass on this Windows host. The CLI subprocess harness decodes chunkhound search --help output with the GBK locale codec and raises UnicodeDecodeError, so stdout is empty for the 8 CLI checks. The non-CLI smoke tests pass (6 passed). This is a host locale issue, not the compaction change; Linux CI should exercise the same test with UTF-8.

What I could not verify

  • _extract_hnsw_metric still falls back to cosine with a warning, rather than fail-closed.
  • In MCP stdio mode loguru sinks are disabled, so the warning may not be visible there.
  • The public ensure_all_hnsw_indexes() path without source_indexes still defaults to cosine; out of scope for this issue.
  • If multiple HNSW indexes exist on one embedding table with different metrics, the first discovered metric wins. Not exercised by tests.

@HananKavitzAmat
HananKavitzAmat self-requested a review November 1, 2026 09:10
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary: The fix is correct for the sampled auto-compaction success path, but it leaves the rollback path unfixed and adds a second metric-restore mechanism next to an existing one.

I read the diff, the PR description, and the surrounding code in duckdb_provider.py. I did not run the new test, so the "fails before, passes after" claim is unverified. The checkout is main, which doesn't include the PR.

Grouping

  1. Compaction plumbing: _compact_copy_data, _compact_finalize and _executor_compact_database now pass index records instead of had_hnsw.
  2. Metric handling: _executor_ensure_all_hnsw_indexes takes source_indexes, and _extract_hnsw_metric now logs warnings.
  3. Test: test_non_cosine_hnsw_metric_survives_index_rebuild.

The groups share one file and depend on each other, so I reviewed them sequentially myself rather than launching parallel agents. The change is only ~60 lines.

Strengths

  • The fix targets the real root cause: the piscovered and then thrown away. Theboolean-to-records change is minimal. The test forces the sampled auto-compactioasserts that compaction ran. That makes it areal contract test for user-visible search semantics. The description openly lists what was not h the diff.
    sues
    jor
  • duckdb_provider.py:1462-1463 (_compact_restore): the rollback path still calls _executor_ensure_all_hnsw_indexes(restoredindexes. The restore signature still takeshad_hnsw=bool(hnsw_indexes). The metric is only preserved if the backed-up DB still holds its HNSW index, because _executor_hnsw_index_exists skips existingopped during the failed swap, rollbacksilently rebuilds as cosine, which is the same bug. _compact_restore should take hnsw_indexes too. The PR also doesn't test a failure after finalize star
  • duckdb_provider.py:2353-2410: there is already a helper, executor_recreate_vector_index_from_info (line 2376). It takes an index record, validates the identes the index with its original name andmetric. It is used at lines 2658, 2711 and 2747. The PR adds a second metric-restore path inside ensure_all, with its own normalize and fallback logic, inst would also preserve custom index names suchas hnsw. The PR rebuilds every index under the canonical idx_hnsw name, soa custom-named index is renamed on compacthe PR, but the PR is the natural place tofix it.
    Minor duckdb_provider.py:2392-2410: the metric imetric}'. It is safe here because_normalize_hnsw_metric allowlists it, but the invalid-metric fallback to cosine is itself a silent rewrite. That is the failure this PR is meant to prevent. Iompaction, or at least log at error level.
  • duckdb_provider.py:2120-2133: _extract_hnsw_metric still returns cosine on failure, only now with a warning. In MCP stdio mode log_if_not_mcp and the loguru sning is invisible in the main deploymentmode. The PR states this itself. During compaction, _compact_copy_data runs the catalog scan with fail_on_error=True, so a failed metric lookup that returns no row also cannot tell thecosine default apart from a real cosine index.
  • duckdb_provider.py:2393-2405: with severalhe first discovered metric wins and theothers are dropped. The PR notes this; it should at least log it. The commit and PR text say "Fixes bug(compaction): auto-compaction rebuilds non-cosine HNSW indexes with cosine #456", wmpact_backup rollback behavior is untestedfor the l2sq case. Test: monkeypatch.setattr(db, "_executor_m ...) and wrapping _executor_compact_database reach into private internals. That is acceptable for forcing the path, but the test could instead assert on the on-disk file size.
  • duckdb_provider.py:1273-1281: the new formatting of hnsw_indexes = (...) has redundant parentheses. Ruff format would likely collapse them.
    usability
  • Build the rebuild step on _executor_recreate_vector_index_from_info, using the records already discovered, instead of extending ensure_all with a source_metr
  • Thread the discovered index records through _compact_restore as well, so both exits of compaction share one restore routine.
  • Move the metric normalize-or-default logic into one helper if both paths still need it.

Decision: REQUEST CHANGES. Fix the _compact_restore gap, and prefer reusing _executor_recreate_vector_index_from_info.
Make an unknown metric fail during compactione.

_compact_copy_data now returns the source catalog's HNSW index records
instead of a had_hnsw boolean, and _compact_finalize passes them to
_executor_ensure_all_hnsw_indexes so each rebuilt canonical index keeps
its per-table metric instead of a hardcoded cosine.

_extract_hnsw_metric now logs a warning when pragma_hnsw_index_info()
fails or returns no row, instead of silently defaulting to cosine.

The non-cosine HNSW test now forces the sampled auto-compaction path
deterministically (COMPACT_SAMPLE_INTERVAL=1 plus a forced fragmentation
measure) and asserts the metric survives the rebuild.

Refs chunkhound#456
Compaction finalize and rollback now share one restore path built on
_executor_recreate_vector_index_from_info, so each discovered source
index keeps its original name and metric. Previously finalize rebuilt
canonical idx_hnsw_<dims> indexes with a hardcoded cosine metric, and
rollback only received a had_hnsw boolean.

Source metrics are validated before the file swap: an unsupported metric
aborts compaction while the original DB is still intact. During
compaction, a pragma_hnsw_index_info() failure now raises through strict
extraction instead of silently defaulting to cosine; best-effort callers
log at ERROR level and also write to stderr in MCP mode.

Tests force sampled auto-compaction deterministically (zero threshold
and sample interval 1) and cover the rollback exit and unknown-metric
failure.

Refs chunkhound#456
@3431481073
3431481073 force-pushed the fix/456-hnsw-metric-compaction branch from f91a453 to 33ccd52 Compare November 1, 2026 15:27
@3431481073

Copy link
Copy Markdown
Author

Addressed the review in 33ccd52:

  • Rollback path: _compact_restore now takes the discovered hnsw_indexes records and restores through the same _executor_restore_hnsw_indexes_from_records path as finalize. A new test simulates a post-swap failure with an unrecoverable backup; it fails on the previous commit with assert 'cosine' == 'l2sq'.
  • Duplicate implementation: removed the metric-map/normalize/fallback logic from _executor_ensure_all_hnsw_indexes; compaction now reuses _executor_recreate_vector_index_from_info, preserving the original index name and metric. The custom-name test asserts alt_live_idx survives and idx_hnsw_3 is not created.
  • Unknown metrics: validated before the file swap; compaction raises RuntimeError while the original DB is still intact.
  • _extract_hnsw_metric: gained strict; compaction passes strict=True, so a pragma failure or missing row raises. Best-effort callers log at error and also print to stderr in MCP mode.
  • Multiple metrics: all discovered records are recreated individually; there is no first-wins map.
  • Tests: dropped most private monkeypatches; the test forces the sample and asserts the Compaction complete log plus on-disk size.
  • Nit: removed the redundant parentheses.

pytest tests/test_duckdb_compaction.py passes (133 passed). Regression controls fail on the previous commit for the restore, unknown-metric, and custom-name cases. Only this file was run; the repo-wide smoke suite was not run here.

@3431481073

Copy link
Copy Markdown
Author

CI is action_required because this is a fork PR. Could a maintainer approve the workflow run when convenient? The local compaction suite passes 133/133.

The metric regression test forced sampled auto-compaction with
COMPACT_SAMPLE_INTERVAL=1 and a zero fragmentation threshold, but the
threshold check still required the environment-dependent fragmentation
ratio to exceed 1.0. On CI runners the tiny DB measured <= 1.0, so the
sample fired but compaction was skipped and "Compaction complete" was
never logged (the same failure on ubuntu and windows shard 1).

Call compact_database() directly instead: it bypasses sampling and the
fragmentation heuristic, so the test deterministically exercises the
compaction finalize path. Assert the positive compacted size, the
"Compaction complete" log, the repo's not-larger contract, and that the
non-cosine metric survives. The test still fails on main with cosine.

Refs chunkhound#456
@3431481073

Copy link
Copy Markdown
Author

Fixed the CI failure in 123b470 without marking the test flaky.

Root cause: the test forced sampling with COMPACT_SAMPLE_INTERVAL = 1, but it still depended on the fragmentation threshold gate. With fragmentation_threshold_pct = 0.0, compaction requires the measured ratio to be > 1.0; the tiny test DB's PRAGMA database_size vs pragma_storage_info accounting is filesystem-dependent, and on the CI runners it was <= 1.0. The sample fired, the check ran, compaction was skipped, so Compaction complete never appeared.

The test now calls db.compact_database() directly, bypassing both sampling and the fragmentation heuristic. It asserts compacted_size > 0, the Compaction complete log line, the not-larger size contract, and that idx_hnsw_3 stays l2sq.

pytest tests/test_duckdb_compaction.py passes (133 passed); the pytest-split shard simulation passes (43 passed). The revised test still fails on main with assert 'cosine' == 'l2sq'.

@3431481073

Copy link
Copy Markdown
Author

The new run 41430234017 is action_required again after the test fix. Could a maintainer approve it? The local compaction suite passes 133/133, and the previously failing metric test now runs deterministically.

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

@3431481073 I looked into the action_required thing. It seems like a policy in github for first time contributors. Hopefuly once this PR is pushed, you won't be expiriencing it again.

@ofriw

ofriw commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

@3431481073 tests are failing, could you please fix them so we can run review again?

This branch has not been deployed

No deployments
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.

bug(compaction): auto-compaction rebuilds non-cosine HNSW indexes with cosine

3 participants