Skip to content

perf(core): run hybrid legs concurrently and read one vector window - #2062

Merged
phernandez merged 1 commit into
mainfrom
perf/hybrid-concurrent-legs
Nov 5, 2026
Merged

phernandez merged 1 commit into
mainfrom
perf/hybrid-concurrent-legs

Conversation

@phernandez

Copy link
Copy Markdown
Member

Problem

Production hybrid search, 10-29..11-05: p50 2.25s, p95 15.8s, p99 25.8s over 19.3k requests. Vector queries were the largest share of tenant search timeouts.

Two costs in SemanticSearch.hybrid:

  1. Sequential legs. The full-text query ran first, then the query embedding and vector query. A request waited for the sum of both.
  2. Double expansion. With reranking off (the default), the vector leg called _candidate_limit on a value _candidate_limit had already produced: max(vector_k, (limit + offset) * 10), then times ten again. A default 10-row page read 1,000 chunks. Production candidate_limit had a p50 of about 1,000 and a max of 60,100; vector p95 was 7.5s at 200 or fewer candidates and 15.3s above 10k.

Fix

  • Both legs run in an asyncio.TaskGroup on separate sessions. If one fails, the other is cancelled and awaited, and the first failure is re-raised bare (the pattern _search_with_exact_count already uses), so callers see the same exception types.
  • The vector leg reads the same candidate_limit as full-text. That window already carries the 10x chunk fan-out for notes that collapse into one row. Filtered queries still widen through _candidate_window until they admit row_target rows.

Quality

test_semantic_quality.py, FastEmbed, run on this branch and on main at the same time:

combo suite hit@1 R@5 MRR@10 avg ms main → branch
sqlite-fastembed lexical 0.625 0.625 0.664 52.9 → 25.6
sqlite-fastembed paraphrase 0.875 0.875 0.893 31.2 → 29.5
postgres-fastembed lexical 1.000 1.000 1.000 179.1 → 152.0
postgres-fastembed paraphrase 1.000 1.000 1.000 182.1 → 157.6

Quality is identical on every row. The benchmark corpus is small, so 100 and 1,000 chunks both reach every note in it. This shows no regression; it does not measure recall on a project with hundreds of thousands of chunks. The two runs shared the machine, so the latency column is indicative only.

Tests

  • test_hybrid_search_preserves_candidate_windows and test_postgres_hybrid_preserves_candidate_windows pinned the old 1,000-chunk window; they now assert 100. The reranked cases are unchanged.
  • The 32 test files that exercise hybrid and semantic search: 778 passed, 41 skipped on SQLite before the two test updates; the two updated tests and the rest of their files pass on Postgres.

Not in this PR: the Postgres FTS chunk MAX(ts_rank) cost and the exact COUNT(*) on FTS searches. Both change ranking or the total contract and need a decision first.

🤖 Generated with Claude Code

https://claude.ai/code/session_01CMYVL4TcbWdXhdvAzxfqjo

Hybrid search ran the full-text query, then embedded the query and ran the
vector query, so a request waited for the sum of both. The legs share
nothing, so they now run together in a TaskGroup on separate sessions; the
first failure is re-raised bare, as the search router already does for its
page and count.

With reranking off, the vector leg also expanded the candidate window a
second time: (limit + offset) * 10 chunks, times ten again. A default
10-row page read 1,000 chunks, and production vector candidate_limit
reached 60,100. Both legs now read the one window, 100 chunks for that
page. The quality benchmark scores hybrid identically to main on SQLite and
Postgres with FastEmbed.

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

chatgpt-codex-connector Bot commented Nov 5, 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-11-05T14:36:36.702137Z 7146f8e PR opened
ℹ️ 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 merged commit 6088fc2 into main Nov 5, 2026
75 of 86 checks passed
@phernandez
phernandez deleted the perf/hybrid-concurrent-legs branch November 5, 2026 20:35
geroldk added a commit to geroldk/merkwerk that referenced this pull request Nov 7, 2026
Upstream 0045_drop_frontmatter_btree_indexes collides with the BM-006
revisions 0044-0046; it is carried as 0048 after 0047. The parallel hybrid
search legs (basicmachines-co#2062) keep the local BM-002 relaxed-FTS detection; the
SQLite FTS count() stays because the local BM-002 ranking tests use it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P763KtSpLErK8vBE3MeTfY
Signed-off-by: Gerold <gkuehne@gmail.com>
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