Skip to content

TRUNCATE TYPE racing concurrent INSERT and DELETE fails with RecordNotFoundException (HTTP 404) for a record another transaction deleted, instead of skipping it or raising a retryable conflict #11731

Closed

Description

@shaunpatterson

Summary

TRUNCATE TYPE T UNSAFE run while other transactions insert into and delete from T sometimes fails with RecordNotFoundException: Record #1:24618 not found and HTTP 404. The record it names is one a concurrent DELETE removed after the truncate's bucket scan found it. The error is not one a client can act on: the statement named no record, the record was gone because someone else deleted it, and the HTTP handler does not retry it the way it retries the ConcurrentModificationException the same race raises most of the time.

DELETE FROM T WHERE ... statements racing each other over the same records do not fail this way: six overlapping DELETEs, 30 rounds, all 180 returned 200.

Measured (26.12.1-SNAPSHOT, main 2d6b9dd)

The script below runs TRUNCATE TYPE T UNSAFE every 0.1 s for 120 s while two threads insert batches of 200 records (the table kept under 20,000 rows) and two threads run DELETE FROM T WHERE v = ? LIMIT 50:

766 x HTTP 503 ConcurrentModificationException: Slot rebase not possible on page PageId(truncrace/1/2) slot 42 (concurrent change to the record being deleted). Please retry the operation
 11 x HTTP 404 RecordNotFoundException: Record #1:24618 not found

With deletes only and no concurrent inserts, 40 attempts gave 27 successes and 13 retryable conflicts, and no RecordNotFoundException.

Where it comes from

Over HTTP the statement runs inside the transaction the handler opens, so TruncateTypeStatement takes truncateInCallerTransaction, which hands db.scanType(...) to TruncateRecordDeleter.deleteAll. That method calls record.delete() on each record the scan returns and stops on the first exception, which it returns as the statement's failure. A record committed by a concurrent insert after the scan began, and deleted by a concurrent transaction before the truncate reaches it, makes delete() throw RecordNotFoundException. The openCypher DeleteStep catches RecordNotFoundException around each delete for exactly this reason ("Already deleted - skip").

reproduction script (HTTP API, port and root password as arguments)
"""TRUNCATE TYPE racing INSERT and DELETE sometimes fails with RecordNotFoundException (not a retryable conflict). Args: port password."""
import base64, json, random, sys, threading, time, urllib.error, urllib.request
from collections import Counter

PORT, PW = sys.argv[1], sys.argv[2]
H = {'Authorization': 'Basic ' + base64.b64encode(f'root:{PW}'.encode()).decode(), 'Content-Type': 'application/json'}


def post(path, body):
    r = urllib.request.Request(f'http://127.0.0.1:{PORT}{path}', data=json.dumps(body).encode(), headers=H, method='POST')
    try:
        return 200, json.loads(urllib.request.urlopen(r, timeout=120).read() or b'{}')
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read() or b'{}')


def sql(q, p=None):
    return post('/api/v1/command/truncrace', {'language': 'sql', 'command': q, 'params': p or {}})


post('/api/v1/server', {'command': 'drop database truncrace'})
post('/api/v1/server', {'command': 'create database truncrace'})
sql('CREATE DOCUMENT TYPE T')
sql('CREATE PROPERTY T.v INTEGER')
outcomes, details = Counter(), {}
stop = threading.Event()


def inserter():
    while not stop.is_set():
        # keep the table small: the truncates mostly lose to the writers, so an unbounded insert loop grows it without end
        if sql('SELECT count(*) AS c FROM T')[1]['result'][0]['c'] > 20000:
            time.sleep(0.05)
            continue
        sql('INSERT INTO T CONTENT :r', {'r': [{'v': i % 50} for i in range(200)]})


def deleter():
    rnd = random.Random()
    while not stop.is_set():
        sql('DELETE FROM T WHERE v = :v LIMIT 50', {'v': rnd.randint(0, 49)})


workers = [threading.Thread(target=f) for f in (inserter, inserter, deleter, deleter)]
[w.start() for w in workers]
deadline = time.time() + 120
while time.time() < deadline:
    time.sleep(0.1)
    status, body = sql('TRUNCATE TYPE T UNSAFE')
    key = f'HTTP {status} ' + body.get('exception', 'ok').split('.')[-1]
    outcomes[key] += 1
    details.setdefault(key, body.get('detail', '')[:160])
stop.set()
[w.join() for w in workers]
print('TRUNCATE TYPE T UNSAFE every 0.1 s for 120 s, while two threads INSERT (table kept under 20,000 rows) and two DELETE ... LIMIT 50:')
for key, n in outcomes.most_common():
    print(f'  {n:3d} x {key}: {details[key]}')

Expected

A record that is already gone when the truncate reaches it is skipped, since the truncate's goal (no record left) holds for it, or the failure is reported as the retryable ConcurrentModificationException the rest of this race raises.

Activity

  1. added
    concurrency
    engine
    server
    severity:minor
    in progress
    on Nov 13, 2026
  2. added a commit that references this issue on Nov 14, 2026
  3. added this to the 26.12.1 milestone on Nov 14, 2026
  4. added 2 commits that reference this issue on Nov 16, 2026
  5. self-assigned this
    on Nov 19, 2026
  6. self-assigned this
    on Nov 19, 2026
  7. added 2 commits that reference this issue on Nov 19, 2026
  8. added a commit that references this issue on Nov 19, 2026
  9. robfrank commented on Nov 19, 2026

    @robfrank
    Collaborator

    TRUNCATE TYPE and TRUNCATE BUCKET delete the records they find one by one. When another transaction deleted one of those records, and committed, between the moment the truncate found it and the moment it tried to delete it, the statement failed with RecordNotFoundException (HTTP 404) for a record you never named. Nothing retried that error.

    Now the same race fails with the retryable ConcurrentModificationException (HTTP 503), the error a DELETE FROM already gets in that position. The failed attempt leaves nothing half done in its transaction, and running the truncate again finishes the job, since the retry no longer sees the deleted record. We chose the retryable conflict over silently skipping the record (the other option you listed), because by the time the record is found missing, delete listeners and index changes for it have already run in the transaction.

    Fixed by #11732, ships in 26.12.1.


    ❤️ Thanks for helping make ArcadeDB better! ArcadeDB is free and open source, sustained by its community. If it's useful to you or your company, please consider becoming a sponsor to keep development going.

  10. removed
    in progress
    on Nov 19, 2026
  11. added a commit that references this issue on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugconcurrencyengineserverseverity:minorsql

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions