Skip to content

BUG: gRPC InsertStream begins the transaction in onNext but commits in onCompleted, which can run on a different pool thread, intermittently failing the commit with "Transaction not begun" #4644

Closed

Description

@TheRealMcoy

Description

A gRPC InsertStream (client-streaming bulk insert) under the default PER_STREAM transaction mode intermittently fails its commit with
TransactionException: Transaction not begun, even though every row was received and inserted without error. The client gets an InsertSummary of the form received=N, inserted=0, failed=N with a single InsertError(row_index=-1, code="COMMIT_FAILED", message="Transaction not begun").

The received=N count and the row_index=-1 (commit-time, not row-time) error are the tell: the rows were inserted fine, then the deferred end-of-stream commit could not find a transaction to commit. Re-running the same insert usually succeeds.

The failure rate depends on how the client paces the request stream. A client that drains its rows synchronously and sends the single data chunk and the half-close back to back almost never trips it. A client that produces rows asynchronously (so the data chunk and the half-close are flushed in separate event-loop turns / TCP segments) trips it regularly, because the server then dispatches onNext and onCompleted as two separate tasks that can land on two different executor threads.

Environment

  • ArcadeDB 26.7.1-SNAPSHOT (build f848c485e92637d9c1163f3d9fcb4e4c08ee3cfd/1781234579679/main)
  • gRPC InsertStream (client-streaming) only. HTTP bulk insert is unaffected (each batch is its own POST/transaction handled on one Undertow worker thread).
  • Default database options, default isolation READ_COMMITTED.
  • transaction_mode = PER_STREAM (the default), where the commit is deferred to onCompleted. PER_REQUEST is affected identically. PER_BATCH / PER_ROW are exposed on any callback thread hop too (see Root cause).

Root cause

ArcadeDB transactions are bound to the calling thread through a ThreadLocal:

engine/src/main/java/com/arcadedb/database/DatabaseContext.java:33

public class DatabaseContext extends ThreadLocal<Map<String, DatabaseContext.DatabaseContextTL>> {
  public static final DatabaseContext INSTANCE = new DatabaseContext();

Both begin() and commit() resolve the active transaction from the current thread's context:

engine/src/main/java/com/arcadedb/database/LocalDatabase.java:463-503

public void begin(final TRANSACTION_ISOLATION_LEVEL isolationLevel) {
  ...
  final DatabaseContext.DatabaseContextTL current = DatabaseContext.INSTANCE.getContext(databasePath);
  ...
}

public void commit() {
  ...
  final DatabaseContext.DatabaseContextTL current = DatabaseContext.INSTANCE.getContext(LocalDatabase.this.getDatabasePath());
  final Binary result = current.getLastTransaction().commit();   // throws "Transaction not begun" if this thread has no active tx
  ...
}

If the commit runs on a thread that never had a transaction begun on it, commit() throws TransactionException: Transaction not begun
(engine/src/main/java/com/arcadedb/database/TransactionContext.java:141 / :341).

The InsertStream handler splits begin and commit across two different StreamObserver callbacks:

grpcw/src/main/java/com/arcadedb/server/grpc/ArcadeDbGrpcService.java:1655-1768

