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
@@ -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")
+3 -1
View File
@@ -10,7 +10,9 @@ from grimoire.models import Base
# native pgvector `vector(384)` (see migration 0067) so similarity is ranked in # 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 # 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 # 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 EMBEDDING_DIM = 384
+51 -18
View File
@@ -22,6 +22,7 @@ from contextvars import ContextVar
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from sqlalchemy import and_, delete, func, or_, select from sqlalchemy import and_, delete, func, or_, select
from sqlalchemy.orm import aliased
from grimoire.models import async_session from grimoire.models import async_session
from grimoire.models.embedding import NoteEmbedding, RuleEmbedding 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 # a MATERIALIZED CTE with the distance computed inside it; the index cannot
# order a materialized CTE, so the ranking over it is exact. # order a materialized CTE, so the ranking over it is exact.
# #
# What exact costs is one distance per in-scope chunk. Rules, milestones and # The index is not a faster way to the same answer. pgvector 0.8's
# Systems are hundreds of chunks. Notes are the big corpus, but the hook arms # `hnsw.iterative_scan` keeps walking the graph until enough rows pass the
# that run on every prompt are project-scoped, so the pass is over one # filter, but under a narrow scope (one small project and the lessons) it
# project's chunks rather than the whole table; `retrieval_logs.duration_ms` # returns a different set: 7 to 60 of the true 144 nearest chunks, in strict
# on those arms is where that claim is checked. If it ever # and relaxed order alike and at an `ef_search` of 200 or 1000. Only a broad
# stops holding, pgvector 0.8's `hnsw.iterative_scan` keeps the index and is # scope comes back right. So the ranking stays exact everywhere.
# the next step — gated on the extension version, because an unknown `hnsw.*` #
# setting errors and these searches would read that error as "nothing found". # 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): def _scoped_chunks(embedding_model, record_key, distance):
"""A select over an embedding table's chunks, each with its distance — the """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. 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( return select(
record_key.label("record_id"), record_key.label("record_id"),
distance.label("distance"), distance.label("distance"),
embedding_model.chunk_index.label("chunk_index"), embedding_model.chunk_index.label("chunk_index"),
embedding_model.chunk_text.label("chunk_text"),
).select_from(embedding_model) ).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 """(record, distance, chunk_index, chunk_text) rows, nearest first, drawn
ONLY from the in-scope chunks — exactly, never through the index. 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 The row shape is what each search's collapse already unpacks, so a search
moves onto this without its callers or its mocks noticing. moves onto this without its callers or its mocks noticing.
""" """
scoped = scoped_chunks.cte(name).prefix_with("MATERIALIZED") scoped = scoped_chunks.cte(name).prefix_with("MATERIALIZED")
return ( nearest = (
select(record_model, scoped.c.distance, scoped.c.chunk_index, scoped.c.chunk_text) select(scoped.c.record_id, scoped.c.distance, scoped.c.chunk_index)
.join(scoped, scoped.c.record_id == record_model.id)
.order_by(scoped.c.distance) .order_by(scoped.c.distance)
.limit(limit) .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 # bar is applied after the collapse, where the rejected scores can
# still be seen. # still be seen.
rows = list((await session.execute( 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()) )).all())
except Exception: except Exception:
logger.warning("Failed to query note embeddings", exc_info=True) logger.warning("Failed to query note embeddings", exc_info=True)
@@ -1635,7 +1663,8 @@ async def semantic_search_rules(
rows = (await session.execute( rows = (await session.execute(
# Overfetch so collapsing chunks to their best row still fills # Overfetch so collapsing chunks to their best row still fills
# the page — the same reason the note search overfetches. # 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) limit=limit * _CHUNK_OVERFETCH)
)).all() )).all()
except Exception: except Exception:
@@ -1838,7 +1867,9 @@ async def semantic_search_milestones(
) )
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( 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) limit=limit * _CHUNK_OVERFETCH)
)).all() )).all()
except Exception: except Exception:
@@ -2010,7 +2041,9 @@ async def semantic_search_systems(
) )
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( 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) limit=limit * _CHUNK_OVERFETCH)
)).all() )).all()
except Exception: except Exception:
+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 assert mine_id not in found and len(found) == 10
finally: finally:
await _cleanup(reader, crowd) 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) .where(Note.user_id == 1)
) )
sql = compiled_sql( 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(), dialect=postgresql.dialect(),
) )
# MATERIALIZED is what keeps the planner from inlining the CTE and walking # 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. # The scope sits inside the CTE, where the ranking draws from.
cte_body = sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0] cte_body = sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0]
assert "notes.user_id" in cte_body 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))