Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
Back to tool/Back to issues
#7544·surrealdb

HNSW: a KNN query returns wrong neighbours and leave the index permanently broken

Author: adoublebCreated Sep 27, 2026Updated Sep 28, 2026
Labelstriage

What component does this affect?

SurrealDB Server

Describe the bug

Related to #7542 and #7543, but a different bug. Both of those are transient windows while an index is first being built: #7542 during DEFINE INDEX ... CONCURRENTLY (KNN returns the whole table or nothing until ready), #7543 after a bulk load (the index reports ready while the graph is still being built; KNN is slow and short until it finishes, fixed on 3.4.0-nightly+20260925.f2541a0). This one happens on an index that is already built and verified correct, under ordinary writes, only when a KNN read overlaps a compaction apply. It returns wrong rows as well as missing ones and can leave the index permanently wrong. It still reproduces on that same nightly.

HNSW index writes are deferred: they are queued as pending entries and folded into the graph by the periodic index-compaction task (index_compaction_interval, default 5 s). If a <|k, ef|> KNN query runs while a compaction batch is being applied to the same index, it returns wrongly. It returns fewer than k (down to []), or rows that are not the nearest. A plain scan over the same table returns the right answer. There is no error raised.

The issue persists after the query. After the writes stop and every pending entry has been compacted, the index sometimes stays permanently wrong: it returns [] or two far-away rows for k=2 while both true neighbours are alive and a scan returns them. This is observed in a small sample of runs, 1 of 4 KNN-reader runs on 3.4.0-nightly, 1 of 6 on 3.3.0 and 4 of 9 on 3.2.4.

Steps to reproduce

Two anchor rows are the true top-2 for a fixed target and are never touched. A writer keeps the compaction backlog large (200 far rows created and then deleted per batch, every one > 40 units from the target), so each apply takes long enough to overlap a read. Readers issue the same KNN query in a loop.

surql
DEFINE INDEX ix ON TABLE v FIELDS f1 HNSW DIMENSION 3;
CREATE v:a1 SET f1 = [4.472, -3.344, 5.459];   -- distance 3.6534 to the target
CREATE v:a2 SET f1 = [1.999, -0.343, 8.25];    -- distance 3.8972
-- wait > 5 s so the anchors are compacted

-- writer, looping: CREATE v:f0 .. v:f199 at far-away vectors, then DELETE them
-- readers, looping concurrently:
RETURN array::sort((SELECT VALUE vector::distance::euclidean(f1, [5.621, -1.752, 8.54])
                    FROM v WHERE f1 <|2,40|> [5.621, -1.752, 8.54]));
-- expected every time: [3.6533855531547714, 3.8972124653398104]

Runnable script (Python 3 standard library only). Start a server, then run the script:

bash
docker run --rm -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass root memory
python3 f11_repro.py                 # 3 arms x 120 s, 4 readers
python3 f11_repro.py --secs 60 --arms knn-reader
f11_repro.py
python
"""Standalone repro: a KNN read overlapping HNSW compaction corrupts the index.

Python 3 standard library only. Start a server first:

    docker run --rm -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass root memory

then run `python3 f11_repro.py` (optionally `--secs 60 --readers 1`).
"""

import argparse
import base64
import json
import math
import random
import threading
import time
import urllib.request

URL = "http://127.0.0.1:8000/sql"
AUTH = "Basic " + base64.b64encode(b"root:root").decode()

TARGET = [5.621, -1.752, 8.54]
A1 = [4.472, -3.344, 5.459]  # distance 3.6534 -- true nearest
A2 = [1.999, -0.343, 8.25]  # distance 3.8972 -- true second nearest
BATCH = 200


def sql(db, text):
    req = urllib.request.Request(
        URL,
        data=f"USE NS f11 DB {db};\n{text}".encode(),
        headers={"Accept": "application/json", "Authorization": AUTH},
    )
    with urllib.request.urlopen(req, timeout=60) as resp:
        results = json.load(resp)[1:]  # drop the USE result
    for r in results:
        if r["status"] != "OK":
            raise RuntimeError(r["result"])
    return [r["result"] for r in results]


def dist(v):
    return math.sqrt(sum((a - b) ** 2 for a, b in zip(v, TARGET)))


EXPECTED = sorted([dist(A1), dist(A2)])
DISTANCE = f"vector::distance::euclidean(f1, {TARGET})"
KNN = f"RETURN array::sort((SELECT VALUE {DISTANCE} FROM v WHERE f1 <|2,40|> {TARGET}));"
SCAN = f"RETURN array::slice(array::sort((SELECT VALUE {DISTANCE} FROM v WHERE f1 != NONE)), 0, 2);"


def far_vector(rng):
    while True:  # > 40 units from the target, so the anchors stay the true top-2
        v = [round(rng.uniform(-60, 60), 3) for _ in range(3)]
        if dist(v) > 40:
            return v


def ok(got):
    return len(got) == 2 and all(abs(a - b) < 1e-9 for a, b in zip(got, EXPECTED))


def run_arm(arm, secs, readers):
    db = arm.replace("-", "_")
    sql(db, f"DEFINE INDEX ix ON TABLE v FIELDS f1 HNSW DIMENSION 3; CREATE v:a1 SET f1 = {A1}; CREATE v:a2 SET f1 = {A2};")
    time.sleep(6)  # let the anchors compact into the graph
    assert ok(sql(db, KNN)[0]), "baseline KNN already wrong"

    stop, lock = threading.Event(), threading.Lock()
    stats = {"reads": 0, "wrong": 0, "writes": 0}

    def writer():
        rng, i = random.Random(7), 0
        while not stop.is_set():
            try:  # the compaction task can make a batch hit a retryable write conflict
                sql(db, "; ".join(f"CREATE v:f{i + j} SET f1 = {far_vector(rng)}" for j in range(BATCH)) + ";")
                sql(db, "; ".join(f"DELETE v:f{i + j}" for j in range(BATCH)) + ";")
                with lock:
                    stats["writes"] += 2 * BATCH
            except RuntimeError:
                pass
            i += BATCH

    def reader(query):
        while not stop.is_set():
            got = sql(db, query)[0]
            with lock:
                stats["reads"] += 1
                stats["wrong"] += not ok(got)

    threads = [threading.Thread(target=writer, daemon=True)]
    query = {"scan-reader": SCAN, "knn-reader": KNN}.get(arm)
    if query:
        threads += [threading.Thread(target=reader, args=(query,), daemon=True) for _ in range(readers)]
    for t in threads:
        t.start()
    time.sleep(secs)
    stop.set()
    for t in threads:
        t.join(timeout=30)

    time.sleep(7)  # let the final backlog compact, then judge the resting state
    knn, scan = sql(db, KNN)[0], sql(db, SCAN)[0]
    verdict = "index intact" if ok(knn) else "INDEX BROKEN"
    print(f"{arm:12s} writes={stats['writes']:>6} reads={stats['reads']:>5} wrong={stats['wrong']:>5}"
          f" | after churn: knn={knn} scan={scan} -> {verdict}", flush=True)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--secs", type=float, default=120)
    ap.add_argument("--readers", type=int, default=4)
    ap.add_argument("--arms", nargs="+", default=["writer-only", "scan-reader", "knn-reader"])
    a = ap.parse_args()
    for arm in a.arms:
        run_arm(arm, a.secs, a.readers)

Output on 3.3.0 (4 readers). Each line starts from an empty database:

writer-only  writes=835200 reads=    0 wrong=    0 | index intact
scan-reader  writes=474400 reads=13757 wrong=    0 | index intact
knn-reader   reads= 6842 wrong=   57 | index intact
knn-reader   reads=12145 wrong=    0 | index intact
knn-reader   reads= 6350 wrong=    2 | index intact
knn-reader   reads= 5967 wrong=   29 | index intact
knn-reader   reads= 6006 wrong=   31 | index intact
knn-reader   reads= 6444 wrong= 5856 | after churn: knn=[46.83106996428759, 49.910566396305306] scan=[3.6533855531547714, 3.8972124653398104] -> INDEX BROKEN

Output on 3.4.0-nightly+20260925.f2541a0 (4 readers, 60 s, a fresh server for each line):

knn-reader   reads= 6820 wrong= 6255 | after churn: knn=[40.17641558178131, 43.5338606833807] scan=[3.6533855531547714, 3.8972124653398104] -> INDEX BROKEN
knn-reader   reads= 5742 wrong=  434 | index intact
knn-reader   reads= 5664 wrong=   51 | index intact
knn-reader   reads= 5758 wrong=   34 | index intact

Once the index breaks, every later read is wrong, which is why the count jumps by orders of magnitude between otherwise identical runs.

Wrong answers seen on 3.2.4 during churn, and after it:

[]                                              -- k=2, both anchors alive
[40.09771057055502, 40.43042411353114]          -- two far rows; anchors missing

-- 7 s after the churn stopped (all pending entries compacted):
KNN : []
SCAN: [3.6533855531547714, 3.8972124653398104]

3.2.4 totals, same write load in every arm, varying only the concurrent reader: writer-only and scan-reader, 4 runs, 0 wrong answers, index intact every time. KNN reader, 9 runs (1 or 4 readers, 60 or 120 s, k = 1 or 2, insert + delete or insert-only churn): wrong answers in every run (1 to 7,744), and the index permanently broken in 4 of them. Repeat the script rather than judging by one execution.

Expected behaviour

A KNN query returns the true nearest neighbours of committed rows (here, always the two anchors), whether or not an index compaction is running at the same time. A read should never change the shared index state, and the index should always converge to the committed data once compaction finishes.

SurrealDB version

3.3.0 for linux on aarch64 (Docker surrealdb/surrealdb:latest, memory backend). Also reproduced on 3.4.0-nightly+20260925.f2541a0 (aarch64) and 3.2.4+20260803.93ab219 (arm64 and amd64).

Contact Details

[email protected]

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

View original on GitHubView discussion on GitHub