  • On the first onNext, it constructs an InsertContext. That constructor calls getDatabase(...), which initializes the DatabaseContext thread-local on the current thread (ArcadeDbGrpcService.java:2976), and then calls db.begin() (InsertContext ctor, :2900). Rows are inserted on this same thread via insertRows(...) (:1710).
  • On onCompleted, it calls ctx.flushCommit(true) → db.commit() (:1751, InsertContext.flushCommit :2927). onCompleted never re-initializes the DatabaseContext thread-local for the committing thread.

gRPC guarantees that a call's StreamObserver callbacks are serialized (no concurrency, with happens-before between them), but it does not guarantee they run on the same thread. The server-side serializing executor can run onCompleted on a different thread from the pool than the one that ran the first onNext. When that happens, the committing thread has no active transaction for the database path, and the deferred PER_STREAM commit throws Transaction not begun.

The handler then routes that exception through recordCommitException(...) (ArcadeDbGrpcService.java:1777), which reclassifies the already-counted inserts as failed (inserted=0, failed=received) and appends a single row_index=-1 error with code COMMIT_FAILED and message Transaction not begun. This is the exact InsertSummary the client observes.

Steps to reproduce

A grpcw integration test in the style of grpcw/src/test/java/com/arcadedb/server/grpc/Issue4198InsertStreamCommitErrorIT.java.
To make the onNext → onCompleted thread hop deterministic, send the single data chunk, wait briefly so the server drains it and the executor thread goes idle, then send the half-close (onCompleted) so it is dispatched on a fresh pool thread.

@Test
void insertStreamPerStreamCommitMustNotDependOnCallbackThread() throws Exception {
  final String typeName = "InsertStreamThreadHopType_" + System.currentTimeMillis();

  authenticatedStub.executeCommand(ExecuteCommandRequest.newBuilder()
      .setDatabase(getDatabaseName()).setCredentials(credentials())
      .setCommand("CREATE DOCUMENT TYPE " + typeName).build());

  final CountDownLatch done = new CountDownLatch(1);
  final AtomicReference<InsertSummary> summaryRef = new AtomicReference<>();
  final AtomicReference<Throwable> errorRef = new AtomicReference<>();

  final StreamObserver<InsertChunk> req = asyncAuthenticatedStub.insertStream(new StreamObserver<>() {
    @Override public void onNext(final InsertSummary s) { summaryRef.set(s); }
    @Override public void onError(final Throwable t) { errorRef.set(t); done.countDown(); }
    @Override public void onCompleted() { done.countDown(); }
  });

  // One chunk carrying every row, marked last=true.
  final InsertChunk.Builder chunk = InsertChunk.newBuilder()
      .setSessionId("thread-hop-repro")
      .setChunkSeq(0)
      .setLast(true)
      .setOptions(InsertOptions.newBuilder()
          .setDatabase(getDatabaseName())
          .setCredentials(credentials())
          .setTargetClass(typeName)
          .setConflictMode(InsertOptions.ConflictMode.CONFLICT_ERROR)
          .setTransactionMode(InsertOptions.TransactionMode.PER_STREAM)
          .build());
  for (int i = 0; i < 150; i++)
    chunk.addRows(GrpcRecord.newBuilder().setType(typeName).putProperties("name", stringValue("ag" + i)).build());

  req.onNext(chunk.build());

  // Let the server process the data chunk and the executor thread go idle, so the
  // half-close below is dispatched on a different pool thread than the one that ran
  // onNext (and therefore db.begin()).
  Thread.sleep(250);
  req.onCompleted();

  assertThat(done.await(30, TimeUnit.SECONDS)).isTrue();
  assertThat(errorRef.get()).isNull();

  final InsertSummary summary = summaryRef.get();
  assertThat(summary).isNotNull();
  assertThat(summary.getReceived()).isEqualTo(150);
  assertThat(summary.getInserted()).isEqualTo(150);   // FAILS: observed inserted=0, failed=150
  assertThat(summary.getFailed()).isEqualTo(0);
  assertThat(summary.getErrorsList()).isEmpty();       // observed: 1x {row_index=-1, COMMIT_FAILED, "Transaction not begun"}

  authenticatedStub.executeCommand(ExecuteCommandRequest.newBuilder()
      .setDatabase(getDatabaseName()).setCredentials(credentials())
      .setCommand("DROP TYPE " + typeName + " IF EXISTS UNSAFE").build());
}

Without the deliberate Thread.sleep(250), the same insert is intermittent: sending the chunk and the half-close back to back usually commits on the onNext thread and passes, which is why it reads as a flaky test rather than a hard failure.

Observed

The RPC terminates cleanly (no Status.INTERNAL) but the InsertSummary reports the deferred commit as a failure:

received   = 150
inserted   = 0
updated    = 0
ignored    = 0
failed     = 150
errors     = [ { row_index = -1, code = "COMMIT_FAILED", message = "Transaction not begun" } ]

Every row was inserted under the transaction on the onNext thread; the commit on the onCompleted thread found no transaction bound to it and threw.

Expected

InsertStream should commit the rows it inserted regardless of which executor thread runs onCompleted:

received = 150
inserted = 150
failed   = 0
errors   = []

The result of a bulk insert must not depend on whether the gRPC executor happens to run the stream's callbacks on the same thread.

Suggested fix

The transaction is thread-bound, so the handler must make sure each callback operates on the correct thread-local context. Options, roughly in order of preference:

  1. Re-bind the context at the top of every callback. At the start of onNext and onCompleted, initialize the thread-local for the committing thread before touching the transaction, e.g. DatabaseContext.INSTANCE.init((DatabaseInternal) ctx.db) (the same call getDatabase(...) already makes for the first chunk at ArcadeDbGrpcService.java:2976). This is the most localized fix and makes begin / insertRows / flushCommit correct on any pool thread. It also covers the multi-chunk and PER_BATCH / PER_ROW hop cases.

  2. Pin the stream to a single thread for its lifetime. Dispatch the InsertStream callbacks onto a single-thread executor (one per call) so begin, the row inserts, and the commit always run on the same thread that holds the transaction. Heavier-weight and serializes per-stream work, but removes the thread-affinity assumption entirely.

  3. Carry the transaction explicitly instead of via the thread-local. Capture the TransactionContext begun in onNext on the InsertContext and commit that instance directly in onCompleted, rather than resolving "the current thread's last transaction." This decouples the commit from thread identity but is a larger change to the transaction API surface.

Option 1 is the smallest change and directly repairs the broken assumption; it mirrors the existing first-chunk DatabaseContext.init(...) call and keeps the gRPC executor's normal thread-pooling intact.

Activity

  1. self-assigned this
    on Jun 16, 2026
  2. added theissue type on Jun 16, 2026
  3. lvca commented on Jun 16, 2026

    @lvca
    Member

    Thanks for the detailed description, I was able to reproduce it.

  4. lvca commented on Jun 16, 2026

    @lvca
    Member

    Fixed

  5. added this to the 26.7.1 milestone on Jun 16, 2026
  6. TheRealMcoy commented on Jun 16, 2026

    @TheRealMcoy
    Author

    Thanks for the fast turn-around, confirmed fixed now!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions