Skip to content

perf(core): rank search by id and fetch note text for returned rows only - #1755

Merged
phernandez merged 4 commits into
perf/1746-search-rank-by-idfrom
perf/1746-search-late-text
Oct 11, 2026
Merged

phernandez merged 4 commits into
perf/1746-search-rank-by-idfrom
perf/1746-search-late-text

Conversation

@phernandez

@phernandez phernandez commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Part 3 of the #1746 search rework, stacked on #1753. Search now ranks by id and fetches note text only for the rows it returns, and each returned note's excerpt is ranked against that note's own chunks.

After #1750 capped note text at 4 KB per row, a hybrid search still moved text for every candidate it considered:

  • the FTS leg's 100+ rows,
  • every vector candidate row,
  • the text of every chunk in the vector window.

Ranking reads none of that text.

Ranking reads no text

  • The hybrid FTS leg calls FtsBackend.search(..., with_text=False), which selects NULL AS content_snippet plus the stored length.
  • The vector candidate row fetch and chunk hydration select ids, scores and lengths only. WindowChunk carries a chunk key, not text, so the ranking types cannot carry text.

Text for the returned rows only

SemanticSearch._materialize runs once the returned rows are known. That is the page, plus the rerank prefix, which is materialized before the reranker reads it.

  • Each row gets its capped content_snippet in one query.
  • Each vector-matched row gets matched_chunk_text: its whole text when it is small (2,000 characters or less, as before), otherwise its five chunks nearest the query.

The bound per search is page × (4 KB preview + 5 × ~900-char chunks), plus the rerank prefix when a reranker is on. A search.materialize Logfire event records the rows and the characters of preview and excerpt text per search.

Excerpts no longer depend on the window

A built-in index ranks every chunk of each returned note against the query. This reuses index.search with an admission naming that note's chunks (#1753), batched under sqlite-vec's 4,096-neighbour limit. Before, an excerpt joined the best chunks the candidate window happened to read:

  • On main, the runaway widening read nearly every chunk of a note.
  • With a bounded window, an excerpt could miss some of a note's best passages.

An external index (Milvus) cannot be asked about chosen chunks, so it still quotes its window chunks, bounded for the rerank prefix as #1557 requires.

Measured against main on a real project

The parity harness ran 138 searches against a copy of a real local project (485 notes, 5,671 chunks, notes up to 191 KB).

  • All 138 rankings, scores and has_more match main.
  • 188 matched_chunk excerpts differ. Every one quotes all of main's passages plus more, where main's window had read fewer than five of the note's chunks. None lost a passage or changed order. The other 70 searches are identical in every field.

Local latency, in process, median / p95 over the same 138 searches:

main #1750 #1753 this PR
All searches 440 / 1,352 ms 216 / 526 ms 188 / 272 ms 200 / 286 ms

Locally, this PR costs about 10 ms more than #1753. SQLite runs in-process, so the text it no longer moves was free there, and ranking each returned note's chunks adds a few small queries. The savings are in Postgres egress: candidate text no longer leaves the database at all.

Test plan

  • Real sqlite-vec: a long note whose best chunk is the only one in the window still quotes its five nearest chunks. The candidate rows the ranking read carried lengths and no text. Excerpt ranking batches under its chunk budget and skips a note with no ready chunks.
  • The Avoid duplicate hybrid/vector retrieval for stable reranker pagination #1557 stable-pagination test runs on the built-in path and on an external-index path (same real index, read as external). Pages and rerank documents are identical at every page size.
  • The prefix-passages test runs on the external path, where window-bounded excerpts still apply.
  • Unit tests that stub the database run on OfflineSemanticSearch, whose text stages answer from memory.
  • just fast-check
  • just test-unit-sqlite: 8247 passed. search_reader.py coverage under tests/repository: 100%
  • just test-int-sqlite: 642 passed. The real-Redis read-cache tests errored because the Docker daemon stopped mid-run on a full disk; rerun with Docker back, test-int/read_cache: 65 passed.
  • Postgres (testcontainers): repository, search routers, search service, migration graph: 1,329 passed
  • Full Postgres suite (CI)

