Repository navigation
Conversation
…verfetch post-filtering
…r HNSW breaking change
|
● ## Code Review — PR #392 Verdict:
Findings🟡 Undocumented new failure mode in multi-hop paginationLocation: Multi-hop search now raises Suggested fix: ❯ create md format of the feedback I will post it 🟡 Unbounded O(N) pagination cost when HNSW is disabledLocation: With Suggested fix: 🟢 Budget-exhausted error path has no test coverageLocation: The Suggested fix: 🟢 New CI lane runs unconditionally and gates pages-artifactLocation: The new Suggested fix: What checked out fine
Reviewed by Ariel Vaknin via Claude Code 🟡 Unbounded O(N) pagination cost when HNSW is disabledLocation: With Suggested fix: 🟢 Budget-exhausted error path has no test coverageLocation: The Suggested fix: 🟢 New CI lane runs unconditionally and gates pages-artifactLocation: The new Suggested fix: |
# Conflicts: # CHANGELOG.md
…p pages exceed the 500-result cap
grzegorznowak
left a comment
There was a problem hiding this comment.
Review — PR #392
PR: chunkhound/chunkhound#392 — fix(duckdb): leverage HNSW index in semantic search by decoupling filters from ANN scan and add toggle to disable
Reviewed head: fda723c3 (base 1f574e4b; 40 files, +5,229/−991). Line references below are from that head.
Verdict summary
The advertised contracts are wired consistently: provider-level semantic totals/windowing, inclusive similarity thresholds, the HNSW toggle and read-only guard, bounded candidate overfetch, and candidate_budget_exhausted. The config/toggle/CLI path also looks clean.
That contract-conformance result is narrower than implementation correctness: it verifies that the declared rules have matching code paths, tests, and docs; it does not prove stable result identity across separately evaluated pages or correct composition through the diff-aware wrapper. Those two gaps expose two high-severity and one medium-severity pagination bugs below. One high-severity test defect actively codifies the problematic implementation, while the remaining test, CI, and documentation findings are medium severity.
High
H1 — Multi-hop pagination can return duplicate and skipped rows because the rerank universe changes by page
Evidence: chunkhound/services/search/multi_hop_strategy.py:154,157,522
requested_fetch = requested_end + 1initial_limit = max(min(page_size * 3, cap), requested_fetch)page = results[offset : offset + page_size]requested_end is offset + page_size, so deeper pages fetch and rerank candidates that earlier pages never saw. A deterministic 31-candidate example with page_size=10 demonstrates the failure: the first two calls fetch 30 candidates; the third fetches 31. If candidate 31 has the highest rerank score, the returned IDs are [1..10], [11..20], and [20..29]. ID 20 is duplicated and ID 30 is skipped, with no score ties or ANN nondeterminism required.
Impact: Sequential multi-hop pagination can corrupt a collected top-K result set with duplicate and missing chunks.
Fix: Materialize and rerank the same bounded, query-wide candidate universe for every page, then slice it; add a consecutive-page no-duplicate/no-skip invariant test.
H2 — vector_source="both" overrides the multi-hop default limit and rejects small explicit limits
Evidence: chunkhound/services/diff_aware_search_service.py:295-322; chunkhound/services/search/multi_hop_strategy.py:135-138
db_result_limit = result_limit if result_limit is not None else db_fetchpage_size=db_fetch,
result_limit=db_result_limit,if materializable_cap is not None and requested_end > materializable_cap:
raise MaterializationLimitError(Here db_fetch is 1,000 with HNSW enabled and 10,000 with it disabled (HNSW_CANDIDATE_BUDGET = 10_000 at chunkhound/core/constants.py:10-11). In multi-hop, the ordinary default is 500 (chunkhound/services/search/multi_hop_strategy.py:108-115). Therefore:
- with no explicit limit, both-mode replaces the 500 default with 1,000/10,000 and can hand that many candidates to the reranker;
- with
result_limit < db_fetch, it still requestspage_size=db_fetch, so the materialization validator rejects the call. For example, HNSW-on both-mode withresult_limit=300requests a 1,000-row page against a 300-row cap. The base revision passed the user limit through without this new window validation, so that call did not fail this way.
Impact: Existing small-limit queries can now raise MaterializationLimitError; omitted limits can multiply rerank cost and change ranking behavior relative to the documented 500 default.
Fix: Do not use db_fetch as both the page size and the default result limit: resolve one effective multi-hop limit, preserve the configured/user limit, and cap the DB fetch page to that value.
H3 — The new multi-hop deep-page test asserts H1's problematic fetch as correct
Evidence: tests/test_multi_hop_semantic_search.py:217-231
assert database.semantic_calls[0] == {"page_size": 156, "offset": 0}This declares the offset-growing fetch (150 + 5 + 1) correct, which is H1's root cause. The test verifies the internal call shape but never compares independently evaluated consecutive pages.
Impact: CI is green for H1 and would turn red for a direct page-invariant-universe fix, actively discouraging the correct behavior.
Fix: Replace the internal fetch-size assertion with the observable contract: no duplicates/skips across consecutive pages whose reranked candidate boundary changes.
Medium
M1 — The suite has no end-to-end tied-score, multi-page pagination contract
Evidence: tests/helpers/duckdb_vector_fixtures.py:144-153; tests/unit/test_duckdb_semantic_search_contracts.py:691-704; tests/fixtures/multi_hop_synthetic.py:194-204
provider, chunk_ids, [[1.0, 0.01 * index, 0.0] for index in range(count)]QUERY_VECTOR, PROVIDER, MODEL, page_size=len(chunk_ids)page = results[offset : offset + page_size]The real-DuckDB pagination fixture uses distinct vectors. The equal-score test requests all tied chunks in one unsliced page. The synthetic multi-hop provider slices one fixed ranking, so it cannot reproduce a page-dependent candidate universe. Both-mode tests likewise do not exercise a small explicit result_limit through real multi-hop behavior.
Impact: The pagination-correctness class behind H1, H2, and the tied-row issue below remains unguarded.
Fix: Add a real-DuckDB tied-score test that walks consecutive pages and asserts preserved order, no duplicates, and complete union through single-hop, multi-hop, and diff-aware both-mode with an explicit small limit.
M2 — Single-hop HNSW pagination can skip or duplicate equal-distance rows
Evidence: chunkhound/providers/database/duckdb_provider.py:3998-4004,4383-4385,4505-4513
ORDER BY distance ASC
LIMIT ? OFFSET 0results.sort(
key=lambda result: (-float(result[sort_key]), int(result["chunk_id"]))
)offset + page_size + 1,Each page asks HNSW for a different-size top-N candidate set. SQL leaves equal distances unordered; Python adds chunk_id ordering only after that page's candidate set has been selected. Consequently, equal-distance rows at a page boundary need not form the same prefix between calls.
Impact: Users can receive duplicate or missing chunks when paginating common equal-embedding/equal-distance results.
A direct SQL tie-breaker is not clearly safe: the existing plan test (tests/unit/test_duckdb_semantic_search_contracts.py:87-89) hard-runs the requirement that the helper query stay HNSW-index-eligible and asserts the tie-breaker is absent:
assert "ORDER BY DISTANCE ASC, CHUNK_ID" not in query.upper()
assert "HNSW_INDEX_SCAN" in "\n".join(str(row) for row in plan)Whether appending , chunk_id ASC would drop this helper out of HNSW_INDEX_SCAN must be verified against a real HNSW-capable DuckDB (not assertable here - this sandbox cannot build an HNSW index). Fix should be confirmed in the HNSW CI lane before committing to a tie-breaker.
Fix (safe direction): Keep the ANN query HNSW-eligible, but make the retrieved candidate universe page-invariant per query (or maintain a stable cursor/snapshot), then sort by (distance, chunk_id) and slice; add a real multi-page tied-score test. If a stable SQL tie-breaker is preferred, confirm it preserves HNSW_INDEX_SCAN on the required CI lane first.
M3 — The HNSW CI job runs on every PR and includes the 10,000-row recall benchmark
Evidence: .github/workflows/ci.yml:3-7,236-277; tests/unit/test_duckdb_semantic_search_contracts.py:769-777,826-846
pull_request:hnsw-contract-tests:n = 10_000The job has no changed-path condition, and its -m hnsw command includes the test marked both hnsw and slow, including Recall@100. The earlier concern that this job gates pages-artifact is stale: that job's needs list does not include it (.github/workflows/ci.yml:279-289).
Impact: Unrelated PRs pay the full HNSW corpus/recall cost.
Fix: Keep fast HNSW contracts on relevant PRs via a changed-path job condition, and move the slow recall benchmark to a scheduled or explicitly triggered lane.
M4 — HNSW-marked tests execute only in the dedicated CI job
Evidence: .github/workflows/ci.yml:62-177,268-276; tests/conftest.py:16-29,67-83
command: uv run pytest tests/ -v --junit-xml=test-results.xml --splits 2 --group ${{ matrix.split }}connection.execute("LOAD vss")for item in hnsw_items:
item.add_marker(skip_hnsw)The ordinary OS/split matrix does not install VSS; the collection probe is load-only and skips HNSW tests when the extension is unavailable. Only hnsw-contract-tests installs VSS before running them.
Impact: HNSW behavior has no matrix redundancy and is exercised on only one OS/job.
Fix: Install VSS in at least one general matrix lane as well, or explicitly make and protect the fail-closed dedicated job as the sole HNSW contract owner.
M5 — The CHANGELOG overstates total=None and omits both-mode's effective limit
Evidence: CHANGELOG.md:11-14,33-50; chunkhound/services/search/semantic_window.py:34-36; chunkhound/services/diff_aware_search_service.py:295-322
`pagination["total"]` is now `None` for semantic searchreturn None if normalize_semantic_window_cap(cap) is not None else exact_totalUncapped multi-hop passes cap=None and therefore reports a numeric exact total, not None. The documented 500-result multi-hop boundary is also bypassed in both-mode when db_fetch becomes the forwarded default limit (H2), and the small-limit failure condition is not documented.
Impact: API consumers can implement the wrong pagination termination logic and encounter an undocumented limit/error in diff-aware both-mode.
Fix: Qualify total=None as the provider/capped-search behavior, and document both-mode's actual effective limit and MaterializationLimitError condition (or fix H2 and document the preserved 500 default).
M6 — Configuration/index documentation mixes provider and multi-hop semantics
Evidence: site/src/pages/docs/configuration.md:198-202; CHANGELOG.md:52-53,70-73
`false` = exact linear scan (uncapped, `total` is `None`, no HNSW index created or used...)Semantic search also requires a cosine-compatible HNSW indexThe first statement is true for provider-level totals but not uncapped multi-hop totals (M5). The second is over-absolute because disabled exact mode explicitly creates and uses no HNSW index.
Impact: Operators and API users receive contradictory guidance about exact-mode totals and index requirements.
Fix: Scope total semantics to the provider layer and qualify the index requirement with “when HNSW is enabled.”
M7 — The PR body's breaking-change list omits the multi-hop 500-result boundary
Evidence: chunkhound/core/config/research_config.py:133-138; chunkhound/services/search/multi_hop_strategy.py:131-138. The PR body's Breaking section lists total=None, the HNSW [0,1000) window, threshold semantics, and the read-only requirement, but not this boundary.
multi_hop_result_limit: int = Field(
default=500,raise MaterializationLimitError(
f"Requested result window ends at {requested_end}, beyond the "The CHANGELOG does describe the 500-result default at CHANGELOG.md:45-50, but PR-only readers will not see it or the both-mode interaction in H2.
Impact: Callers can discover the new page boundary only at runtime when page end 501 raises.
Fix: Add the 500-result multi-hop materialization boundary to the PR body's breaking/migration list and describe the corrected both-mode behavior.
Suggested priority before merge
- H1 and M1/M2: establish stable pagination invariants, then fix both multi-hop and tied single-hop ordering.
- H2: preserve user/configured limits through diff-aware both-mode.
- H3: replace the offset-growing implementation assertion as part of the H1 fix.
- M3/M4 CI changes and M5-M7 documentation corrections.
Conflict resolutions: - ci.yml: keep main's composite-action CI refactor and native-wheel-smoke-arm64 / native-dev-macos jobs; keep hnsw-contract-tests rewired onto build-rust-extension. pages-artifact.needs unchanged beyond main's native jobs. - CHANGELOG.md: our DuckDB/HNSW entries under [Unreleased]; main's 6.0.0 release section and link refs kept intact. - constants.py: keep HNSW_CANDIDATE_BUDGET and EMBEDDING_MODEL_UPGRADES. - duckdb_provider.py: keep both imports (core.constants, core.exceptions). Deferred (follow-up): gate the Rust pipeline's HNSW bracket on database.duckdb_hnsw_enabled so --no-duckdb-hnsw holds on the Rust path.
# Conflicts: # CHANGELOG.md
|
Some measurements in support of the Growth with HNSW on vs off, same edits. 15 rounds of 40-file edits, each followed by an incremental index:
Each embedding write batch rewrote the whole HNSW index into fresh space, about 68 MB per batch at this size. After dropping the index and compacting, our live index went from 356 MB to 71 MB. The current Exact-scan cost. A plain exact top-10 scan measured about 70 ms at 16k × 1024-dim vectors and about 360 ms at 100k. One observation for exact mode that I haven't root-caused:
So the parameter binding may be worth a look if exact mode becomes common. Separately, I've opened #468 for a WAL-replay bug in 🤖 Generated with Claude Code |
|
A correction to my comment above, plus one result that may be useful for this PR's exact (HNSW-off) mode. Correction. I timed the
What does cost time in exact mode is the join order. The query joins WITH scored AS (
SELECT chunk_id, array_cosine_similarity(embedding, ?::FLOAT[1024]) AS similarity
FROM embeddings_1024 WHERE provider = ? AND model = ?
),
page AS (
SELECT scored.chunk_id, scored.similarity
FROM scored
JOIN chunks c ON scored.chunk_id = c.id
JOIN files f ON c.file_id = f.id
WHERE TRUE /* threshold, path filter */
ORDER BY scored.similarity DESC
LIMIT ? OFFSET ?
)
SELECT c.id, c.symbol, c.code, ..., page.similarity, c.metadata
FROM page JOIN chunks c ON page.chunk_id = c.id JOIN files f ON c.file_id = f.id
ORDER BY page.similarity DESCOn that index this went from 299 ms to 124 ms per query, with the same top 90. Two details matter:
It's on our fork as fstrasz/chunkhound@e3c5d43a, with a test against a brute-force cosine ranking that also covers an orphaned embedding, the path filter, the threshold and the offset. The test fails if the page step's joins are made 🤖 Generated with Claude Code |
Resolve 21 conflicts by taking main's streaming transient search (issue #336) as the base and migrating this branch's HNSW and API-honesty work onto it. - Remove DiffAwareSearchService and its unit test; TransientSearchService is the only transient engine, shared by git history and web pages. - Keep main's pagination metadata (total, corpus_total, has_more, next_offset) and add candidate_budget_exhausted as a provider-originated recall signal. It never replaces total and is forwarded by the both and hybrid paths. - DuckDB semantic search reports an exact total and leaves total=None only under candidate-budget exhaustion (main's #521 semantics). Malformed vectors are skipped without losing the HNSW index scan, and the HNSW-disabled exact path stays uncapped. - Keep path_filter.py from main; the DuckDB provider keeps its local validation and LIKE-pattern helpers. - Realtime: main's event filtering, duplicate handling, and inotify-overflow resync, plus the branch's delivery probe, supervision cadence, 8 s setup budget, and dropped-batch rescan. The macOS rescan-aware FSEvents observer is now actually constructed instead of a plain Observer. - MCP tools use the SDK 2.x single dispatch point and streaming transient injection; no truncation plumbing remains. - Config keeps the branch's env-source policy and gains main's VOYAGE_API_KEY fallback; CI keeps HNSW contract gating and mirrors it in prepare-alpha. - Tests: sandbox state moved outside tmp_path so repos and directory listings stay clean, fixture paths no longer depend on cwd, realtime fakes follow the observer/probe contracts, and pagination assertions encode the merged numeric-total contract. Verified: pytest tests/ 6187 passed, 100 skipped; smoke 19 passed; cargo check clean.
Note: This PR was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!
Summary
Fixes DuckDB HNSW so the index is actually used during semantic search — the old SQL caused DuckDB's query planner to skip the index and fall back to brute-force scans. Adds a
duckdb_hnsw_enabledtoggle to opt out of HNSW entirely, since the real-world performance gain is negligible relative to indexing overhead and DB size.What Changed
array_cosine_distance(), with provider/model/path/threshold filters applied afterward via post-filter overfetch (3x→2x→10K max budget)duckdb_hnsw_enabledtoggle (defaulttrue): whenfalse, skips HNSW index creation entirely and uses exact linear scanssemantic_result_window_cap:1000when HNSW is on,Nonewhen off — enforced at the service layerpagination["total"]is nowNone— usehas_more/next_offsetinsteadthresholdis now an inclusive cosine-similarity floor (was distance ceiling) — convert with1 - distancecandidate_budget_exhaustedflag signals short pages in HNSW mode--no-duckdb-hnswWhy
Before this PR: The old
search_semanticSQL mixed provider/model/path/threshold filters into the same query as the HNSW ANN scan. DuckDB's query planner couldn't use the HNSW index with those filters present, so it silently fell back to full sequential scans — the index was maintained but never actually accelerated queries.After this PR: The HNSW scan is a clean candidate-fetch (no filters), followed by a filtering pass. This lets DuckDB actually use the index. But measurements showed the speedup is negligible for typical corpora, so the toggle lets operators skip HNSW entirely for faster indexing and smaller databases with no meaningful loss.
Breaking
pagination["total"]isNone; usehas_more/next_offset[0, 1000)when HNSW is enabledthresholdis now a similarity floor — convert with1 - distance--no-duckdb-hnswTests
15 new/modified test files covering exact-mode contracts, HNSW overfetch budgets, config validation, and failure modes.
Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md