CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 2m7s
CI & Build / integration (push) Failing after 2m15s
CI & Build / Build & push image (push) Skipped
Step 1 of milestone 669 "Knowledge reaches every project, work stays in its own: a fast exact search, cross-project recall ranked and labelled", for #6834 "auto_inject p90 latency has climbed since 10-23". A search with no project in scope took about 1 s, because it ranked about 26k chunks exactly. Two costs on that path, neither of which changes a result: - pgvector's vector type defaults to EXTERNAL storage, and a chunk row (about 1.5 KB of vector plus its text) is over the 2 KB toast threshold, so every vector sat in TOAST and each distance paid a lookup (151k buffer hits for 26k rows). Migration 0139 sets STORAGE MAIN on the four embedding tables and rewrites the existing rows once. - The materialized scope carried every chunk's text beside its distance and spilled the sort to disk. It now carries the id, chunk index and distance, and the text is joined back for the rows that survive the cut. Measured on the live corpus: 1,151 ms as before, 393 ms with the text out of the scope, before the storage change. The HNSW index stays out of the ranking. With pgvector 0.8's iterative scan it returned 7 to 60 of the true 144 nearest chunks under a narrow scope, at every setting tried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
139 lines
5.9 KiB
Python
139 lines
5.9 KiB
Python
"""Every semantic search scopes first, then ranks.
|
|
|
|
Ordered straight off a `*_embeddings` table, the planner walks the HNSW index:
|
|
it takes ~`hnsw.ef_search` (40) nearest chunks from every owner and project
|
|
and filters them afterwards, so an in-scope record behind 40 nearer ones the
|
|
caller cannot see is silently dropped. The remedy is one shape, `_rank_scoped`,
|
|
and these pin that every search goes through it — fixed in one search alone,
|
|
the others keep the fault, because nothing says they are the same query.
|
|
|
|
The integration lane's crowd tests show the behaviour on a real index; these
|
|
are the guard that fails on a rank-then-scope query whatever plan Postgres
|
|
picks.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import ast
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy.dialects import postgresql
|
|
|
|
from grimoire.models.embedding import NoteEmbedding
|
|
from grimoire.models.note import Note
|
|
from grimoire.services import embeddings as emb
|
|
from tests.helpers import compiled_sql
|
|
|
|
_SOURCE = Path("src/grimoire/services/embeddings.py")
|
|
|
|
|
|
def _searches() -> dict[str, ast.AsyncFunctionDef]:
|
|
tree = ast.parse(_SOURCE.read_text())
|
|
return {
|
|
node.name: node for node in tree.body
|
|
if isinstance(node, ast.AsyncFunctionDef)
|
|
and node.name.startswith("semantic_search_")
|
|
}
|
|
|
|
|
|
def _calls(fn: ast.AST) -> list[str]:
|
|
return [
|
|
getattr(n.func, "attr", None) or getattr(n.func, "id", None)
|
|
for n in ast.walk(fn) if isinstance(n, ast.Call)
|
|
]
|
|
|
|
|
|
def test_every_semantic_search_ranks_through_the_scoped_shape():
|
|
searches = _searches()
|
|
# The four corpora with an embedding table: if one is renamed or a fifth
|
|
# is added, this has to be looked at rather than silently passing.
|
|
assert set(searches) == {
|
|
"semantic_search_notes", "semantic_search_rules",
|
|
"semantic_search_milestones", "semantic_search_systems",
|
|
}
|
|
for name, fn in searches.items():
|
|
calls = _calls(fn)
|
|
assert "_rank_scoped" in calls, f"{name} does not rank through _rank_scoped"
|
|
assert "_scoped_chunks" in calls, f"{name} does not build its scope as chunks"
|
|
# Its own ORDER BY is the rank-then-scope shape: a distance ordered on the
|
|
# embedding table, which the index serves before the scope applies.
|
|
assert "order_by" not in calls, f"{name} orders by distance itself"
|
|
|
|
|
|
def test_a_rank_then_scope_query_is_caught():
|
|
"""Replay the guard against a query that ranks first and scopes after."""
|
|
old = ast.parse(
|
|
"async def semantic_search_x():\n"
|
|
" rows = await session.execute(select(Note, distance).select_from(E)"
|
|
".join(Note, E.note_id == Note.id).where(scope)"
|
|
".order_by(distance).limit(k))\n"
|
|
).body[0]
|
|
calls = _calls(old)
|
|
assert "_rank_scoped" not in calls and "order_by" in calls
|
|
|
|
|
|
def test_the_scope_is_materialized_and_the_order_is_over_it():
|
|
# Column against column, so there is no vector literal to inline: the
|
|
# shape is the subject here, not the query.
|
|
distance = NoteEmbedding.embedding.cosine_distance(NoteEmbedding.embedding)
|
|
scoped = (
|
|
emb._scoped_chunks(NoteEmbedding, NoteEmbedding.note_id, distance)
|
|
.join(Note, NoteEmbedding.note_id == Note.id)
|
|
.where(Note.user_id == 1)
|
|
)
|
|
sql = compiled_sql(
|
|
emb._rank_scoped(Note, scoped, embedding_model=NoteEmbedding,
|
|
record_key=NoteEmbedding.note_id, name="scoped_x", limit=5),
|
|
dialect=postgresql.dialect(),
|
|
)
|
|
# MATERIALIZED is what keeps the planner from inlining the CTE and walking
|
|
# the index again; the ORDER BY must name the CTE's column, not the table's.
|
|
assert "scoped_x AS MATERIALIZED" in sql
|
|
assert "ORDER BY scoped_x.distance" in sql
|
|
assert "note_embeddings.embedding <=>" in sql.split("ORDER BY")[0]
|
|
# The scope sits inside the CTE, where the ranking draws from.
|
|
cte_body = sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0]
|
|
assert "notes.user_id" in cte_body
|
|
|
|
|
|
def _ranked_sql(scoped) -> str:
|
|
return compiled_sql(
|
|
emb._rank_scoped(Note, scoped, embedding_model=NoteEmbedding,
|
|
record_key=NoteEmbedding.note_id, name="scoped_x", limit=5),
|
|
dialect=postgresql.dialect(),
|
|
)
|
|
|
|
|
|
def _scope_body(sql: str) -> str:
|
|
"""The materialized scope's own SELECT, up to where the ranking reads it."""
|
|
return sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0]
|
|
|
|
|
|
def _mine(scoped):
|
|
return scoped.join(Note, NoteEmbedding.note_id == Note.id).where(Note.user_id == 1)
|
|
|
|
|
|
def test_the_scope_carries_distances_and_the_text_is_read_for_the_winners_only():
|
|
"""Every in-scope chunk's text materialized beside its distance spills the
|
|
sort to disk on a whole-corpus scope (about 1 s on tens of thousands of
|
|
chunks), so the scope holds ids and distances, the cut happens over those,
|
|
and the text is joined back for the rows that survived it."""
|
|
distance = NoteEmbedding.embedding.cosine_distance(NoteEmbedding.embedding)
|
|
sql = _ranked_sql(_mine(emb._scoped_chunks(NoteEmbedding, NoteEmbedding.note_id, distance)))
|
|
|
|
assert "chunk_text" not in _scope_body(sql), "the materialized scope carries the chunk text"
|
|
# The cut sits inside the subquery the text is joined onto, so the join
|
|
# reads at most `limit` rows of text.
|
|
nearest = sql.split(") AS scoped_x_nearest", 1)[0].rsplit("FROM scoped_x", 1)[1]
|
|
assert "LIMIT 5" in nearest
|
|
assert "scoped_x_text.chunk_text" in sql
|
|
assert "scoped_x_text.chunk_index = scoped_x_nearest.chunk_index" in sql
|
|
|
|
|
|
def test_a_scope_that_carries_the_text_is_caught():
|
|
"""Replay the guard against the shape it replaced: a scope that labels the
|
|
chunk text beside the distance."""
|
|
distance = NoteEmbedding.embedding.cosine_distance(NoteEmbedding.embedding)
|
|
old = _mine(emb._scoped_chunks(NoteEmbedding, NoteEmbedding.note_id, distance)
|
|
.add_columns(NoteEmbedding.chunk_text.label("chunk_text")))
|
|
assert "chunk_text" in _scope_body(_ranked_sql(old))
|