🤖 Generated with Claude Code

https://claude.ai/code/session_01EQPZkbnuxxtTEJoNJCkt45

phernandez and others added 3 commits October 11, 2026 15:39
After the stopgap capped note text at 4 KB per row, a hybrid search still
moved text for every candidate: the FTS leg (100+ rows), the vector
candidate rows, and the text of every chunk in the window. Ranking reads
none of it (#1746).

- The hybrid FTS leg (FtsBackend.search with_text=False), the vector
  candidate row fetch, and chunk hydration select ids, scores and the
  stored text length only. WindowChunk carries a chunk key, not text.
- SemanticSearch._materialize runs once the returned rows are known: the
  page, and the rerank prefix before the reranker reads it. Each row
  gets its capped content_snippet; each vector-matched row gets
  matched_chunk_text, its whole text when small, else its five chunks
  nearest the query.
- A built-in index ranks every chunk of each returned note against the
  query (index.search with an admission naming the note's chunks), so an
  excerpt no longer depends on how far the candidate window reached. An
  external index (Milvus) still quotes its window chunks, bounded for the
  rerank prefix (#1557).

Unit tests that stub the database run on OfflineSemanticSearch, whose text
stages answer from memory; real sqlite-vec and pgvector tests cover the
database path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EQPZkbnuxxtTEJoNJCkt45
Signed-off-by: phernandez <paul@basicmachines.co>
A search.materialize event reports the rows returned, how many quote an
excerpt, and the characters of preview and excerpt text read, so the
per-search text budget (#1746) is visible in Logfire instead of in an
egress bill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EQPZkbnuxxtTEJoNJCkt45
Signed-off-by: phernandez <paul@basicmachines.co>
The #1557 stable-pagination test now also runs with the real index read as
an external one (ranked by similarity alone, filtered after, widened), which
is the only path that still extends the rerank prefix bound. The excerpt
test ranks notes directly under a two-chunk budget, so the ranker batches
and skips a note with no ready chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EQPZkbnuxxtTEJoNJCkt45
Signed-off-by: phernandez <paul@basicmachines.co>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T22:30:26.258104Z 8d2578b New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@phernandez
phernandez added this pull request to stack #1756 October 11, 2026 22:03
#1753 ended the window loop after the first read whenever the index had
evaluated the filters, on the grounds that every chunk was admitted. But
admitted chunks still collapse to rows: with ~52 chunks per note, a
100-chunk read holds two notes, so a default (entity-filtered) MCP search
for ten results could return one or two while more admitted notes sat
just past the window. Filtered reads now widen to the row target as they
did before, each read still carrying the admission and skipping the
reader-side filter pass. The rerank prefix bound extends for any filtered
window again, since a widened built-in window can also admit its leading
rows past the fixed bound.

Also accept the admission argument in the semantic coverage test's
_run_vector_query recorder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EQPZkbnuxxtTEJoNJCkt45
Signed-off-by: phernandez <paul@basicmachines.co>
@phernandez
phernandez merged commit a97abcc into main Oct 11, 2026
30 of 38 checks passed
phernandez added a commit that referenced this pull request Nov 7, 2026
…bytes (#2074)

## Why

Basic Memory Cloud bills Neon transfer to customers as of 2026-11-07,
and search is most of that transfer (#1746). Cloud already runs #1755
(late text fetch) and #2062, yet production still moves about 18 MB per
search.

A new byte counter shows that most of what a vector or hybrid search
still reads is chunk keys, not note text:

- **Excerpts.** To pick each returned row's best passages, search read
every chunk key of every returned note.
- **Vector window.** Filtered searches (every default MCP search)
widened the window until enough rows appeared, re-reading thousands of
chunk rows. On a large project that loop runs up to 50,000 chunks.

## What

- **Row search in the index.** pgvector and sqlite-vec get
`search_rows`. The database ranks chunks, keeps each search row's best
`chunks_per_row`, and returns at most `limit` rows. The collapse SQL is
shared by both engines (`collapse_to_rows_sql`).
- **One read per window.** A built-in index reads its window once: no
widening loop and no manifest hydration statement, because the index
already joins the ready manifest.
- **Smaller scans.**
- An approximate scan (pgvector HNSW, sqlite-vec) reads 10 chunks per
requested row.
- pgvector's exact ranking of 50,000 or fewer admitted chunks reads them
all, as before.
- On SQLite the scan is capped at 4,096 chunks (the issue's "one bounded
overfetch").
- **Excerpts.** One count query per page, then a row search with
`chunks_per_row=5` over the returned rows.
- **Milvus** keeps the chunk path and its widening loop.
- **Ranking.** Rows still rank by their best chunk's similarity, and
fusion is unchanged. The vector leg now hands fusion up to
`candidate_limit` rows instead of `candidate_limit` chunks.

## Measuring it

- `tests/statement_traffic.py` records rows and bytes returned per
statement.
- `test-int/test_search_traffic.py` runs searches through the HTTP route
over 40 KB notes (production's average is 41 KB). Its regular test
asserts a byte budget and at most two nearest-neighbour queries per
search.
- `test_benchmark_search_traffic` (`-m benchmark`) prints per-statement
bytes. `BASIC_MEMORY_SEARCH_TRAFFIC_NOTES` sets its size.

Bytes per search, page of 10, `main` (7f7a219) → this branch. Each
note is cut into about 129 chunks.

| backend, notes | fts | vector | hybrid | hybrid, no filters |
| --- | --- | --- | --- | --- |
| SQLite, 300 | 48 → 48 KB | 379 → 115 KB | 398 → 135 KB | 398 → 135 KB
|
| Postgres, 100 | 47 → 47 KB | 367 → 104 KB | 381 → 118 KB | 381 → 118
KB |

Rows per vector search fell from about 3,200 to about 350–500. On
Postgres I used 100 notes because seeding takes about 9 s per note; the
300-note Postgres baseline timed out after 190.

What a 300-note search still reads:

| bytes | what | note |
| --- | --- | --- |
| 43 KB | the page's `content` (4,000 chars per row) | public response
contract |
| 34 KB | excerpts | 5 chunks × 10 rows |
| 20 KB | title, path and metadata for the 100-row window | could be
deferred to the returned page; follow-up |
| 12–18 KB | the window itself | |

The fixture cannot show the production-scale gain. There, the widening
loop read up to 50,000 chunk rows per round across several rounds; it
now reads one window of rows.

**Latency.** Indicative only: every timed run shared the machine with
the test suite.
- Hybrid on Postgres was 414–668 ms on this branch, against 429–1,264 ms
on main.
- Vector-only on Postgres was 665–1,517 ms on this branch, against
419–994 ms on main.

One plan change to watch: the HNSW path (more than 50,000 admitted
chunks, or no filters) now reads up to 10 chunks per requested row,
1,000 at the default 100 rows, where main read 100 chunks per round. I
could not exercise it at that size locally.

## Tests

- New: `test_search_rows_collapses_chunks_to_their_nearest_rows` (real
sqlite-vec), pgvector unit tests for the exact and HNSW plans, a reader
trace test for row matches, and the traffic test on both backends.
- Updated: tests that pinned the old chunk window
(`test_a_built_in_index_reads_its_row_window_once` replaces the
long-notes widening test).
- Verification:
  - `just fast-check` clean.
  - `just fast-test`: 6,881 passed.
- `tests/repository` plus the traffic test pass on SQLite; the traffic
test passes on Postgres.
  - All four changed modules: every line this change adds is covered.

## Not in this PR

- Deferring candidate row fields (title, metadata) to the returned page.
- Trimming `content` for vector-matched rows (a response change).
- RRF or other ranking changes.
- Milvus.

Refs #1746

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01CMYVL4TcbWdXhdvAzxfqjo

---------

Signed-off-by: phernandez <paul@basicmachines.co>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant