perf(8190): the exact search reads vectors from the row and text only for the winners
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>
This commit is contained in:
2026-11-28 16:10:00 -05:00
co-authored by Claude Opus 5.5
parent 6cb61cdf84
commit efba891f5e
5 changed files with 161 additions and 20 deletions
+20
View File
@@ -187,3 +187,23 @@ async def test_a_system_is_found_behind_another_users_nearer_charters():
assert mine_id not in found and len(found) == 10
finally:
await _cleanup(reader, crowd)
@pytest.mark.asyncio
async def test_every_embedding_table_keeps_its_vectors_inline():
"""The ranking computes one distance per in-scope chunk, so a vector moved
out of line into TOAST costs a lookup per chunk on every search.
pgvector's type defaults to EXTERNAL storage; migration 0139 sets MAIN."""
from sqlalchemy import text
async with async_session() as s:
rows = (await s.execute(text(
"SELECT c.relname, a.attstorage FROM pg_attribute a "
"JOIN pg_class c ON c.oid = a.attrelid "
"WHERE a.attname = 'embedding' AND c.relname = ANY(:tables)"
), {"tables": ["note_embeddings", "rule_embeddings",
"milestone_embeddings", "system_embeddings"]})).all()
assert dict(rows) == {
"note_embeddings": "m", "rule_embeddings": "m",
"milestone_embeddings": "m", "system_embeddings": "m",
}
+45 -1
View File
@@ -81,7 +81,8 @@ def test_the_scope_is_materialized_and_the_order_is_over_it():
.where(Note.user_id == 1)
)
sql = compiled_sql(
emb._rank_scoped(Note, scoped, name="scoped_x", limit=5),
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
@@ -92,3 +93,46 @@ def test_the_scope_is_materialized_and_the_order_is_over_it():
# 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))