From: Manuelreyesbravo (@Manuelreyesbravo) <noreply+Manuelreyesbravo@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: Re: [pgvector/pgvector] PR #1020: Prefetch unvisited neighbors during HNSW search
Date: Fri, 25 Sep 2026 21:22:47 +0000
Message-ID: <gh-pgvector-pgvector-1020-c5839817611@github.com> (raw)
In-Reply-To: <gh-pgvector-pgvector-1020@github.com>
References: <gh-pgvector-pgvector-1020@github.com>
Thanks for taking the time to test this. First, a correction to my earlier comment: I said `read_stream_resume()` restores the saved distance, so the ramp-up happens once per stream. That was wrong, sorry for the confusion. The distance is only saved by `read_stream_pause()`; when the callback returns `InvalidBlockNumber`, read_stream.c sets it to 0 without saving it (the same in 19beta2), so every hop starts again from the initial distance: 16 with `READ_STREAM_FULL`, 1 without. That is also why `READ_STREAM_FULL` helped so much.
I checked it with a build that logs the distance: on one query (49 hops) the distance grew to 32-90 within each hop, and `resume` restored 16 on all 49. With `read_stream_pause()` it restored the grown value.
That is one of two limits behind the gap:
1. The distance restarts at 16 on every hop, and a hop at layer 0 has ~28 unvisited neighbors, so the reads past the 16th start later.
2. The stream never has more than `effective_io_concurrency` (16) reads in flight.
Fixing either one alone barely helps; fixing both closes most of the gap: `return read_stream_pause(stream);` instead of `return InvalidBlockNumber;` in `HnswReadStreamNextBlock`, plus `effective_io_concurrency = 64`.
PG 19beta4 (-O2), 500k random vectors of 1536 dimensions, default HNSW parameters, 100 queries after a cold start, io_uring, median of 9-14 runs (master 5; runs disturbed by other load on the machine dropped). First column on a local NVMe, second with 1 ms added to every read (dm-delay):
| | local NVMe | +1 ms per read |
|---|---|---|
| master | 6.21 s | 69.8 s |
| `READ_STREAM_USE_BATCHING` | 2.46 s | 22.5 s |
| `READ_STREAM_FULL` | 1.47 s | 10.5 s |
| `FULL` + eic 64 | 1.47 s | 10.5 s |
| `FULL` + pause | 1.41 s | 10.1 s |
| `FULL` + pause + eic 64 | 1.39 s | 7.2 s |
| PrefetchBuffer (this PR) | 1.19 s | 6.8 s |
On the fast disk the fix closes less of the gap, since the per-I/O cost of the stream matters more there. With `io_method = worker` the `FULL` stream took 2.18 s / 13.7 s; PrefetchBuffer took 1.24 s / 6.8 s, and on PG 18.6 6.8 s at +1 ms (master 68.4 s).
Separately, I tried also prefetching the unvisited neighbors of the next two candidates while the current hop's reads are in flight, so hops overlap: 1.06 s / 5.5 s, for 9% more reads, and the same on PG 18. It works with either approach, so I've kept it out of this PR; happy to open it separately if it seems worth it.
Caveats: random vectors, one machine, default `m` and `ef_search`. I can share the scripts if useful.