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
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:
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user