From efba891f5e5de4680061b675bfbb6913233772d7 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 28 Nov 2026 16:10:00 -0500 Subject: [PATCH] perf(8190): the exact search reads vectors from the row and text only for the winners 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 --- .../versions/0139_embedding_vectors_inline.py | 42 +++++++++++ src/grimoire/models/embedding.py | 4 +- src/grimoire/services/embeddings.py | 69 ++++++++++++++----- tests/test_integration_search_scope.py | 20 ++++++ tests/test_search_scope_shape.py | 46 ++++++++++++- 5 files changed, 161 insertions(+), 20 deletions(-) create mode 100644 alembic/versions/0139_embedding_vectors_inline.py diff --git a/alembic/versions/0139_embedding_vectors_inline.py b/alembic/versions/0139_embedding_vectors_inline.py new file mode 100644 index 00000000..a705e9bc --- /dev/null +++ b/alembic/versions/0139_embedding_vectors_inline.py @@ -0,0 +1,42 @@ +"""embedding vectors stored inline, not in TOAST + +Revision ID: 0139 +Revises: 0138 +Create Date: 2026-11-28 + +Every semantic search ranks its in-scope chunks exactly, one distance per +chunk (see embeddings._rank_scoped). pgvector's `vector` type defaults to +EXTERNAL storage, and a chunk row (a 384-dimension vector, about 1.5 KB, plus +the chunk's text) is over Postgres's 2 KB toast threshold, so the vector was +moved out of line and every distance paid a TOAST lookup: several buffer +reads per chunk, on every search. + +`STORAGE MAIN` keeps the vector in the row. When a row is still too wide, the +chunk text (EXTENDED) is compressed or moved out instead, which costs nothing +on the ranking path: the text is read only for the rows a search returns. + +A storage change applies to rows written after it, so the existing rows are +rewritten once. Casting through `real[]` produces a fresh value, which the +row is stored with under the new setting; assigning the column to itself +would keep the old out-of-line pointer. +""" +from alembic import op + +revision = "0139" +down_revision = "0138" +branch_labels = None +depends_on = None + +TABLES = ("note_embeddings", "rule_embeddings", "milestone_embeddings", "system_embeddings") + + +def upgrade() -> None: + for table in TABLES: + op.execute(f"ALTER TABLE {table} ALTER COLUMN embedding SET STORAGE MAIN") + op.execute(f"UPDATE {table} SET embedding = embedding::real[]::vector") + + +def downgrade() -> None: + # Rows already inline stay inline; new rows follow the type's default. + for table in TABLES: + op.execute(f"ALTER TABLE {table} ALTER COLUMN embedding SET STORAGE EXTERNAL") diff --git a/src/grimoire/models/embedding.py b/src/grimoire/models/embedding.py index f3dc5c71..bf732cad 100644 --- a/src/grimoire/models/embedding.py +++ b/src/grimoire/models/embedding.py @@ -10,7 +10,9 @@ from grimoire.models import Base # native pgvector `vector(384)` (see migration 0067) so similarity is ranked in # Postgres by `<=>` rather than by a full-table Python cosine scan. The semantic # searches rank the CALLER'S in-scope chunks exactly rather than through the -# HNSW index, which ranks before it filters (see embeddings._rank_scoped). +# HNSW index, which ranks before it filters (see embeddings._rank_scoped). The +# column is stored inline (`STORAGE MAIN`, migration 0139), so that exact pass +# reads each vector from its row rather than from TOAST. EMBEDDING_DIM = 384 diff --git a/src/grimoire/services/embeddings.py b/src/grimoire/services/embeddings.py index a5495ca9..f38607ce 100644 --- a/src/grimoire/services/embeddings.py +++ b/src/grimoire/services/embeddings.py @@ -22,6 +22,7 @@ from contextvars import ContextVar from typing import TYPE_CHECKING from sqlalchemy import and_, delete, func, or_, select +from sqlalchemy.orm import aliased from grimoire.models import async_session from grimoire.models.embedding import NoteEmbedding, RuleEmbedding @@ -861,43 +862,68 @@ def record_best_chunk(report: dict | None, chunks: dict[int, dict]) -> None: # a MATERIALIZED CTE with the distance computed inside it; the index cannot # order a materialized CTE, so the ranking over it is exact. # -# What exact costs is one distance per in-scope chunk. Rules, milestones and -# Systems are hundreds of chunks. Notes are the big corpus, but the hook arms -# that run on every prompt are project-scoped, so the pass is over one -# project's chunks rather than the whole table; `retrieval_logs.duration_ms` -# on those arms is where that claim is checked. If it ever -# stops holding, pgvector 0.8's `hnsw.iterative_scan` keeps the index and is -# the next step — gated on the extension version, because an unknown `hnsw.*` -# setting errors and these searches would read that error as "nothing found". +# The index is not a faster way to the same answer. pgvector 0.8's +# `hnsw.iterative_scan` keeps walking the graph until enough rows pass the +# filter, but under a narrow scope (one small project and the lessons) it +# returns a different set: 7 to 60 of the true 144 nearest chunks, in strict +# and relaxed order alike and at an `ef_search` of 200 or 1000. Only a broad +# scope comes back right. So the ranking stays exact everywhere. +# +# What exact costs is one distance per in-scope chunk, and two things keep +# that cheap on a corpus of tens of thousands of chunks: +# +# - The vector is stored inline (`STORAGE MAIN`, migration 0139). pgvector's +# type defaults to EXTERNAL, and a chunk row (a 1.5 KB vector plus its text) +# is over the 2 KB toast threshold, so every vector was moved out of line +# and each distance paid a TOAST lookup. +# - The scope carries the record id, the chunk index and the distance, never +# the chunk text. The text of every in-scope chunk materialized beside the +# distance spills to disk on a whole-corpus scope, so `_rank_scoped` joins +# it back only for the rows that survive the cut. def _scoped_chunks(embedding_model, record_key, distance): """A select over an embedding table's chunks, each with its distance — the caller joins its record and adds its scope, and `_rank_scoped` orders it. - The columns are labelled so every search's CTE carries the same four. + The columns are labelled so every search's CTE carries the same three. The + chunk text is not one of them: `_rank_scoped` reads it for the winners. """ return select( record_key.label("record_id"), distance.label("distance"), embedding_model.chunk_index.label("chunk_index"), - embedding_model.chunk_text.label("chunk_text"), ).select_from(embedding_model) -def _rank_scoped(record_model, scoped_chunks, *, name: str, limit: int): +def _rank_scoped(record_model, scoped_chunks, *, embedding_model, record_key, + name: str, limit: int): """(record, distance, chunk_index, chunk_text) rows, nearest first, drawn ONLY from the in-scope chunks — exactly, never through the index. + The nearest `limit` chunks are cut first, over the distances alone; only + then is each survivor's text read back from `embedding_model` by its key + (`record_key`, `chunk_index`), so a broad scope never carries every + chunk's text through the sort. + The row shape is what each search's collapse already unpacks, so a search moves onto this without its callers or its mocks noticing. """ scoped = scoped_chunks.cte(name).prefix_with("MATERIALIZED") - return ( - select(record_model, scoped.c.distance, scoped.c.chunk_index, scoped.c.chunk_text) - .join(scoped, scoped.c.record_id == record_model.id) + nearest = ( + select(scoped.c.record_id, scoped.c.distance, scoped.c.chunk_index) .order_by(scoped.c.distance) .limit(limit) + .subquery(f"{name}_nearest") + ) + text_of = aliased(embedding_model, name=f"{name}_text") + text_key = getattr(text_of, record_key.key) + return ( + select(record_model, nearest.c.distance, nearest.c.chunk_index, text_of.chunk_text) + .join(nearest, nearest.c.record_id == record_model.id) + .join(text_of, and_(text_key == nearest.c.record_id, + text_of.chunk_index == nearest.c.chunk_index)) + .order_by(nearest.c.distance) ) @@ -1116,7 +1142,9 @@ async def semantic_search_notes( # bar is applied after the collapse, where the rejected scores can # still be seen. rows = list((await session.execute( - _rank_scoped(Note, stmt, name="scoped_note_chunks", limit=fetch) + _rank_scoped(Note, stmt, embedding_model=NoteEmbedding, + record_key=NoteEmbedding.note_id, + name="scoped_note_chunks", limit=fetch) )).all()) except Exception: logger.warning("Failed to query note embeddings", exc_info=True) @@ -1635,7 +1663,8 @@ async def semantic_search_rules( rows = (await session.execute( # Overfetch so collapsing chunks to their best row still fills # the page — the same reason the note search overfetches. - _rank_scoped(Rule, scoped, name="scoped_rule_chunks", + _rank_scoped(Rule, scoped, embedding_model=RuleEmbedding, + record_key=RuleEmbedding.rule_id, name="scoped_rule_chunks", limit=limit * _CHUNK_OVERFETCH) )).all() except Exception: @@ -1838,7 +1867,9 @@ async def semantic_search_milestones( ) async with async_session() as session: rows = (await session.execute( - _rank_scoped(Milestone, scoped, name="scoped_milestone_chunks", + _rank_scoped(Milestone, scoped, embedding_model=MilestoneEmbedding, + record_key=MilestoneEmbedding.milestone_id, + name="scoped_milestone_chunks", limit=limit * _CHUNK_OVERFETCH) )).all() except Exception: @@ -2010,7 +2041,9 @@ async def semantic_search_systems( ) async with async_session() as session: rows = (await session.execute( - _rank_scoped(System, scoped, name="scoped_system_chunks", + _rank_scoped(System, scoped, embedding_model=SystemEmbedding, + record_key=SystemEmbedding.system_id, + name="scoped_system_chunks", limit=limit * _CHUNK_OVERFETCH) )).all() except Exception: diff --git a/tests/test_integration_search_scope.py b/tests/test_integration_search_scope.py index a96b551a..eb42b6cc 100644 --- a/tests/test_integration_search_scope.py +++ b/tests/test_integration_search_scope.py @@ -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", + } diff --git a/tests/test_search_scope_shape.py b/tests/test_search_scope_shape.py index b3a517c0..34b27041 100644 --- a/tests/test_search_scope_shape.py +++ b/tests/test_search_scope_shape.py @@ -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))