HNSW: a KNN query during DEFINE INDEX ... CONCURRENTLY returns the whole table (3.2.4) or no rows (nightly), with no error
What component does this affect?
SurrealDB Server
Describe the bug
While DEFINE INDEX ... HNSW ... CONCURRENTLY is building (status cleaning, then indexing), a KNN query on that field returns a wrong result with no error: on 3.2.4 it returns every row in the table (50,000 rows for <|10,100|>), and on the 3.4.0 nightly it returns no rows. Once the status reaches ready the same query returns its 10 nearest rows. INFO FOR INDEX is truthful here (it says indexing and counts up), but nothing tells the query that the index is not usable yet.
Trace, one line per query, 50,000 random unit vectors of dimension 64 loaded into a table with no index, then DEFINE INDEX pe ON product FIELDS embedding HNSW DIMENSION 64 DIST EUCLIDEAN CONCURRENTLY, then SELECT id FROM product WHERE embedding <|10,100|> [...] back to back:
3.2.4+20260803.93ab219 (all 8 queries during the build returned the whole table):
t= 0.58 s rows 50000/10 581.5 ms {"building":{"status":"cleaning"}}
t= 1.08 s rows 50000/10 495.7 ms {"building":{"initial":6766,"pending":0,"status":"indexing"}}
t= 2.22 s rows 50000/10 526.8 ms {"building":{"initial":19266,"pending":0,"status":"indexing"}}
t= 4.38 s rows 50000/10 509.0 ms {"building":{"initial":45016,"pending":0,"status":"indexing"}}
t= 9.97 s rows 10/10 5587.9 ms {"building":{"initial":50000,"pending":0,"status":"ready","updated":0}}3.4.0-nightly+20260925.f2541a0 (all 11 queries during the build returned nothing):
t= 0.48 s rows 0/10 479.4 ms {"building":{"compacting":false,"status":"cleaning"}}
t= 0.85 s rows 0/10 364.8 ms {"building":{"compacting":true,"initial":5016,"pending":0,"status":"indexing"}}
t= 3.40 s rows 0/10 411.0 ms {"building":{"compacting":true,"initial":35016,"pending":0,"status":"indexing"}}
t= 5.46 s rows 0/10 1221.4 ms {"building":{"compacting":true,"initial":49766,"pending":0,"status":"indexing"}}
t= 5.73 s rows 10/10 259.0 ms {"building":{"compacting":true,"initial":50000,"pending":0,"status":"ready","updated":0}}Totals over the 40 s trace: 3.2.4 {10: 10, 50000: 8} queries by rows returned, nightly {0: 11, 10: 324}. On 3.3.0-beta.3+20260819.6dce5c8 a query during cleaning also returned 0 rows. At 50,000 rows the window is about 5 seconds; it is the build time, so it grows with the table.
The 3.2.4 trace after ready also shows #7543 (KNN at 3 to 5.6 s while the graph is still being built in the background).
Steps to reproduce
docker run -d --name hnsw-trace -p 127.0.0.1:8000:8000 --cpus 4 surrealdb/surrealdb:v3.2.4 start --user root --pass root rocksdb:/tmp/db(orsurrealdb/surrealdb:nightly)python3 concurrent_trace.py 50000 64 40(Python 3 standard library only, below). It signs in, loads the vectors in 1,000-row batches with no index, runsDEFINE INDEX ... CONCURRENTLY, then for 40 s printsINFO FOR INDEX, the number of rows, and the latency of each KNN query.
"""KNN answers while DEFINE INDEX ... CONCURRENTLY builds an HNSW index, one line per query.
Standard library only; talks to a running `surreal start` over HTTP /sql.
Usage: python3 concurrent_trace.py [N] [DIM] [SECONDS]
Loads N vectors into a table with no index, runs DEFINE INDEX ... CONCURRENTLY,
then queries back to back for SECONDS, printing the index status beside each
query's row count (K = 10) and latency.
"""
import json
import os
import random
import sys
import time
import urllib.request
URL = os.environ.get("SURREAL_URL", "http://127.0.0.1:8000")
N = int(sys.argv[1]) if len(sys.argv) > 1 else 50_000
DIM = int(sys.argv[2]) if len(sys.argv) > 2 else 64
SECONDS = float(sys.argv[3]) if len(sys.argv) > 3 else 40
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()
def sql(text, scoped=True):
headers = {"Authorization": AUTH, "Accept": "application/json"}
if scoped:
headers.update({"Surreal-NS": "repro", "Surreal-DB": "trace"})
req = urllib.request.Request(URL + "/sql", data=text.encode(), method="POST", headers=headers)
with urllib.request.urlopen(req, timeout=3600) 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]
sql("DEFINE NAMESPACE IF NOT EXISTS repro; USE NS repro; DEFINE DATABASE IF NOT EXISTS trace",
scoped=False)
sql("REMOVE TABLE IF EXISTS product; DEFINE TABLE product SCHEMALESS")
for s in range(0, N, 1_000):
sql("INSERT INTO product " + json.dumps(
[{"id": i, "embedding": unit(DIM)} for i in range(s, min(s + 1_000, N))]))
print(f"loaded {N} x {DIM}", flush=True)
queries = [unit(DIM) for _ in range(50)]
sql(f"DEFINE INDEX pe ON product FIELDS embedding HNSW DIMENSION {DIM} DIST EUCLIDEAN CONCURRENTLY")
t0, j, counts = time.perf_counter(), 0, {}
while time.perf_counter() - t0 < SECONDS:
status = json.dumps(sql("INFO FOR INDEX pe ON product"), separators=(",", ":"))
q = queries[j % len(queries)]
t = time.perf_counter()
rows = sql(f"SELECT id FROM product WHERE embedding <|10,100|> {json.dumps(q)}")
ms = (time.perf_counter() - t) * 1000
print(f"t={time.perf_counter() - t0:6.2f} s rows {len(rows):2d}/10 {ms:8.1f} ms {status}",
flush=True)
counts[len(rows)] = counts.get(len(rows), 0) + 1
j += 1
print(f"queries by rows returned: {dict(sorted(counts.items()))}", flush=True)Expected behaviour
A KNN query issued while its index is still being built either returns the K nearest rows or fails with an error saying the index is not ready. It should not return the whole table or an empty result.
SurrealDB version
3.2.4+20260803.93ab219 for linux on x86_64 (Docker surrealdb/surrealdb:v3.2.4); also 3.4.0-nightly+20260925.f2541a0 (0 rows) and 3.3.0-beta.3+20260819.6dce5c8 (0 rows seen during cleaning).
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