Repository navigation
Description
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(buildf848c485e92637d9c1163f3d9fcb4e4c08ee3cfd/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 toonCompleted.PER_REQUESTis affected identically.PER_BATCH/PER_ROWare 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 anInsertContext. That constructor callsgetDatabase(...), which initializes theDatabaseContextthread-local on the current thread (ArcadeDbGrpcService.java:2976), and then callsdb.begin()(InsertContextctor,:2900). Rows are inserted on this same thread viainsertRows(...)(:1710). - On
onCompleted, it callsctx.flushCommit(true)→db.commit()(:1751,InsertContext.flushCommit:2927).onCompletednever re-initializes theDatabaseContextthread-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:
-
Re-bind the context at the top of every callback. At the start of
onNextandonCompleted, initialize the thread-local for the committing thread before touching the transaction, e.g.DatabaseContext.INSTANCE.init((DatabaseInternal) ctx.db)(the same callgetDatabase(...)already makes for the first chunk atArcadeDbGrpcService.java:2976). This is the most localized fix and makesbegin/insertRows/flushCommitcorrect on any pool thread. It also covers the multi-chunk andPER_BATCH/PER_ROWhop cases. -
Pin the stream to a single thread for its lifetime. Dispatch the
InsertStreamcallbacks onto a single-thread executor (one per call) sobegin, 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. -
Carry the transaction explicitly instead of via the thread-local. Capture the
TransactionContextbegun inonNexton theInsertContextand commit that instance directly inonCompleted, 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
fix: gRPC InsertStream begins the transaction in onNext but commits i…
lvca commentedon Jun 16, 2026
Thanks for the detailed description, I was able to reproduce it.
lvca commentedon Jun 16, 2026
Fixed
TheRealMcoy commentedon Jun 16, 2026
Thanks for the fast turn-around, confirmed fixed now!
fix: gRPC InsertStream begins the transaction in onNext but commits i…