HNSW: INFO FOR INDEX reports ready for minutes while the graph is still being built, and KNN meanwhile returns fewer than K rows (3.2.4, 3.3.0-beta.3; fixed on nightly)
What component does this affect?
SurrealDB Server
Describe the bug
After a bulk insert into a table that already has an HNSW index, INFO FOR INDEX immediately reports {"status":"ready","pending":0}, but the server keeps building the graph in the background (one core busy) for minutes. During that window a KNN query runs at brute-force speed and some <|10,100|> queries return 8 or 9 rows instead of 10. DEFINE INDEX ... CONCURRENTLY on a loaded table does the same: it reports ready minutes before KNN is fast and complete. A blocking DEFINE INDEX on the loaded table is fine.
So on the current stable release a client cannot tell when an HNSW index is usable, and queries in that window silently return incomplete results.
On 3.4.0-nightly+20260925.f2541a0 this is fixed: the build appears to happen inline, answers are complete from the first read, and a compacting flag stays true until the work is done. I am filing it because 3.2.4 and 3.3.0-beta.3 still have it, to ask whether the fix will ship in 3.3.0 and reach 3.2.x. The public main here ends on 2026-09-04, so I could not find the change to reference.
Setup: RocksDB, one server limited to 4 CPUs, 50,000 random unit vectors of dimension 64, HNSW DIMENSION 64 DIST EUCLIDEAN, inserted in 1,000-row batches, queried over HTTP with a session token. Each row is the median of 12 KNN queries and the fewest rows any of them returned for K = 10, read every ~10 s (a read takes longer while queries are slow).
| build | index defined first, then INSERT | INSERT, then DEFINE INDEX ... CONCURRENTLY |
INSERT, then blocking DEFINE INDEX |
|---|---|---|---|
| 3.2.4+20260803.93ab219 | ready from the first read; 3,541 ms (8 rows), 4,931 ms (9), 2,697 ms (9), then 16 ms (10) from ~200 s |
cleaning, then ready by 90 s; 4,476 ms (10), 7,534 ms (9), 5,751 ms (9), then 15 ms (10) from ~280 s |
returns after 219 s; 21 ms (10) |
| 3.3.0-beta.3+20260819.6dce5c8 | ready from the first read; 11,566 ms (9), 12,884 ms (9), 13,967 ms (9), 7,038 ms (10), then 16 ms (9, then 10) from ~615 s |
cleaning, then ready; 11,725 ms (9), 13,095 ms (8), ... |
not run |
| 3.4.0-nightly+20260925.f2541a0 | ready with compacting: true; 40 ms (10), 26 ms (10), 17 ms (10), then 11 ms (10) with compacting: false at 33 s |
see #7542 (during the build); ready with compacting: true, 57 ms (10) falling to 10 ms (10) at 70 s |
returns after 64 s; 15 ms (10) |
With the index defined first on 3.2.4 the server sat at 100 to 118% CPU from the end of the load until the latency dropped, then went idle, while INFO FOR INDEX said ready throughout.
We hit this in a benchmark that pins the latest stable release: the served SurrealDB arm was timing queries during the background build (1.5 s per query at 1M vectors). Our workaround is to poll a KNN query after the load until its latency stops falling.
Possibly related: #7541 (a DiskANN rebuild reports ready while KNN is ~270x slower; private data).
Steps to reproduce
docker run -d --name hnsw-repro -p 127.0.0.1:8000:8000 --cpus 4 surrealdb/surrealdb:v3.2.4 start --user root --pass root rocksdb:/tmp/dbpython3 repro.py before(Python 3 standard library only, below).python3 repro.py concurrentandpython3 repro.py afterrun the other two orders; use a fresh server for each.
The script signs in, defines the namespace, database, table, and index, inserts 50,000 vectors, then every ~10 s prints INFO FOR INDEX beside the median latency of 12 KNN queries and the fewest rows any of them returned, until the latency has been flat for three reads.
"""SurrealDB HNSW: INFO FOR INDEX says "ready" while KNN still runs at brute-force speed.
Standard library only; talks to a running `surreal start` over HTTP /sql.
Usage: python3 repro.py <mode> [N] [DIM]
before DEFINE INDEX on the empty table, then bulk INSERT (the usual order)
after bulk INSERT, then a blocking DEFINE INDEX
concurrent bulk INSERT, then DEFINE INDEX ... CONCURRENTLY
After the load (and the DEFINE), it prints INFO FOR INDEX and the KNN latency
every 10 s until the latency has been flat for 3 rounds, or 15 minutes pass.
"""
import json
import os
import random
import statistics
import sys
import time
import urllib.request
URL = os.environ.get("SURREAL_URL", "http://127.0.0.1:8000")
# Sign in once and send the session token: HTTP Basic auth re-verifies the
# password hash on every request, which alone costs ~70-90 ms per query here.
def _signin():
req = urllib.request.Request(
URL + "/signin", data=json.dumps({"user": "root", "pass": "root"}).encode(),
method="POST", headers={"Accept": "application/json", "Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=60) as r:
return "Bearer " + json.loads(r.read())["token"]
AUTH = _signin()
MODE = sys.argv[1]
N = int(sys.argv[2]) if len(sys.argv) > 2 else 50_000
DIM = int(sys.argv[3]) if len(sys.argv) > 3 else 64
BATCH = 1_000 # the HTTP /sql endpoint refuses a ~3 MB body (413)
DDL = f"DEFINE INDEX pe ON product FIELDS embedding HNSW DIMENSION {DIM} DIST EUCLIDEAN"
def sql(text, timeout=3600, scoped=True):
headers = {"Authorization": AUTH, "Accept": "application/json"}
if scoped:
headers.update({"Surreal-NS": "repro", "Surreal-DB": MODE})
req = urllib.request.Request(URL + "/sql", data=text.encode(), method="POST", headers=headers)
with urllib.request.urlopen(req, timeout=timeout) as r:
out = json.loads(r.read())
for stmt in out:
if stmt.get("status") != "OK":
raise RuntimeError(str(stmt.get("result"))[:300])
return out[-1]["result"]
rnd = random.Random(20260721)
def unit(d):
v = [rnd.gauss(0, 1) for _ in range(d)]
n = sum(x * x for x in v) ** 0.5
return [round(x / n, 6) for x in v]
queries = [unit(DIM) for _ in range(12)]
def knn_ms():
"""Median latency of 12 KNN queries (k=10), and the fewest rows any returned."""
lat, fewest = [], 10
for q in queries:
t = time.perf_counter()
rows = sql(f"SELECT id FROM product WHERE embedding <|10,100|> {json.dumps(q)}")
lat.append((time.perf_counter() - t) * 1000)
fewest = min(fewest, len(rows))
return statistics.median(lat[2:]), fewest
def info():
return json.dumps(sql("INFO FOR INDEX pe ON product"), separators=(",", ":"))
print(f"mode={MODE} N={N} DIM={DIM} server={URL}", flush=True)
sql(f"DEFINE NAMESPACE IF NOT EXISTS repro; USE NS repro; DEFINE DATABASE IF NOT EXISTS {MODE}",
scoped=False)
sql("REMOVE TABLE IF EXISTS product; DEFINE TABLE product SCHEMALESS")
if MODE == "before":
sql(DDL)
t0 = time.perf_counter()
for s in range(0, N, BATCH):
rows = [{"id": i, "embedding": unit(DIM)} for i in range(s, min(s + BATCH, N))]
sql("INSERT INTO product " + json.dumps(rows))
print(f"load {time.perf_counter() - t0:.1f} s", flush=True)
if MODE in ("after", "concurrent"):
t1 = time.perf_counter()
try:
sql(DDL + (" CONCURRENTLY" if MODE == "concurrent" else ""))
print(f"DEFINE INDEX returned after {time.perf_counter() - t1:.1f} s", flush=True)
except Exception as exc:
print(f"DEFINE INDEX FAILED after {time.perf_counter() - t1:.1f} s: {exc}", flush=True)
sys.exit(1)
start, history = time.perf_counter(), []
while time.perf_counter() - start < 900:
status = info()
ms, fewest = knn_ms()
history.append(ms)
print(f"t={time.perf_counter() - start:6.1f} s KNN p50 {ms:9.1f} ms fewest rows {fewest:2d}/10 "
f"INFO FOR INDEX {status}", flush=True)
last = history[-3:]
if len(last) == 3 and max(last) <= 1.5 * min(last) and (last[-1] < 0.1 * history[0] or history[0] < 500):
break
time.sleep(10)
print(f"settled at {history[-1]:.1f} ms; first read after the load was {history[0]:.1f} ms",
flush=True)Expected behaviour
INFO FOR INDEX reports an HNSW index as still building until KNN is served by the finished graph, and KNN queries never return fewer than K rows when the table holds at least K records, as on the nightly build. I would like to know whether that behaviour will be in 3.3.0 and backported to 3.2.x.
SurrealDB version
3.2.4+20260803.93ab219 for linux on x86_64 (Docker surrealdb/surrealdb:v3.2.4); also 3.3.0-beta.3+20260819.6dce5c8. Fixed on 3.4.0-nightly+20260925.f2541a0.
Contact Details
No response
Could this be a bug with your application?
- I confirm this is a bug with SurrealDB, not with my own application
Is there an existing issue for this?
- I confirm that I have searched the existing issues
Code of Conduct
- I agree to follow this project's Code of Conduct
Source: surrealdb/surrealdb