Skip to content

fix(#4801): serialize gRPC streaming terminal calls on a thread-safe StreamObserver - #4818

Merged
robfrank merged 4 commits into
mainfrom
fix/4801-grpc-streamobserver-thread-safety
Jun 30, 2026
Merged

robfrank merged 4 commits into
mainfrom
fix/4801-grpc-streamobserver-thread-safety

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Summary

Fixes #4801. gRPC StreamObserver is not thread-safe, but ArcadeDbGrpcService.graphBatchLoad and insertBidirectional issued terminal/write calls (onNext/onError/onCompleted) directly on the raw observer:

  • graphBatchLoad relied on a TOCTOU if (!cancelled.get()) check, so a cancellation racing the final terminal call could deliver a write/terminal on an already-closed call.
  • insertBidirectional dispatched DB work to a single-threaded executor and called terminal methods from those tasks while the cancel handler ran on the transport thread; a duplicate terminal (e.g. COMMIT then a stray message hitting the defensive catch) or a cancellation could interleave terminal calls.

Symptoms: IllegalStateException ("call already closed"), dropped responses, or client hangs.

Fix

New SynchronizedStreamObserver<T> (grpcw) wraps the response observer and:

  • serializes every call through a single monitor;
  • enforces at most one delegated terminal via an AtomicBoolean completed CAS, and drops any onNext after a terminal call;
  • exposes markTerminated() for the call's cancel handler to flip the flag without delegating (the transport already closed the call);
  • swallows the IllegalStateException the delegate throws on a concurrent close, marking itself terminated.

Both streaming handlers now route all write/terminal calls through it; the original ServerCallStreamObserver reference is kept only for flow control.

Tests

Issue4801SynchronizedStreamObserverTest (unit, mock-free) drives the wrapper against a delegate that emulates gRPC's contract (throws on a second terminal / write-after-close):

  • drop onNext after onCompleted
  • collapse duplicate terminals to one
  • markTerminated drops subsequent calls without delegating
  • delegate IllegalStateException on concurrent close is swallowed
  • 200 iterations x 32 threads racing onNext/onCompleted/onError/markTerminated - no exception escapes, never more than one terminal, no contract violation

Red/green verified: a naive pass-through wrapper fails with the exact IllegalStateException: call already closed from the issue; the fix makes all 5 pass. GrpcServerIT#graphBatchLoadVerticesAndEdges still passes end-to-end.

🤖 Generated with Claude Code

…treamObserver

graphBatchLoad and insertBidirectional issued onNext/onError/onCompleted
directly on a non-thread-safe StreamObserver. A cancellation racing a final
terminal call, or a duplicate terminal, could interleave terminal calls and
throw IllegalStateException ("call already closed"), drop responses, or hang
the client.

Introduce SynchronizedStreamObserver: serializes every call, enforces at most
one delegated terminal via an AtomicBoolean CAS, drops onNext after terminal,
exposes markTerminated() for the cancel handler, and swallows the delegate's
IllegalStateException on concurrent close. Both streaming handlers now route
all write/terminal calls through it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mergify

mergify Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 14 complexity

Metric Results
Complexity 14

View in Codacy

🟢 Coverage 70.59% diff coverage · -7.28% coverage variation

Metric Results
Coverage variation ✅ -7.28% coverage variation
Diff coverage ✅ 70.59% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (61d0b69) 133245 98847 74.18%
Head commit (0f89c86) 165096 (+31851) 110459 (+11612) 66.91% (-7.28%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#4818) 68 48 70.59%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses issue #4801 by introducing SynchronizedStreamObserver, a thread-safe wrapper for gRPC's StreamObserver to prevent concurrent terminal calls and race conditions in graphBatchLoad and insertBidirectional. It also adds a comprehensive suite of unit tests to verify thread safety and contract enforcement. The review feedback suggests a valuable improvement: catching io.grpc.StatusRuntimeException alongside IllegalStateException in onNext, onError, and onCompleted to ensure transport-level exceptions from cancelled or closed calls do not propagate unexpectedly.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +51 to +62
public void onNext(final T value) {
synchronized (lock) {
if (completed.get())
return;
try {
delegate.onNext(value);
} catch (final IllegalStateException closed) {
// The underlying call was concurrently cancelled/closed by the transport: stop sending.
completed.set(true);
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In addition to IllegalStateException, gRPC's StreamObserver can throw io.grpc.StatusRuntimeException (e.g., with status CANCELLED) if the call is cancelled or closed by the transport. Catching StatusRuntimeException ensures that the wrapper immediately marks itself as completed and avoids redundant subsequent calls to the delegate.

Suggested change
public void onNext(final T value) {
synchronized (lock) {
if (completed.get())
return;
try {
delegate.onNext(value);
} catch (final IllegalStateException closed) {
// The underlying call was concurrently cancelled/closed by the transport: stop sending.
completed.set(true);
}
}
}
@Override
public void onNext(final T value) {
synchronized (lock) {
if (completed.get())
return;
try {
delegate.onNext(value);
} catch (final IllegalStateException | io.grpc.StatusRuntimeException closed) {
// The underlying call was concurrently cancelled/closed by the transport: stop sending.
completed.set(true);
}
}
}

Comment on lines +65 to +75
public void onError(final Throwable t) {
synchronized (lock) {
if (!completed.compareAndSet(false, true))
return;
try {
delegate.onError(t);
} catch (final IllegalStateException ignore) {
// Call already closed: nothing more to deliver.
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Catching io.grpc.StatusRuntimeException here as well prevents transport-level exceptions from propagating when trying to deliver an error on an already closed or cancelled call.

Suggested change
public void onError(final Throwable t) {
synchronized (lock) {
if (!completed.compareAndSet(false, true))
return;
try {
delegate.onError(t);
} catch (final IllegalStateException ignore) {
// Call already closed: nothing more to deliver.
}
}
}
@Override
public void onError(final Throwable t) {
synchronized (lock) {
if (!completed.compareAndSet(false, true))
return;
try {
delegate.onError(t);
} catch (final IllegalStateException | io.grpc.StatusRuntimeException ignore) {
// Call already closed: nothing more to deliver.
}
}
}

Comment on lines +78 to +88
public void onCompleted() {
synchronized (lock) {
if (!completed.compareAndSet(false, true))
return;
try {
delegate.onCompleted();
} catch (final IllegalStateException ignore) {
// Call already closed: nothing more to deliver.
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Catching io.grpc.StatusRuntimeException here as well prevents transport-level exceptions from propagating when trying to complete an already closed or cancelled call.

Suggested change
public void onCompleted() {
synchronized (lock) {
if (!completed.compareAndSet(false, true))
return;
try {
delegate.onCompleted();
} catch (final IllegalStateException ignore) {
// Call already closed: nothing more to deliver.
}
}
}
@Override
public void onCompleted() {
synchronized (lock) {
if (!completed.compareAndSet(false, true))
return;
try {
delegate.onCompleted();
} catch (final IllegalStateException | io.grpc.StatusRuntimeException ignore) {
// Call already closed: nothing more to deliver.
}
}
}

@claude

claude Bot commented Jun 30, 2026

Copy link
Copy Markdown

Review: fix(#4801) serialize gRPC streaming terminal calls

Solid, well-scoped fix. The SynchronizedStreamObserver wrapper is a clean way to enforce the gRPC StreamObserver contract (single terminal, no onNext after terminal, serialized delivery), and the markTerminated() escape hatch for the cancel handler is the right idea since the transport has already closed the call. The mock-free unit test (including the 200x32 concurrency stress test racing writes/terminals/cancel) is exactly the kind of coverage this class of bug needs, and the red/green note is appreciated.

Main observation: the fix looks incomplete

insertStream (ArcadeDbGrpcService.java:1646) has the same TOCTOU cancel-vs-terminal race this PR fixes in the other two handlers, but it was left untouched:

call.setOnCancelHandler(() -> cancelled.set(true));
...
if (!cancelled.get()) {        // <-- cancellation can win between check and the calls below
  resp.onNext(ctx.summary(totals, startedAt));
  resp.onCompleted();
}
...
resp.onError(Status.INTERNAL.withDescription("insertStream: " + e.getMessage()).asException());

This is the identical if (!cancelled.get()) pattern the PR description calls out for graphBatchLoad. Since the PR frames the root cause as "gRPC StreamObserver is not thread-safe" generally, it would be worth either wrapping insertStream's resp in SynchronizedStreamObserver too (a 4-line change matching the others), or explicitly noting in the PR why it is considered safe/out of scope. Risk is lower than insertBidirectional since insertStream runs inline on the serialized gRPC inbound thread, but the cancel-handler race is real and identical in kind.

Code quality / correctness

  • The wrapper logic is correct. markTerminated() intentionally bypasses lock (just an AtomicBoolean flip), which is fine: a thread waiting on the monitor will fail the compareAndSet and skip delegation, and an onNext already past the completed.get() gate that races a concurrent markTerminated will at worst hit delegate.onNext after close, which throws IllegalStateException and is caught. Good.
  • Catching only IllegalStateException is the correct narrow choice (that is what gRPC throws on write-after-close); other runtime exceptions still propagate, which is desirable.
  • Minor: the onNext ISE-catch and markTerminated() both set completed = true but, unlike the terminal methods, record "terminated without ever delegating a terminal." That is the intended behavior (transport already closed), just worth a one-line comment on the onNext catch clarifying no terminal will subsequently be delegated by design.

Performance

Negligible: one monitor + one AtomicBoolean per stream, and writes on a single stream were already logically serialized. The lock is held across delegate.onNext, but gRPC's ServerCallStreamObserver.onNext is non-blocking (it buffers), so no contention concern. Consistent with the CLAUDE.md performance guidance.

Security

No concerns. No new dependencies, no change to auth/credential paths, error messages unchanged.

Test coverage

Strong for the wrapper in isolation. Two suggestions:

  • The concurrency test asserts no contract violations but does not assert that at least one terminal is eventually delegated when no markTerminated ran first; consider a deterministic case asserting exactly-one terminal reaches the delegate in the no-cancel path (duplicateTerminalCallsAreCollapsedToOne partly covers this).
  • An integration-level test that actually cancels mid-stream against the real handler would close the loop on the originally reported IllegalStateException (the cited GrpcServerIT#graphBatchLoadVerticesAndEdges only exercises the happy path).

Overall: good fix, good tests. The main actionable item is deciding whether insertStream should get the same treatment for consistency.

…tStream

Review feedback:
- gemini: gRPC can throw StatusRuntimeException (e.g. CANCELLED) on write/close
  after the transport closes the call, not only IllegalStateException. Widen the
  guarded delegate catch blocks to a multi-catch.
- claude: insertStream had the identical TOCTOU cancel-vs-terminal race; wrap its
  response observer in SynchronizedStreamObserver too for consistency.
- Add a happy-path test asserting exactly one terminal reaches the delegate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@robfrank

Copy link
Copy Markdown
Collaborator Author

Thanks for the reviews. Addressed in f785c9d:

  • @gemini-code-assist: widened the three guarded delegate catch blocks to also catch io.grpc.StatusRuntimeException (e.g. CANCELLED) via multi-catch, with an explicit import (no fully-qualified names per project style).
  • @claude: insertStream had the identical TOCTOU cancel-vs-terminal race, so it now wraps its response observer in SynchronizedStreamObserver too (cancel handler + onError + onCompleted paths). Added happyPathDeliversExactlyOneTerminalToDelegate asserting exactly one terminal reaches the delegate on the no-cancel path.

Verified: Issue4801SynchronizedStreamObserverTest 6/6, and GrpcServerIT#graphBatchLoadVerticesAndEdges + Issue4198InsertStreamCommitErrorIT pass end-to-end.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Thanks for the update, @robfrank. The inclusion of insertStream in the SynchronizedStreamObserver wrapper and the addition of the happyPathDeliversExactlyOneTerminalToDelegate test case provide the necessary consistency and coverage to resolve the race condition fully. The implementation looks solid and addresses the observations raised.

@claude

claude Bot commented Jun 30, 2026

Copy link
Copy Markdown

Review: PR #4818 - serialize gRPC streaming terminal calls

Thanks for the careful writeup and the red/green-verified tests. The core design is sound and the fix directly addresses the TOCTOU if (!cancelled.get()) races in graphBatchLoad, insertStream, and insertBidirectional. A few notes below.

Strengths

  • SynchronizedStreamObserver is a clean, minimal abstraction. The two-layer guard is the right model: the synchronized(lock) monitor serializes the delegate call sequence (gRPC requires ordered onNext* then a single terminal, not just the flag flipped), and the AtomicBoolean completed CAS enforces at-most-one terminal.
  • Keeping markTerminated() lock-free (plain set(true), no monitor) is a good call: the transport cancel handler must not block behind an in-flight delegate.onNext(). Worth a one-line comment making that intent explicit, since it's the one deliberate deviation from "everything goes through the lock."
  • Widening the catch to StatusRuntimeException as well as IllegalStateException (cycle-1 feedback) is correct - gRPC genuinely throws CANCELLED/StatusRuntimeException on write-after-close, not just ISE.
  • Test coverage is strong: the 200x32 racing test plus the contract-enforcing delegate is exactly the right shape to catch interleaving regressions, and the happy-path "exactly one terminal" assertion guards against over-suppression.

Observations / possible follow-ups (non-blocking)

  1. The query-streaming path still uses the old pattern. executeQuery -> streamMaterialized/streamCursor/streamPaged push via safeOnNext(scso, cancelled, ...) (~line 1587), the same TOCTOU if (cancelled.get()) + raw scso.onNext shape that gRPC insertBidirectional / graphBatchLoad call terminal onNext/onError/onCompleted on a non-thread-safe StreamObserver from multiple threads #4801 is fixing. It's partially self-healing because safeOnNext catches StatusRuntimeException(CANCELLED) and sets cancelled, but the terminal onCompleted in executeQuery isn't funneled through anything equivalent. Since it's the same bug class, consider routing that path through SynchronizedStreamObserver too, or adding a comment explaining why it's safe (single producer thread + self-healing catch). Out of scope here, but it leaves the codebase inconsistent.

  2. onNext's swallow path silently drops data without a terminal. When delegate.onNext throws, the wrapper sets completed=true and returns with no terminal delegated (correct - transport already closed). Intentional, but an IllegalStateException from a genuine bug (not a transport close) would be swallowed identically to a normal cancel. A LogManager debug/trace on that swallow would aid future diagnosis without changing behavior. Minor.

  3. isTerminated() is test-only. Fine as package-private, just flagging it's unused in production.

  4. Redundant errorSent[0] bookkeeping in graphBatchLoad. Now that completed tracks terminal state, errorSent only still matters for the call.request(1) flow-control gate. Not worth changing, but a sentence noting why both exist would stop a future reader from "simplifying" it away.

Style / conventions

Aligns with CLAUDE.md: final on fields/params, classes imported (no FQNs), AssertJ assertThat(...).isTrue() style, Apache headers present, no new dependencies, tests added. Commit/PR correctly credit Claude as co-author rather than source author.

Verdict

Looks good to merge. The fix is correct and well-tested; the items above are follow-up hygiene rather than blockers. The one to keep on the radar is #1 - the query-streaming terminal path is the remaining instance of the same race class.

Review (cycle 2) clarity-only follow-ups: document why markTerminated() is
deliberately lock-free (cancel handler must not block behind an in-flight
onNext), and note that graphBatchLoad's errorSent flag only gates the
onCompleted flush and flow-control pull while SynchronizedStreamObserver
independently guarantees terminal-call safety. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@robfrank

Copy link
Copy Markdown
Collaborator Author

Thanks for the cycle-2 pass. Addressed the clarity items in cfe87b4 (comment-only, no behavior change):

  • Documented why markTerminated() is deliberately lock-free (cancel handler must not block behind an in-flight onNext).
  • Added a note on graphBatchLoad's errorSent flag so a future reader does not "simplify" it away (it gates the onCompleted flush + flow-control pull; terminal-call safety is now owned by the wrapper).

On the non-blocking follow-ups:

  • executeQuery / streamMaterialized-Cursor-Paged (build support #1): kept out of scope intentionally. That path runs on a single producer thread and already routes writes through safeOnNext, which catches StatusRuntimeException(CANCELLED) and self-heals. Converting it to SynchronizedStreamObserver is the same bug class but a distinct, hot query path beyond this issue's two named handlers (+ insertStream, which shares the exact client-streaming terminal shape). Better as a dedicated follow-up so this PR stays reviewable and scoped.
  • onNext swallow trace-log (Bump gremlin.version from 3.4.10 to 3.5.1 #2) and isTerminated() being test-only (Bump slf4j-simple.version from 1.7.31 to 1.7.32 #3): noted; leaving as-is to avoid adding logging/visibility surface to a hot path for a no-behavior-change PR.

Verified after the change: grpcw test-compile clean; unit + the two ITs unchanged.

@claude

claude Bot commented Jun 30, 2026

Copy link
Copy Markdown

Code Review - PR #4818 (fix #4801: serialize gRPC streaming terminal calls)

Reviewed the new SynchronizedStreamObserver, the three handler call sites (insertStream, graphBatchLoad, insertBidirectional), the unit suite, and the design doc. This is a well-scoped, correct fix for a real TOCTOU bug. Overall in good shape. Notes below.

Strengths

  • Right diagnosis, right fix. The if (!cancelled.get()) guard followed by a separate onNext/onCompleted was a textbook check-then-act race against the cancel handler. Funneling all write/terminal calls through one monitor plus a single completed CAS is the correct and minimal way to enforce the StreamObserver contract.
  • Lock-free markTerminated() is the right call and the Javadoc explaining why (the transport cancel handler must not block behind an in-flight delegate.onNext() holding lock) is exactly the kind of reasoning that prevents a future "simplification" from reintroducing the bug. The "races at worst into delegate.onNext after close, which throws and is caught" argument holds.
  • Catching both IllegalStateException and StatusRuntimeException is correct - gRPC can surface a CANCELLED/StatusRuntimeException rather than ISE depending on the close path.
  • Strong tests. Mock-free, contract-emulating delegate, the 200x32 stress test, the happy-path "exactly one terminal" assertion, and the documented red/green check against a naive pass-through wrapper. Coverage of the relevant branches (drop-after-terminal, duplicate-terminal collapse, markTerminated, swallow-on-throw) is good.
  • Follows repo conventions: final on params/locals, assertThat(...).isTrue() style, Apache headers, the docs/<issue>-*.md note convention, no new dependencies, Claude not credited as source author.

Points worth a look

  1. onNext swallowing StatusRuntimeException then marking terminated (possible silent hang in a rare case). In onNext, any StatusRuntimeException from delegate.onNext sets completed = true and silently drops the rest of the stream including the would-be terminal. For the common case (call already closed/cancelled) this is correct - the client is gone. But if delegate.onNext ever throws a non-fatal StatusRuntimeException (e.g. a per-message serialization / RESOURCE_EXHAUSTED failure on an otherwise-live call), the wrapper terminates the stream without ever delivering onError/onCompleted, and the client could hang. Swallowing in the two terminal methods is unambiguously safe; swallowing in onNext is slightly more aggressive. Low risk in practice, but consider either delivering an onError on that path, or commenting the intent that any onNext throw is treated as "call is dead." Not a blocker.

  2. insertBidirectional half-close path is unchanged and still delivers no terminal. onCompleted() (client half-close without a COMMIT) rolls back and shuts the executor down but never calls out.onCompleted()/onError. Pre-existing and out of scope for this fix, but now that out exists it would be safe to close the response side here too. Worth a follow-up if a half-close-without-commit can leave the response stream un-terminated.

  3. Minor - onNext uses completed.get() (non-CAS) while terminals use CAS. Correct because the shared lock mutually excludes onNext from the terminal methods, so the plain read is sufficient. Just flagging that safety depends entirely on the monitor; the AtomicBoolean is doing volatile-visibility duty for the lock-free markTerminated/onNext-gate reads rather than providing atomicity. The current code is right - a "keep it that way" note.

  4. Test gap (minor). The ContractEnforcingObserver models a delegated terminal as the thing that closes the delegate, but markTerminated() does not close it. So the lock-free race of markTerminated flipping completed while an onNext is mid-flight against a throwing delegate isn't directly exercised in one test - it is covered indirectly by delegateThrowingOnConcurrentCloseIsSwallowedAndTerminates. Coverage is adequate; just noting the stress test's delegate is slightly more lenient than real gRPC on the markTerminated path.

Performance / security

  • Overhead is one monitor acquire per outbound call plus one AtomicBoolean per stream, as stated. The serialized streams (insertBidirectional single-threaded executor; client-streaming inbound thread) are effectively single-producer, so monitor contention is negligible. No GC pressure concerns. delegate.onNext is assumed non-blocking under gRPC buffering, matching the existing code's assumption.
  • No security surface change.

Nice work - the fix is correct, the rationale is well documented in code, and the regression coverage is solid. Item #1 is the only one I'd consider acting on before merge; #2 is a good follow-up.

Review (cycle 3): when delegate.onNext throws, the wrapper previously marked
itself terminated without delivering any terminal. For an already-closed call
that is correct, but a still-live call that rejects a single message (e.g.
RESOURCE_EXHAUSTED) would leave the client hanging. onNext now best-effort
delivers onError on that path (compareAndSet skips it if markTerminated already
fired; an already-closed call swallows the no-op onError). Adds a regression
test for the live-but-rejecting-write path. Unit suite 7/7.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@robfrank

Copy link
Copy Markdown
Collaborator Author

Thanks - acted on item #1 in 0f89c86. onNext now best-effort delivers onError when a write throws: compareAndSet skips it if a concurrent markTerminated (cancel handler) already fired, and an already-closed call swallows the no-op onError. So a still-live call that rejects a single message no longer leaves the client without a terminal. Added failedWriteOnLiveCallDeliversTerminalSoClientDoesNotHang (unit suite now 7/7).

Item #2 (insertBidirectional half-close-without-COMMIT delivers no terminal) is pre-existing and left as a documented follow-up; #3/#4 are "keep it that way" notes, no change.

@claude

claude Bot commented Jun 30, 2026

Copy link
Copy Markdown

Review: fix(#4801) - serialize gRPC streaming terminal calls

Solid, well-scoped fix with an accurate root-cause analysis. The SynchronizedStreamObserver wrapper is a clean, minimal way to enforce the StreamObserver contract (at most one delegated terminal, no onNext after terminal), and the test suite is genuinely good: mock-free, contract-emulating delegate, a 32-thread x 200-iteration stress test, and documented red/green verification. The wrapper is applied consistently across all three multi-threaded streaming handlers (insertStream, graphBatchLoad, insertBidirectional). The per-issue docs/ note matches the repo convention.

Correctness - looks sound

  • The single-terminal guarantee holds: onError, onCompleted, and the onNext failure-recovery path all gate on the same completed.compareAndSet(false, true), while markTerminated() only flips the flag without delegating. At most one terminal can ever reach the delegate.
  • All delegate access is serialized under lock, so the delegate never sees concurrent calls; the only un-serialized state is the AtomicBoolean (volatile write/read), which is safe.
  • The lock-free markTerminated() is well reasoned and documented: the cancel handler must not block behind an in-flight delegate.onNext(), and the worst case (a write racing into an already-closed call) is caught.

Minor / discussion points (non-blocking)

  1. onNext recovery passes the raw caught exception to onError. In the write-failure branch, delegate.onError(failed) is invoked with an IllegalStateException or StatusRuntimeException. gRPC maps a non-Status throwable like IllegalStateException to UNKNOWN with no description. For a cleaner client-visible terminal, consider delivering a Status.CANCELLED/UNAVAILABLE (.asException()) instead of the raw throwable. Low priority since this is a best-effort path on an already-degraded call.

  2. Redundant gating now overlaps the wrapper. cancelled.get() (all three handlers) and errorSent[] (graphBatchLoad) still guard the terminal flushes, which the wrapper now also guarantees independently. The PR documents this intentionally (errorSent still gates call.request(1) flow control), so it is fine - just flagging that a later simplification pass could remove the now-defensive double-guards on the pure terminal calls.

  3. streamQuery/executeQuery left out of scope. Reasonable: that path is single-producer-thread and safeOnNext already self-heals on StatusRuntimeException(CANCELLED). Worth keeping the follow-up tracked, since safeOnNext re-throws non-CANCELLED StatusRuntimeException and does not catch IllegalStateException - if that path ever dispatches to an executor it inherits the same bug class.

  4. insertBidirectional half-close-without-COMMIT delivering no terminal is acknowledged as pre-existing and deferred. Agreed that is a separate issue, but it does mean a client that half-closes mid-session still hangs; good to land the follow-up before declaring 4801 fully closed.

Style / conventions

  • Package-private final class, final params/fields throughout, AssertJ assertThat(...) style - all consistent with CLAUDE.md.
  • No new dependencies; negligible per-stream overhead (one monitor + one AtomicBoolean).

Note: I reviewed statically and did not rebuild locally; the PR documents the unit suite (7/7) and GrpcServerIT/Issue4198InsertStreamCommitErrorIT passing end-to-end.

Overall: LGTM. The thread-safety guarantee is correct and the test coverage backing it is strong. The points above are refinements, not blockers.

@robfrank

Copy link
Copy Markdown
Collaborator Author

Thanks for the LGTM. Noting the cycle-4 refinements for the record:

  • build support #1 (deliver a Status.CANCELLED/UNAVAILABLE.asException() instead of the raw throwable on the best-effort onNext-failure path): agreed it would give a cleaner client-visible terminal. Since it is explicitly low-priority on an already-degraded path and the PR is at its review-cycle budget with no blockers, I am leaving the current best-effort onError(failed) as-is rather than pushing an unreviewed change post-approval; happy to fold it in if a maintainer wants it before merge.
  • Bump gremlin.version from 3.4.10 to 3.5.1 #2/Bump slf4j-simple.version from 1.7.31 to 1.7.32 #3 (executeQuery/streamQuery path; insertBidirectional half-close-without-COMMIT): tracked as follow-ups, as discussed - both pre-existing and outside this issue's three named/equivalent handlers.
  • defensive double-guards (cancelled/errorSent): intentionally retained; documented in code.

Final state: unit suite 7/7, GrpcServerIT#graphBatchLoadVerticesAndEdges + Issue4198InsertStreamCommitErrorIT green. Ready for maintainer review/merge.

@codecov

codecov Bot commented Jun 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.11765% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.18%. Comparing base (61d0b69) to head (0f89c86).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
.../com/arcadedb/server/grpc/ArcadeDbGrpcService.java 46.87% 17 Missing ⚠️
...cadedb/server/grpc/SynchronizedStreamObserver.java 88.88% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #4818      +/-   ##
============================================
- Coverage     65.19%   65.18%   -0.02%     
+ Complexity      716      715       -1     
============================================
  Files          1680     1681       +1     
  Lines        133245   133293      +48     
  Branches      28482    28486       +4     
============================================
+ Hits          86867    86881      +14     
- Misses        34435    34465      +30     
- Partials      11943    11947       +4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@robfrank
robfrank merged commit f0ef7f0 into main Jun 30, 2026
25 of 30 checks passed
@robfrank
robfrank deleted the fix/4801-grpc-streamobserver-thread-safety branch June 30, 2026 12:43
mergify Bot added a commit that referenced this pull request Jul 29, 2026
…io with 2 updates [skip ci]

Bumps the build-tools group in /studio with 2 updates: [webpack](https://github.com/webpack/webpack) and [webpack-cli](https://github.com/webpack/webpack-cli).
Updates `webpack` from 5.109.0 to 5.109.2
Release notes

*Sourced from [webpack's releases](https://github.com/webpack/webpack/releases).*

> v5.109.2
> --------
>
> ### Patch Changes
>
> * Resolve aliases pointing at a package directory whose name ends with `.js` again. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21542](https://redirect.github.com/webpack/webpack/pull/21542))
> * Name CSS sources in source maps by their resource path, without the `css`  prefix. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21536](https://redirect.github.com/webpack/webpack/pull/21536))
> * Delete no longer referenced files from the filesystem cache directory after storing the cache, age them by recorded time so restored caches are cleaned too, and collect every fully expired pack in one store instead of one per build. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21528](https://redirect.github.com/webpack/webpack/pull/21528))
> * Report `"universal"` as the loader context target for the universal target. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21540](https://redirect.github.com/webpack/webpack/pull/21540))
> * Skip `require().prop` in dead branches gated by inlined imported constants. (by [`@​hai-x`](https://github.com/hai-x) in [#21517](https://redirect.github.com/webpack/webpack/pull/21517))
> * Annotate configuration options and public hooks in the generated types with the `@since` JSDoc tag. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21473](https://redirect.github.com/webpack/webpack/pull/21473))
>
> v5.109.1
> --------
>
> ### Patch Changes
>
> * Fix stray semicolon emitted before an imported call following a parenthesized sequence element. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21533](https://redirect.github.com/webpack/webpack/pull/21533))
> * Make `require(esm)` `module.exports` re-export analysis independent of module processing order. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21521](https://redirect.github.com/webpack/webpack/pull/21521))
> * Ignore ERR\_SERVER\_NOT\_RUNNING on lazy-compilation backend dispose so `compiler.close()` succeeds on Bun. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21521](https://redirect.github.com/webpack/webpack/pull/21521))
> * Name the failing key when DefinePlugin fails to evaluate a `typeof` value. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21503](https://redirect.github.com/webpack/webpack/pull/21503))
> * Improve Deno compatibility: guard `setNoDelay` and force-close connections on lazy-compilation backend dispose, and return a real `ArrayBuffer` from the Node async/sync wasm loader so `WebAssembly.instantiate` accepts it. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21524](https://redirect.github.com/webpack/webpack/pull/21524))
> * Speed up the HTML parser and cut its peak memory: module-scope helpers/state and tokenizer callbacks, plus exact AST column pre-sizing. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21492](https://redirect.github.com/webpack/webpack/pull/21492))
> * Track CommonJS build dependencies by parsing sources when `require.cache` children are unavailable (e.g. Bun). (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21531](https://redirect.github.com/webpack/webpack/pull/21531))
> * Cook common string-literal escapes on the JS parser fast path and own the tokenizer's cold-path readers. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21500](https://redirect.github.com/webpack/webpack/pull/21500))
> * Build the CSS `parseA*` AST on the SoA store instead of node classes, cutting parse memory and time. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21498](https://redirect.github.com/webpack/webpack/pull/21498))
> * Speed up and cut memory of the experimental CSS and HTML parsers: drop two derivable AST node columns, and scan long string, url, comment, and plaintext token bodies natively. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21504](https://redirect.github.com/webpack/webpack/pull/21504))
> * Speed up non-modules CSS parsing: skip redundant token re-reads, drop selector-prelude tokens without materializing nodes, allocate rule preludes lazily, and fast-path empty list seals. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21511](https://redirect.github.com/webpack/webpack/pull/21511))
> * Speed up stats generation and cut its peak memory: reuse cached sort comparators instead of thrashing the comparator caches on every sort, and drop redundant module-graph lookups and allocations in the extractors. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21506](https://redirect.github.com/webpack/webpack/pull/21506))
> * Speed up CSS parsing: byte-range function-name checks, indexed sibling lookahead. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21520](https://redirect.github.com/webpack/webpack/pull/21520))
> * Reduce allocations and redundant work across the code-generation, module-concatenation, exports/usage-analysis, hashing, and chunk-splitting hot paths. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21516](https://redirect.github.com/webpack/webpack/pull/21516))
> * Enable the Node.js compile cache in the webpack CLI entry point. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21523](https://redirect.github.com/webpack/webpack/pull/21523))
> * Encode the persistent cache with V8's value serializer. (by [`@​avivkeller`](https://github.com/avivkeller) in [#21514](https://redirect.github.com/webpack/webpack/pull/21514))

... (truncated)


Changelog

*Sourced from [webpack's changelog](https://github.com/webpack/webpack/blob/main/CHANGELOG.md).*

> 5.109.2
> -------
>
> ### Patch Changes
>
> * Resolve aliases pointing at a package directory whose name ends with `.js` again. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21542](https://redirect.github.com/webpack/webpack/pull/21542))
> * Name CSS sources in source maps by their resource path, without the `css`  prefix. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21536](https://redirect.github.com/webpack/webpack/pull/21536))
> * Delete no longer referenced files from the filesystem cache directory after storing the cache, age them by recorded time so restored caches are cleaned too, and collect every fully expired pack in one store instead of one per build. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21528](https://redirect.github.com/webpack/webpack/pull/21528))
> * Report `"universal"` as the loader context target for the universal target. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21540](https://redirect.github.com/webpack/webpack/pull/21540))
> * Skip `require().prop` in dead branches gated by inlined imported constants. (by [`@​hai-x`](https://github.com/hai-x) in [#21517](https://redirect.github.com/webpack/webpack/pull/21517))
> * Annotate configuration options and public hooks in the generated types with the `@since` JSDoc tag. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21473](https://redirect.github.com/webpack/webpack/pull/21473))
>
> 5.109.1
> -------
>
> ### Patch Changes
>
> * Fix stray semicolon emitted before an imported call following a parenthesized sequence element. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21533](https://redirect.github.com/webpack/webpack/pull/21533))
> * Make `require(esm)` `module.exports` re-export analysis independent of module processing order. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21521](https://redirect.github.com/webpack/webpack/pull/21521))
> * Ignore ERR\_SERVER\_NOT\_RUNNING on lazy-compilation backend dispose so `compiler.close()` succeeds on Bun. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21521](https://redirect.github.com/webpack/webpack/pull/21521))
> * Name the failing key when DefinePlugin fails to evaluate a `typeof` value. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21503](https://redirect.github.com/webpack/webpack/pull/21503))
> * Improve Deno compatibility: guard `setNoDelay` and force-close connections on lazy-compilation backend dispose, and return a real `ArrayBuffer` from the Node async/sync wasm loader so `WebAssembly.instantiate` accepts it. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21524](https://redirect.github.com/webpack/webpack/pull/21524))
> * Speed up the HTML parser and cut its peak memory: module-scope helpers/state and tokenizer callbacks, plus exact AST column pre-sizing. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21492](https://redirect.github.com/webpack/webpack/pull/21492))
> * Track CommonJS build dependencies by parsing sources when `require.cache` children are unavailable (e.g. Bun). (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21531](https://redirect.github.com/webpack/webpack/pull/21531))
> * Cook common string-literal escapes on the JS parser fast path and own the tokenizer's cold-path readers. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21500](https://redirect.github.com/webpack/webpack/pull/21500))
> * Build the CSS `parseA*` AST on the SoA store instead of node classes, cutting parse memory and time. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21498](https://redirect.github.com/webpack/webpack/pull/21498))
> * Speed up and cut memory of the experimental CSS and HTML parsers: drop two derivable AST node columns, and scan long string, url, comment, and plaintext token bodies natively. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21504](https://redirect.github.com/webpack/webpack/pull/21504))
> * Speed up non-modules CSS parsing: skip redundant token re-reads, drop selector-prelude tokens without materializing nodes, allocate rule preludes lazily, and fast-path empty list seals. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21511](https://redirect.github.com/webpack/webpack/pull/21511))
> * Speed up stats generation and cut its peak memory: reuse cached sort comparators instead of thrashing the comparator caches on every sort, and drop redundant module-graph lookups and allocations in the extractors. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21506](https://redirect.github.com/webpack/webpack/pull/21506))
> * Speed up CSS parsing: byte-range function-name checks, indexed sibling lookahead. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21520](https://redirect.github.com/webpack/webpack/pull/21520))
> * Reduce allocations and redundant work across the code-generation, module-concatenation, exports/usage-analysis, hashing, and chunk-splitting hot paths. (by [`@​alexander-akait`](https://github.com/alexander-akait) in [#21516](https://redirect.github.com/webpack/webpack/pull/21516))
> * Enable the Node.js compile cache in the webpack CLI entry point. (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#21523](https://redirect.github.com/webpack/webpack/pull/21523))

... (truncated)


Commits

* [`6a24bd6`](webpack/webpack@6a24bd6) chore(release): new release ([#21534](https://redirect.github.com/webpack/webpack/issues/21534))
* [`d1b5b6d`](webpack/webpack@d1b5b6d) fix: resolve aliases pointing at a package directory ending in .js ([#21542](https://redirect.github.com/webpack/webpack/issues/21542))
* [`9cdcc57`](webpack/webpack@9cdcc57) fix(target): report "universal" as the loader target ([#21540](https://redirect.github.com/webpack/webpack/issues/21540))
* [`774e7e4`](webpack/webpack@774e7e4) feat: annotate schema options with added keywords ([#21473](https://redirect.github.com/webpack/webpack/issues/21473))
* [`ff07bdc`](webpack/webpack@ff07bdc) fix(css): name CSS sources in source maps by their resource path ([#21536](https://redirect.github.com/webpack/webpack/issues/21536))
* [`d56d82d`](webpack/webpack@d56d82d) fix(cache): reclaim stale filesystem cache files reliably ([#21539](https://redirect.github.com/webpack/webpack/issues/21539))
* [`ae67e2a`](webpack/webpack@ae67e2a) chore(readme): add codspeed ([#21497](https://redirect.github.com/webpack/webpack/issues/21497))
* [`964bbfa`](webpack/webpack@964bbfa) fix: delete no longer referenced files from the filesystem cache directory (#...
* [`075d0cd`](webpack/webpack@075d0cd) feat: skip `require().prop` in dead branches ([#21517](https://redirect.github.com/webpack/webpack/issues/21517))
* [`ec39088`](webpack/webpack@ec39088) chore(release): new release ([#21493](https://redirect.github.com/webpack/webpack/issues/21493))
* Additional commits viewable in [compare view](webpack/webpack@v5.109.0...v5.109.2)
  
Updates `webpack-cli` from 7.2.1 to 7.2.2
Release notes

*Sourced from [webpack-cli's releases](https://github.com/webpack/webpack-cli/releases).*

> webpack-cli@7.2.2
> -----------------
>
> ### Patch Changes
>
> * perf: enable the Node.js compile cache (`module.enableCompileCache`, available on Node.js >= 22.8.0) to speed up CLI startup (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#4818](https://redirect.github.com/webpack/webpack-cli/pull/4818))


Changelog

*Sourced from [webpack-cli's changelog](https://github.com/webpack/webpack-cli/blob/main/CHANGELOG.md).*

> 7.2.2
> -----
>
> ### Patch Changes
>
> * perf: enable the Node.js compile cache (`module.enableCompileCache`, available on Node.js >= 22.8.0) to speed up CLI startup (by [`@​bjohansebas`](https://github.com/bjohansebas) in [#4818](https://redirect.github.com/webpack/webpack-cli/pull/4818))


Commits

* [`191fa9f`](webpack/webpack-cli@191fa9f) chore(release): new release ([#4820](https://redirect.github.com/webpack/webpack-cli/issues/4820))
* [`1082235`](webpack/webpack-cli@1082235) chore(deps-dev): bump js-yaml from 5.2.1 to 5.2.2 ([#4821](https://redirect.github.com/webpack/webpack-cli/issues/4821))
* [`e36ae82`](webpack/webpack-cli@e36ae82) chore: add publish workflow and script for pkg.pr.new integration ([#4819](https://redirect.github.com/webpack/webpack-cli/issues/4819))
* [`b0a2024`](webpack/webpack-cli@b0a2024) perf: enable the Node.js compile cache ([#4818](https://redirect.github.com/webpack/webpack-cli/issues/4818))
* [`53f6d72`](webpack/webpack-cli@53f6d72) chore(deps): bump actions/checkout in the dependencies group ([#4816](https://redirect.github.com/webpack/webpack-cli/issues/4816))
* [`8856346`](webpack/webpack-cli@8856346) chore: add allowscripts to work with npm 12 ([#4811](https://redirect.github.com/webpack/webpack-cli/issues/4811))
* [`0b0f1ee`](webpack/webpack-cli@0b0f1ee) chore(deps): bump fast-uri from 3.1.2 to 3.1.4 ([#4815](https://redirect.github.com/webpack/webpack-cli/issues/4815))
* [`d60a777`](webpack/webpack-cli@d60a777) chore(deps-dev): bump postcss from 8.5.10 to 8.5.22 ([#4814](https://redirect.github.com/webpack/webpack-cli/issues/4814))
* [`8c1719a`](webpack/webpack-cli@8c1719a) chore(deps): bump shell-quote from 1.8.4 to 1.10.0 ([#4813](https://redirect.github.com/webpack/webpack-cli/issues/4813))
* [`8c2473c`](webpack/webpack-cli@8c2473c) chore(deps): bump immutable from 5.1.5 to 5.1.9 ([#4812](https://redirect.github.com/webpack/webpack-cli/issues/4812))
* Additional commits viewable in [compare view](https://github.com/webpack/webpack-cli/compare/webpack-cli@7.2.1...webpack-cli@7.2.2)
  
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
Dependabot commands and options
  
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot show  ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore  major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself)
- `@dependabot ignore  minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself)
- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency
- `@dependabot unignore  ` will remove the ignore condition of the specified dependency and ignore conditions
robfrank added a commit that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

gRPC insertBidirectional / graphBatchLoad call terminal onNext/onError/onCompleted on a non-thread-safe StreamObserver from multiple threads

1 participant