#7550·surrealdb

Bug: `DEFINE INDEX … CONCURRENTLY` can permanently miss writes committed while the build starts (first build only; `REBUILD INDEX … CONCURRENTLY` does not have this window)

Author: omer9564Created Sep 29, 2026Updated Sep 29, 2026

What component does this affect?

SurrealDB Server

Describe the bug

DEFINE INDEX … CONCURRENTLY starts the background build before the statement's own transaction has committed the index definition. Until that transaction commits, other transactions do not see the index. A write in that interval does not update the index and is not queued for the builder. If the builder has already scanned that row, the finished index keeps an entry for the row's old value (stale entry) and has no entry for its new value (lost entry).

INFO FOR INDEX then reports status: 'ready' with updated: 0, and no error is reported.

Later writes do not fully repair the damage. After a bad build (50,000 rows, t:1..t:100 lost), we sent each of these UPDATEs as its own auto-commit request and then queried t:1..t:3. The results were the same in 5 of 5 runs on 3.2.4:

surql
UPDATE t:1 SET x = 'third';
UPDATE t:2 SET x = 'new';     -- the value t:2 already has
UPDATE t:3 SET x = 'old';
UPDATE t:3 SET x = 'fourth';

SELECT VALUE record::id(id) FROM t WHERE x = 'third';                                    -- [1]
SELECT id, x FROM t WHERE x = 'old' AND record::id(id) <= 3;                             -- t:1 with x: 'third', t:2 with x: 'new'
SELECT VALUE record::id(id) FROM t WHERE x = 'new' AND record::id(id) <= 3;              -- []   (WITH NOINDEX: [2])
SELECT VALUE record::id(id) FROM t WHERE x = 'fourth';                                   -- [3]
  • t:1: the 'third' entry is added, but the stale 'old' entry stays.
  • t:2: writing 'new' again adds nothing. t:2 is still missing under 'new' and still stale under 'old'.
  • t:3: set to 'old' and then to 'fourth', it came out correct.

A REBUILD INDEX … CONCURRENTLY run the same way, with the same transaction and the same writes at the same times, loses nothing. Its definition is already visible to writers, so a write during the scan is queued (updated: 50) and replayed. A REBUILD after the bad build also makes the index exact again.

In the repro, BEGIN … SLEEP 3s … COMMIT only holds the window open, so the race is deterministic. The repro is itself a DEFINE INDEX … CONCURRENTLY followed by another statement (SLEEP) in the same transaction.

We have not reproduced the plain auto-commit case (DEFINE INDEX … CONCURRENTLY; on its own). From reading the code, we infer that it has the same window, between the start of the build and the commit of the statement's transaction. At v3.2.4 the statement does all of this inside its own transaction (expr/statements/define/index.rs L214–L237): it writes the definition, calls register_uncommitted_index_build_cleanup (L219–L227), and then starts the build.

A separate issue covers stale entries left by concurrent writers during DEFINE/REBUILD INDEX … CONCURRENTLY; it is not part of this report.

After the build, some queries return wrong results (50,000 rows, t:1..t:100 updated inside the window):

Query Result Correct result
SELECT VALUE record::id(id) FROM t WHERE x = 'new' (plan: IndexScan on ix) [] 100 ids (as returned by WITH NOINDEX)
SELECT count() FROM t WHERE x = 'old' GROUP ALL 50000 49900 (as returned by WITH NOINDEX)
SELECT id, x FROM t WHERE x = 'old' AND record::id(id) <= 3 t:1, t:2, t:3, all with x: 'new' []

A plain SELECT VALUE record::id(id) FROM t WHERE x = 'old' LIMIT 3 returned [101, 102, 103], so it did not return the updated rows.

Relevant code at v3.2.4. We have not confirmed this diagnosis; it comes from reading the code.

Steps to reproduce

Two connections to surreal start --user root --pass root memory.

Connection A, seed the table:

surql
DEFINE TABLE t SCHEMALESS;
FOR $i IN 1..=50000 { CREATE type::record('t', $i) SET x = 'old' RETURN NONE; };

Connection A, then send this whole block as a single request (for example one HTTP POST /sql, as the script below does), so that the transaction stays open during SLEEP:

surql
BEGIN;
DEFINE INDEX ix ON t FIELDS x CONCURRENTLY;
SLEEP 3s;   -- only holds the window open
COMMIT;

Connection B, while A's request is still open. The UPDATE must commit after the build's initial scan has passed t:1..t:100 and before A's COMMIT. With 50,000 rows, an UPDATE sent 0.8 s after A's request (the script's second write) was lost in every run:

surql
UPDATE t:1..=100 SET x = 'new' RETURN NONE;   -- own auto-commit transaction; returns OK
INFO FOR INDEX ix ON t;                        -- ERR: The index 'ix' does not exist

After A commits and INFO FOR INDEX ix ON t reports status: 'ready':

surql
SELECT VALUE record::id(id) FROM t WHERE x = 'new';               -- []                   expected: [1, …, 100]
SELECT VALUE record::id(id) FROM t WITH NOINDEX WHERE x = 'new';  -- [1, …, 100]
SELECT count() FROM t WHERE x = 'old' GROUP ALL;                  -- [{ count: 50000 }]   expected: 49900
SELECT count() FROM t WITH NOINDEX WHERE x = 'old' GROUP ALL;     -- [{ count: 49900 }]
SELECT id, x FROM t WHERE x = 'old' AND record::id(id) <= 3;      -- t:1..t:3, each with x: 'new'
INFO FOR INDEX ix ON t;  -- { building: { initial: 50000, pending: 0, status: 'ready', updated: 0 } }

REBUILD INDEX ix ON t CONCURRENTLY;  -- once ready, every query above is exact

Expected: the index contains t:1..t:100 under 'new' and not under 'old', as WITH NOINDEX shows. Observed: all 100 updates are missing from the index, and their old entries remain.

The script below (bash + curl + python3, runs the official Docker image) automates this. Each block of SurrealQL it sends is one HTTP request, so each BEGIN … COMMIT is one transaction. For each run it:

  1. Seeds 50,000 rows.
  2. Sends BEGIN; DEFINE INDEX ix ON t FIELDS x CONCURRENTLY; SLEEP 3s; COMMIT; as one request. On another connection, it updates t:1..t:50 at 0.05 s (usually during the initial scan) and t:51..t:100 at 0.8 s (after the scan), then checks the index.
  3. If the index is wrong, sends the follow-up UPDATEs on t:1..t:3 shown above, one request each, and checks them. It then sets t:1 and t:3 back to 'new'.
  4. Runs REBUILD INDEX … CONCURRENTLY with no writers, then checks the index.
  5. Sends BEGIN; REBUILD INDEX … CONCURRENTLY; SLEEP 3s; COMMIT; with the same write timing on t:101..t:200, then checks the index.

The write helper retries an in-window UPDATE that returns an error (for example a transaction conflict) and prints the attempt number. In the final 3.2.4 run, all 20 in-window UPDATEs succeeded on the first attempt, so no retry was needed. The script exits 0 if the bug reproduced and 2 if it did not.

Build (official image, memory engine) 1st build: DEFINE … CONCURRENTLY REBUILD, no writers REBUILD with the same writes
3.2.4+20260803.93ab219 5/5 runs lost 100/100 updates, 100 stale entries, updated: 0; follow-up writes as described above in 5/5 5/5 exact 5/5 exact, updated: 50
3.3.0 5/5 runs lost 100/100, 100 stale, updated: 0 5/5 exact 5/5 exact, updated: 50
3.4.0-nightly+20260925.df34ba7 3/3 runs lost 100/100, 100 stale, updated: 0 3/3 exact 3/3 exact, updated: 50

The 3.2.4 row is the final run of the script below. The 3.3.0 and nightly rows come from an earlier revision of the script with the same statements and write timing; that revision did not yet send the follow-up writes or print attempt numbers.

Both writes are lost: the one at 0.05 s, which falls during the scan judging by the REBUILD's updated: 50, and the one at 0.8 s, after the scan. The bug also reproduces with 1,000 rows (10 rows updated at 0.8 s, 10/10 lost in each of 2 runs on 3.2.4).

Output of the first run on 3.2.4:

image:  surrealdb/surrealdb:v3.2.4
server: 3.2.4+20260803.93ab219 for linux on aarch64
rows=50000  rows-updated-per-phase=100  hold=3s  writes at 0.05s and 0.8s  runs=5
run 1/5
  seed: OK
  BEGIN; DEFINE INDEX ix ON t FIELDS x CONCURRENTLY; SLEEP 3s; COMMIT; -> OK
    UPDATE t:1..=50 -> OK on attempt 1 (DDL transaction still open when it returned)
    UPDATE t:51..=100 -> OK on attempt 1 (DDL transaction still open when it returned)
    INFO FOR INDEX ix ON t, from another connection inside the window -> ERR "The index 'ix' does not exist"
  x='new': index 0 / NOINDEX 100 (expected 100) | count x='old': index 50000 / NOINDEX 49900 | lost=100 stale=100 | {"initial":50000,"pending":0,"status":"ready","updated":0}
  BUG: the new index lost 100 and kept 100 stale entries
  plan of SELECT ... WHERE x = 'new': IndexScan on ix
  SELECT id, x FROM t WHERE x = 'old' AND record::id(id) <= 3 -> [{"id": "t:1", "x": "new"}, {"id": "t:2", "x": "new"}, {"id": "t:3", "x": "new"}]
  SELECT VALUE record::id(id) FROM t WHERE x = 'old' LIMIT 3 -> [101, 102, 103]
  follow-up writes, one auto-commit request each:
    UPDATE t:1 SET x = 'third'; -> OK
    UPDATE t:2 SET x = 'new'; -> OK
    UPDATE t:3 SET x = 'old'; -> OK
    UPDATE t:3 SET x = 'fourth'; -> OK
    SELECT VALUE record::id(id) FROM t WHERE x = 'third' -> [1]
    SELECT id, x FROM t WHERE x = 'old' AND record::id(id) <= 3 -> [{"id": "t:1", "x": "third"}, {"id": "t:2", "x": "new"}]
    SELECT VALUE record::id(id) FROM t WHERE x = 'new' AND record::id(id) <= 3 -> []   (WITH NOINDEX: [2])
    SELECT VALUE record::id(id) FROM t WHERE x = 'fourth' -> [3]
  NOT REPAIRED: t:1 still stale under 'old'; t:2 still missing under 'new' and stale under 'old'; t:3 exact
  set t:1 and t:3 back to 'new' -> OK
  REBUILD INDEX ix ON t CONCURRENTLY -> OK
  x='new': index 100 / NOINDEX 100 (expected 100) | count x='old': index 49900 / NOINDEX 49900 | lost=0 stale=0 | {"initial":50000,"pending":0,"status":"ready","updated":0}
  PASS: REBUILD made the index exact
  BEGIN; REBUILD INDEX ix ON t CONCURRENTLY; SLEEP 3s; COMMIT; -> OK
    UPDATE t:101..=150 -> OK on attempt 1 (DDL transaction still open when it returned)
    UPDATE t:151..=200 -> OK on attempt 1 (DDL transaction still open when it returned)
    INFO FOR INDEX ix ON t, from another connection inside the window -> OK {"building":{"initial":50000,"pending":0,"status":"ready","updated":50}}
  x='new': index 200 / NOINDEX 200 (expected 200) | count x='old': index 49800 / NOINDEX 49800 | lost=0 stale=0 | {"initial":50000,"pending":0,"status":"ready","updated":50}
  PASS: REBUILD with a concurrent writer lost nothing
...
SUMMARY (surrealdb/surrealdb:v3.2.4): first build lost writes in 5/5 runs; follow-up writes left t:1/t:2 wrong and t:3 exact in 5/5 of those; REBUILD wrong in 0 checks
BUG REPRODUCED
repro.sh
bash
#!/usr/bin/env bash
# DEFINE INDEX ... CONCURRENTLY (first build of a new index) permanently misses a
# write that commits after the build has started scanning but before the DEFINE's
# own transaction has committed. REBUILD INDEX ... CONCURRENTLY, run the same way, does not.
# Prints BUG / PASS lines per phase and a SUMMARY.
#
# Requires: docker, curl, python3 (JSON parsing only).
# Exit code: 0 = bug reproduced, 2 = not reproduced, 1 = setup error.
#
#   bash repro.sh                                   # surrealdb/surrealdb:v3.2.4
#   IMAGE=surrealdb/surrealdb:v3.3.0 bash repro.sh
set -uo pipefail

IMAGE=${IMAGE:-surrealdb/surrealdb:v3.2.4}
ROWS=${ROWS:-50000}        # rows in the table
K=${K:-100}                # rows t:1..t:K are updated inside the window (the scan reads them first)
RUNS=${RUNS:-5}
HOLD=${HOLD:-3s}           # how long the DDL's transaction stays open after the statement
EARLY_AT=${EARLY_AT:-0.05} # first write: while the initial scan is (usually) still running
LATE_AT=${LATE_AT:-0.8}    # second write: after the initial scan has finished
NAME=surreal-define-concurrently-repro-$$-$RANDOM

cleanup() { docker rm -fv "$NAME" >/dev/null 2>&1 || true; }
trap cleanup EXIT INT TERM

docker run --rm -d --name "$NAME" -p 127.0.0.1::8000 "$IMAGE" \
	start --user root --pass root memory >/dev/null || { echo "docker run failed"; exit 1; }
URL="http://$(docker port "$NAME" 8000/tcp | head -1)"
for _ in $(seq 200); do curl -sf "$URL/health" >/dev/null && break; sleep 0.1; done
curl -sf "$URL/health" >/dev/null || { echo "server did not start"; exit 1; }
echo "image:  $IMAGE"
echo "server: $(docker exec "$NAME" /surreal version 2>/dev/null | grep -v onnxruntime | tail -1)"
echo "rows=$ROWS  rows-updated-per-phase=$K  hold=$HOLD  writes at ${EARLY_AT}s and ${LATE_AT}s  runs=$RUNS"

# sql DB QUERY -> JSON array with one result per statement. One call = one HTTP request,
# so `BEGIN; ...; COMMIT;` sent in one call is one transaction.
sql() {
	curl -s -u root:root -H 'Accept: application/json' -H 'Surreal-NS: repro' -H "Surreal-DB: $1" \
		--data-binary "$2" "$URL/sql"
}
# py EXPR -> evaluate EXPR over the parsed JSON response `r` read from stdin
py() { python3 -c "import json,sys; r=json.load(sys.stdin); print($1)"; }
# ok -> "OK" if every statement in the response succeeded, else the first error
ok() { py 'next((str(s["result"]) for s in r if s["status"] != "OK"), "OK")'; }

wait_ready() { # DB -> waits until INFO FOR INDEX reports the build as ready
	local s
	for _ in $(seq 600); do
		s=$(sql "$1" 'INFO FOR INDEX ix ON t;' |
			py 'r[-1]["result"]["building"]["status"] if r[-1]["status"] == "OK" and r[-1]["result"] else "absent"')
		[ "$s" = ready ] && return 0
		sleep 0.1
	done
	echo "  index never became ready (last status: $s)"
	return 1
}

# check DB EXPECTED_NEW -> prints one line and sets MISSING / STALE
check() {
	local out
	out=$(sql "$1" "
		SELECT VALUE record::id(id) FROM t WHERE x = 'new';
		SELECT VALUE record::id(id) FROM t WITH NOINDEX WHERE x = 'new';
		SELECT count() FROM t WHERE x = 'old' GROUP ALL;
		SELECT count() FROM t WITH NOINDEX WHERE x = 'old' GROUP ALL;
		INFO FOR INDEX ix ON t;" | py '"%d %d %d %d %s" % (
			len(r[0]["result"]), len(r[1]["result"]),
			(r[2]["result"] or [{"count": 0}])[0]["count"], (r[3]["result"] or [{"count": 0}])[0]["count"],
			json.dumps(r[4]["result"]["building"], sort_keys=True, separators=(",", ":")))')
	read -r idx_new scan_new idx_old scan_old info <<<"$out"
	MISSING=$((scan_new - idx_new))
	STALE=$((idx_old - scan_old))
	echo "  x='new': index $idx_new / NOINDEX $scan_new (expected $2) | count x='old': index $idx_old / NOINDEX $scan_old | lost=$MISSING stale=$STALE | $info"
}

# write DB FIRST LAST -> sets x = 'new' on t:FIRST..=t:LAST in one auto-commit
# transaction; prints "OK on attempt N", or the last response if every attempt failed.
# An UPDATE that returns an error (e.g. a transaction conflict) is retried, up to 50
# attempts; N shows whether a retry was needed. Pure bash + curl: it runs inside the
# timing window.
write() {
	local resp n
	for n in $(seq 50); do
		resp=$(sql "$1" "UPDATE t:$2..=$3 SET x = 'new' RETURN NONE;")
		if [[ $resp == *'"status":"OK"'* && $resp != *'"status":"ERR"'* ]]; then echo "OK on attempt $n"; return; fi
		sleep 0.05
	done
	echo "$resp"
}

# window DB STATEMENT FIRST LAST -> sends `BEGIN; STATEMENT; SLEEP HOLD; COMMIT;` as one
# request on one connection and, on another connection, updates the first half of
# t:FIRST..=t:LAST at EARLY_AT seconds and the second half at LATE_AT seconds.
window() {
	local ddl_out ddl_pid mid w1 w2 open1 open2 info
	mid=$(( ($3 + $4) / 2 ))
	ddl_out=$(mktemp)
	sql "$1" "BEGIN; $2; SLEEP $HOLD; COMMIT;" >"$ddl_out" &
	ddl_pid=$!
	sleep "$EARLY_AT"
	w1=$(write "$1" "$3" "$mid")
	kill -0 "$ddl_pid" 2>/dev/null && open1=open || open1=CLOSED
	sleep "$(awk "BEGIN { d = $LATE_AT - $EARLY_AT; print (d > 0 ? d : 0) }")"
	w2=$(write "$1" $((mid + 1)) "$4")
	kill -0 "$ddl_pid" 2>/dev/null && open2=open || open2=CLOSED
	info=$(sql "$1" 'INFO FOR INDEX ix ON t;') # what other connections see inside the window
	wait "$ddl_pid"
	echo "  BEGIN; $2; SLEEP $HOLD; COMMIT; -> $(ok <"$ddl_out")"
	echo "    UPDATE t:$3..=$mid -> $w1 (DDL transaction still $open1 when it returned)"
	echo "    UPDATE t:$((mid + 1))..=$4 -> $w2 (DDL transaction still $open2 when it returned)"
	echo "    INFO FOR INDEX ix ON t, from another connection inside the window -> $(py '(r[-1]["status"] + " " + json.dumps(r[-1]["result"], separators=(",", ":")))' <<<"$info")"
	[ "$open1$open2" = openopen ] || echo "    WARNING: a write landed after the DDL committed; raise HOLD"
	rm -f "$ddl_out"
}

# followup DB -> after a bad build (t:1..t:3 lost under 'new', stale under 'old'), sends
# each UPDATE below as its own auto-commit request, prints what the index returns for
# t:1..t:3, then sets t:1 and t:3 back to 'new'. Sets FOLLOWUP_AS_REPORTED=1 if t:1 and
# t:2 stayed wrong and t:3 came out exact.
followup() {
	local s out verdict
	echo "  follow-up writes, one auto-commit request each:"
	for s in "UPDATE t:1 SET x = 'third';" "UPDATE t:2 SET x = 'new';" \
		"UPDATE t:3 SET x = 'old';" "UPDATE t:3 SET x = 'fourth';"; do
		echo "    $s -> $(sql "$1" "$s" | ok)"
	done
	out=$(sql "$1" "
		SELECT VALUE record::id(id) FROM t WHERE x = 'third';
		SELECT id, x FROM t WHERE x = 'old' AND record::id(id) <= 3;
		SELECT VALUE record::id(id) FROM t WHERE x = 'new' AND record::id(id) <= 3;
		SELECT VALUE record::id(id) FROM t WITH NOINDEX WHERE x = 'new' AND record::id(id) <= 3;
		SELECT VALUE record::id(id) FROM t WHERE x = 'fourth';")
	py '"\n".join([
		"    SELECT VALUE record::id(id) FROM t WHERE x = %s -> %s" % (chr(39) + "third" + chr(39), json.dumps(r[0]["result"])),
		"    SELECT id, x FROM t WHERE x = %s AND reco