Skip to content

Commit e3c5d43

Browse files
fstraszclaude
andcommitted
perf(duckdb): score embeddings before joining in semantic search
The exact (non-HNSW) semantic query joined embeddings to chunks and files first, so every joined row carried its whole vector, and computed the cosine twice when a threshold was set. It now scores each embedding into (chunk_id, similarity), joins that to chunks/files to apply the path filter, threshold and page, and fetches the chunk rows for the page only. The joins stay in the page step, so an embedding whose chunk or file is gone never ranks or shortens a page (embeddings have no foreign key to chunks). ORDER BY/LIMIT sit over the join, never over a bare scan of the embeddings table, so the VSS optimizer cannot turn it into an approximate HNSW scan. Measured on a 14k-chunk, 1024-dim index: 299 ms -> 124 ms per query, same top 90. The new test compares against a brute-force ranking and fails when the page step's joins are made LEFT JOINs (orphan returned / page short). Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5c1ad70 commit e3c5d43

2 files changed

Lines changed: 180 additions & 22 deletions

File tree

‎chunkhound/providers/database/duckdb_provider.py‎

Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4003,8 +4003,48 @@ def _executor_search_semantic(
40034003
WITH (metric = 'cosine')
40044004
""")
40054005

4006-
# Build query with dimension-specific table
4006+
# Score every embedding first, so the joins carry an id and a float
4007+
# instead of a whole vector per row, then join to apply the scope
4008+
# filters (an embedding whose chunk or file is gone must never
4009+
# rank or shorten a page), take the page, and fetch the chunk rows
4010+
# for that page only. Same rows and ranking as joining first;
4011+
# measured ~2.4x faster at 14k x 1024-dim vectors (299 -> 124 ms).
4012+
# The ORDER BY/LIMIT sit over the join, never over a bare scan of
4013+
# the embeddings table, so DuckDB's VSS optimizer cannot rewrite
4014+
# this into an approximate HNSW index scan.
4015+
params: list[Any] = [query_embedding, provider, model]
4016+
page_conditions = ""
4017+
4018+
path_like: str | None = None
4019+
if normalized_path is not None:
4020+
path_like = self._build_path_like_pattern(normalized_path)
4021+
4022+
if threshold is not None:
4023+
page_conditions += " AND scored.similarity >= ?"
4024+
params.append(threshold)
4025+
4026+
if path_like is not None:
4027+
page_conditions += " AND CONCAT('/', f.path) LIKE ? ESCAPE '\\'"
4028+
# Prepend / so %/repo_a/% only matches repo_a as a complete directory component.
4029+
params.append(path_like)
4030+
40074031
query = f"""
4032+
WITH scored AS (
4033+
SELECT
4034+
chunk_id,
4035+
array_cosine_similarity(embedding, ?::FLOAT[{query_dims}]) AS similarity
4036+
FROM {table_name}
4037+
WHERE provider = ? AND model = ?
4038+
),
4039+
page AS (
4040+
SELECT scored.chunk_id, scored.similarity
4041+
FROM scored
4042+
JOIN chunks c ON scored.chunk_id = c.id
4043+
JOIN files f ON c.file_id = f.id
4044+
WHERE TRUE{page_conditions}
4045+
ORDER BY scored.similarity DESC
4046+
LIMIT ? OFFSET ?
4047+
)
40084048
SELECT
40094049
c.id as chunk_id,
40104050
c.symbol,
@@ -4014,30 +4054,14 @@ def _executor_search_semantic(
40144054
c.end_line,
40154055
f.path as file_path,
40164056
f.language,
4017-
array_cosine_similarity(e.embedding, ?::FLOAT[{query_dims}]) as similarity,
4057+
page.similarity,
40184058
c.metadata
4019-
FROM {table_name} e
4020-
JOIN chunks c ON e.chunk_id = c.id
4059+
FROM page
4060+
JOIN chunks c ON page.chunk_id = c.id
40214061
JOIN files f ON c.file_id = f.id
4022-
WHERE e.provider = ? AND e.model = ?
4062+
ORDER BY page.similarity DESC
40234063
"""
40244064

4025-
params: list[Any] = [query_embedding, provider, model]
4026-
4027-
path_like: str | None = None
4028-
if normalized_path is not None:
4029-
path_like = self._build_path_like_pattern(normalized_path)
4030-
4031-
if threshold is not None:
4032-
query += f" AND array_cosine_similarity(e.embedding, ?::FLOAT[{query_dims}]) >= ?"
4033-
params.append(query_embedding)
4034-
params.append(threshold)
4035-
4036-
if path_like is not None:
4037-
query += " AND CONCAT('/', f.path) LIKE ? ESCAPE '\\'"
4038-
# Prepend / so %/repo_a/% only matches repo_a as a complete directory component.
4039-
params.append(path_like)
4040-
40414065
# Get total count for pagination
40424066
# Build count query separately to avoid string replacement issues
40434067
count_query = f"""
@@ -4061,7 +4085,6 @@ def _executor_search_semantic(
40614085

40624086
total_count = conn.execute(count_query, count_params).fetchone()[0]
40634087

4064-
query += " ORDER BY similarity DESC LIMIT ? OFFSET ?"
40654088
params.extend([page_size, offset])
40664089

40674090
results = conn.execute(query, params).fetchall()
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
"""DuckDB semantic search returns the exact ranking, scoped like the old query.
2+
3+
The query scores embeddings before joining chunks/files. These tests pin what
4+
that must not change: the ranking equals a brute-force cosine ranking, an
5+
embedding whose chunk no longer exists is never returned and never shortens a
6+
page, and the path filter, threshold and offset still apply.
7+
"""
8+
9+
import asyncio
10+
from pathlib import Path
11+
12+
import numpy as np
13+
import pytest
14+
15+
from chunkhound.providers.database.duckdb_provider import DuckDBProvider
16+
from chunkhound.services.indexing_coordinator import IndexingCoordinator
17+
18+
_DIMS = 8
19+
_PAGE = 3
20+
21+
22+
def _source(prefix: str) -> str:
23+
return "\n\n".join(
24+
f"def {prefix}_{i}(value):\n"
25+
f" total = value * {i + 2}\n"
26+
f" for step in range({i + 3}):\n"
27+
f" total += step\n"
28+
f" return total\n"
29+
for i in range(8)
30+
)
31+
32+
33+
@pytest.fixture
34+
def indexed(tmp_path: Path):
35+
pytest.importorskip("duckdb")
36+
root = tmp_path / "repo"
37+
for sub in ("alpha", "beta"):
38+
(root / sub).mkdir(parents=True)
39+
(root / sub / f"{sub}.py").write_text(_source(sub))
40+
41+
provider = DuckDBProvider(db_path=tmp_path / "db.duckdb", base_directory=root)
42+
provider.connect()
43+
coordinator = IndexingCoordinator(provider, root)
44+
paths: dict[int, str] = {}
45+
for sub in ("alpha", "beta"):
46+
result = asyncio.run(
47+
coordinator.process_file(root / sub / f"{sub}.py", skip_embeddings=True)
48+
)
49+
for chunk in provider.get_chunks_by_file_id(result["file_id"], as_model=False):
50+
paths[int(chunk["id"])] = sub
51+
assert sum(1 for p in paths.values() if p == "beta") > 2 * _PAGE, (
52+
"fixture needs more beta chunks than two pages"
53+
)
54+
55+
rng = np.random.default_rng(5)
56+
vectors = {cid: rng.standard_normal(_DIMS).tolist() for cid in paths}
57+
provider.insert_embeddings_batch(
58+
[
59+
{
60+
"chunk_id": cid,
61+
"provider": "test",
62+
"model": "mini",
63+
"embedding": vec,
64+
"dims": _DIMS,
65+
}
66+
for cid, vec in vectors.items()
67+
]
68+
)
69+
query = rng.standard_normal(_DIMS).tolist()
70+
# An embedding left behind by a deleted chunk, identical to the query, so
71+
# it would rank first if it were scored without the join.
72+
orphan_id = max(paths) + 1000
73+
provider.insert_embeddings_batch(
74+
[
75+
{
76+
"chunk_id": orphan_id,
77+
"provider": "test",
78+
"model": "mini",
79+
"embedding": query,
80+
"dims": _DIMS,
81+
}
82+
]
83+
)
84+
try:
85+
yield provider, paths, vectors, query, orphan_id
86+
finally:
87+
provider.disconnect()
88+
89+
90+
def _expected(vectors, query, keep=lambda cid: True):
91+
q = np.asarray(query)
92+
scored = [
93+
(cid, float(np.dot(v, q) / (np.linalg.norm(v) * np.linalg.norm(q))))
94+
for cid, v in ((cid, np.asarray(vec)) for cid, vec in vectors.items())
95+
if keep(cid)
96+
]
97+
return sorted(scored, key=lambda item: item[1], reverse=True)
98+
99+
100+
def _search(provider, query, **kwargs):
101+
results, pagination = provider.search_semantic(
102+
query, provider="test", model="mini", **kwargs
103+
)
104+
return [(int(r["chunk_id"]), r["similarity"]) for r in results], pagination
105+
106+
107+
def _assert_same(actual, expected):
108+
assert [cid for cid, _ in actual] == [cid for cid, _ in expected]
109+
assert [s for _, s in actual] == pytest.approx([s for _, s in expected], abs=1e-5)
110+
111+
112+
def test_ranking_is_exact_and_skips_orphaned_embeddings(indexed) -> None:
113+
provider, _, vectors, query, orphan_id = indexed
114+
expected = _expected(vectors, query)
115+
116+
first, pagination = _search(provider, query, page_size=_PAGE)
117+
second, _ = _search(provider, query, page_size=_PAGE, offset=_PAGE)
118+
119+
assert orphan_id not in [cid for cid, _ in first + second]
120+
_assert_same(first, expected[:_PAGE])
121+
_assert_same(second, expected[_PAGE : 2 * _PAGE])
122+
assert pagination["total"] == len(vectors)
123+
124+
125+
def test_path_filter_and_threshold_still_apply(indexed) -> None:
126+
provider, paths, vectors, query, _ = indexed
127+
128+
in_beta, _ = _search(provider, query, page_size=_PAGE, path_filter="beta")
129+
_assert_same(
130+
in_beta, _expected(vectors, query, lambda c: paths[c] == "beta")[:_PAGE]
131+
)
132+
133+
floor = _expected(vectors, query)[4][1]
134+
above, _ = _search(provider, query, page_size=50, threshold=floor)
135+
_assert_same(above, [e for e in _expected(vectors, query) if e[1] >= floor - 1e-6])

0 commit comments

Comments
 (0)