From 2073c07d7d9fe282567f665d011232ccceee6b19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Knut=20Olav=20L=C3=B8ite?= Date: Thu, 5 Nov 2026 19:36:29 +0100 Subject: [PATCH 1/2] perf(spanner): make async query execution event-driven Asynchronous queries share a bounded background thread pool to read rows from query streams and dispatch them to application callbacks. Previously, each active query held onto a background thread for its entire lifetime, parking that thread whenever the query was waiting for more data from the server, waiting for a full row buffer to be drained, or paused by the application callback. Running many concurrent or paused queries could exhaust the shared thread pool and stall other queries waiting for an available worker thread. This change switches asynchronous query execution to an event-driven model so background threads are only used while actively moving buffered rows: - Event-driven row production: Background tasks read rows only while stream data is already buffered locally and space remains in the row queue, releasing the worker thread immediately whenever a query is waiting on the network, the row buffer is full, or consumption is paused. Incoming stream data, buffer consumption, and resume calls re-schedule row production as needed. - Serialized stream startup and consumption: Completes stream initialization before row production begins so underlying query iterators are never accessed concurrently across threads, while preserving startup error translation for queries that inline transaction creation. - Prompt cancellation and clean lifecycle termination: Delivers cancellation directly to paused or in-flight callbacks without requiring a separate resume call, closes underlying streams outside internal locks, and waits for all active tasks to finish before completing the result future and releasing executor resources. - Strict callback thread scoping and interrupt handling: Restricts cursor advancement and row reads in asynchronous mode to the active callback invocation thread, and cancels the query while preserving the thread interrupt status if a blocking list conversion is interrupted. --- .../cloud/spanner/AsyncResultSetImpl.java | 1022 ++++++++---- .../cloud/spanner/ForwardingStructReader.java | 10 +- ...ultSetImplLifecycleAndConcurrencyTest.java | 1269 +++++++++++++++ .../AsyncResultSetImplStreamingTest.java | 1363 +++++++++++++++++ .../cloud/spanner/AsyncResultSetImplTest.java | 707 ++++++++- .../spanner/AsyncResultSetImplTestUtil.java | 298 ++++ .../google/cloud/spanner/ReadAsyncTest.java | 206 +++ 7 files changed, 4464 insertions(+), 411 deletions(-) create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java index c13c306e21e4..f10b2b0d3695 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java @@ -21,38 +21,41 @@ import com.google.api.core.SettableApiFuture; import com.google.api.gax.core.ExecutorProvider; import com.google.cloud.spanner.AbstractReadContext.ListenableAsyncResultSet; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; +import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.spanner.v1.PartialResultSet; import com.google.spanner.v1.ResultSetMetadata; import com.google.spanner.v1.ResultSetStats; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.LinkedList; import java.util.List; -import java.util.concurrent.BlockingDeque; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ScheduledExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.concurrent.GuardedBy; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** Default implementation for {@link AsyncResultSet}. */ +@NullMarked class AsyncResultSetImpl extends ForwardingStructReader implements ListenableAsyncResultSet, AsyncResultSet.StreamMessageListener { private static final Logger log = Logger.getLogger(AsyncResultSetImpl.class.getName()); /** State of an {@link AsyncResultSetImpl}. */ - private enum State { + @VisibleForTesting + enum State { INITIALIZED, STREAMING_INITIALIZED, /** SYNC indicates that the {@link ResultSet} is used in sync pattern. */ @@ -76,12 +79,12 @@ private enum State { } static final int DEFAULT_BUFFER_SIZE = 10; + static final int MAX_BUFFERED_CHUNKS = 512; private static final int MAX_WAIT_FOR_BUFFER_CONSUMPTION = 10; - private static final SpannerException CANCELLED_EXCEPTION = - SpannerExceptionFactory.newSpannerException( - ErrorCode.CANCELLED, "This AsyncResultSet has been cancelled"); private final Object monitor = new Object(); + + @GuardedBy("monitor") private boolean closed; /** @@ -90,14 +93,25 @@ private enum State { */ private final ExecutorProvider executorProvider; - private final ListeningScheduledExecutorService service; + private final ScheduledExecutorService service; + + private final int maxBufferSize; + + @GuardedBy("monitor") + private final ArrayDeque buffer; + + @GuardedBy("monitor") + private boolean waitingForBufferSpace; + + @Nullable private volatile Struct currentRow; - private final BlockingDeque buffer; - private Struct currentRow; + private volatile boolean syncHasCurrentRow; /** Supplies the underlying synchronous {@link ResultSet} that will be producing the rows. */ private final Supplier delegateResultSet; + @VisibleForTesting @Nullable volatile ResultSet initializedDelegate; + /** * Callback invoked once when query execution begins or when the result set is closed without * starting, allowing callers (like {@link MultiUseReadOnlyTransaction}) to track query lifecycle. @@ -113,64 +127,110 @@ private enum State { @GuardedBy("monitor") private boolean delegateClosed; - @GuardedBy("monitor") - private Throwable supplierException; - /** * Any exception that occurs while executing the query and iterating over the result set will be * stored in this variable and propagated to the user through {@link #tryNext()}. */ - private volatile SpannerException executionException; + @GuardedBy("monitor") + @Nullable + private SpannerException executionException; + + @GuardedBy("monitor") + @Nullable + private SpannerException cancelledException; /** * Executor for callbacks. Regardless of the type of executor that is provided, the {@link * AsyncResultSetImpl} will ensure that at most 1 callback call will be active at any one time. */ + @GuardedBy("monitor") + @Nullable private Executor executor; + @GuardedBy("monitor") + @Nullable private ReadyCallback callback; /** * Listeners that will be called when the {@link AsyncResultSetImpl} has finished fetching all * rows and any underlying transaction or session can be closed. */ - private final Collection listeners = new LinkedList<>(); + @GuardedBy("monitor") + private final Collection listeners = new ArrayList<>(2); - private volatile State state = State.INITIALIZED; + @GuardedBy("monitor") + private State state = State.INITIALIZED; - /** This variable indicates that produce rows thread is initiated */ - private volatile boolean produceRowsInitiated; + /** Indicates whether InitiateStreamingRunnable is currently scheduled or executing. */ + @GuardedBy("monitor") + private boolean initiatingStreaming; + + /** Indicates whether the delegate dynamically supports non-blocking streaming notifications. */ + @GuardedBy("monitor") + private boolean streamingSupported; + + /** Indicates whether a task is currently scheduled or executing ProduceRowsRunnable. */ + @GuardedBy("monitor") + private boolean producerRunning; + + /** Indicates whether a producer wakeup has been requested while a producer task is running. */ + @GuardedBy("monitor") + private boolean producerWakeupRequested; + + /** Indicates whether produce rows has been initiated. */ + @GuardedBy("monitor") + private boolean produceRowsInitiated; /** - * This variable indicates whether all the results from the underlying result set have been read. + * Counts initial stream chunks without a resume token before {@link #produceRowsInitiated} flips + * to {@code true}, ensuring row production starts once {@link ResumableStreamIterator} exceeds + * {@link #MAX_BUFFERED_CHUNKS} even when {@code prefetchChunks} is larger. */ - private volatile boolean finished; - - private volatile SettableApiFuture result; + @GuardedBy("monitor") + private int initialChunksWithoutResumeToken; /** - * This variable indicates whether {@link #tryNext()} has returned {@link CursorState#DONE} or a - * {@link SpannerException}. + * Indicates whether the entire async result set lifecycle and cleanup have been completed (all + * rows processed/handled, callback done, future resolved, resources freed). */ - private volatile boolean cursorReturnedDoneOrException; + @GuardedBy("monitor") + private boolean completed; + + /** Indicates whether a task is currently scheduled or executing CallbackRunnable. */ + @GuardedBy("monitor") + private boolean callbackRunning; /** - * This variable is used to pause the producer when the {@link AsyncResultSet} is paused. The - * production of rows that are put into the buffer is only paused once the buffer is full. + * The thread currently executing {@link ReadyCallback#cursorReady(AsyncResultSet)}, or {@code + * null} when no callback invocation is in progress. Written only under {@link #monitor} by the + * callback thread itself; volatile allows lock-free self-thread checks in {@link + * #checkValidState()}. */ - private volatile CountDownLatch pausedLatch = new CountDownLatch(1); + @Nullable private volatile Thread callbackInvocationThread; /** - * This variable is used to pause the producer when the buffer is full and the consumer needs some - * time to catch up. + * This variable indicates whether all the results from the underlying result set have been read. */ - private volatile CountDownLatch bufferConsumptionLatch = new CountDownLatch(0); + @GuardedBy("monitor") + private boolean finished; + + @GuardedBy("monitor") + @Nullable + private SettableApiFuture result; /** - * This variable is used to pause the producer when all rows have been put into the buffer, but - * the consumer (the callback) has not yet received and processed all rows. + * This variable indicates whether {@link #tryNext()} has returned {@link CursorState#DONE} or a + * {@link SpannerException}. */ - private volatile CountDownLatch consumingLatch = new CountDownLatch(0); + @GuardedBy("monitor") + private boolean cursorReturnedDoneOrException; + + @VisibleForTesting + State getState() { + synchronized (monitor) { + return state; + } + } AsyncResultSetImpl(ExecutorProvider executorProvider, ResultSet delegate, int bufferSize) { this( @@ -193,7 +253,7 @@ private enum State { Runnable onStartOrClose) { this( executorProvider, - Suppliers.memoize(Preconditions.checkNotNull(delegate)), + new MemoizingSupplier(Preconditions.checkNotNull(delegate)), bufferSize, Preconditions.checkNotNull(onStartOrClose), /* delegateInitialized= */ false); @@ -206,12 +266,20 @@ private AsyncResultSetImpl( Runnable onStartOrClose, boolean delegateInitialized) { super(memoizedDelegate); + Preconditions.checkArgument(bufferSize > 0, "bufferSize must be > 0"); this.executorProvider = Preconditions.checkNotNull(executorProvider); this.delegateResultSet = memoizedDelegate; this.onStartOrClose = onStartOrClose; this.delegateInitialized = delegateInitialized; - this.service = MoreExecutors.listeningDecorator(executorProvider.getExecutor()); - this.buffer = new LinkedBlockingDeque<>(bufferSize); + this.service = executorProvider.getExecutor(); + this.maxBufferSize = bufferSize; + this.buffer = new ArrayDeque<>(Math.min(bufferSize, 1024)); + replaceDelegateSupplier(this::currentRowOrDelegate); + } + + private StructReader currentRowOrDelegate() { + Struct row = getCurrentCallbackRow(); + return row != null ? row : getOrInitializeDelegate(); } /** @@ -219,38 +287,18 @@ private AsyncResultSetImpl( * any necessary early-close reconciliation and start/close notifications. */ private ResultSet getOrInitializeDelegate() { + ResultSet delegate = initializedDelegate; + if (delegate != null) { + return delegate; + } try { - ResultSet delegate = invokeDelegateSupplier(); + delegate = delegateResultSet.get(); closeIfClosedBeforeInitialization(delegate); - return delegate; } finally { maybeNotifyStartOrClose(); } - } - - private ResultSet invokeDelegateSupplier() { - checkSupplierException(); - try { - return delegateResultSet.get(); - } catch (Throwable throwable) { - synchronized (monitor) { - supplierException = throwable; - } - throw throwable; - } - } - - private void checkSupplierException() { - synchronized (monitor) { - if (supplierException != null) { - if (supplierException instanceof RuntimeException) { - throw (RuntimeException) supplierException; - } else if (supplierException instanceof Error) { - throw (Error) supplierException; - } - throw SpannerExceptionFactory.asSpannerException(supplierException); - } - } + initializedDelegate = delegate; + return delegate; } private void closeIfClosedBeforeInitialization(ResultSet delegate) { @@ -289,12 +337,6 @@ private void maybeNotifyStartOrClose() { } } - boolean isUsed() { - synchronized (monitor) { - return state != State.INITIALIZED; - } - } - /** * Closes the {@link AsyncResultSet}. {@link #close()} is non-blocking and may be called multiple * times without side effects. An {@link AsyncResultSet} may be closed before all rows have been @@ -312,6 +354,8 @@ public void close() { } if (state == State.INITIALIZED || state == State.SYNC) { shouldCloseDelegate = true; + currentRow = null; + syncHasCurrentRow = false; } if (state == State.INITIALIZED) { shouldNotifyClose = true; @@ -356,36 +400,44 @@ public void removeListener(Runnable listener) { */ @Override public CursorState tryNext() throws SpannerException { + boolean shouldExecuteProducer = false; synchronized (monitor) { + Preconditions.checkState( + isInCallbackInvocation(), "tryNext may only be called from a DataReady callback."); if (state == State.CANCELLED) { + currentRow = null; cursorReturnedDoneOrException = true; - throw CANCELLED_EXCEPTION; + throw Preconditions.checkNotNull(cancelledException); } - if (buffer.isEmpty() && executionException != null) { - cursorReturnedDoneOrException = true; - throw executionException; - } - Preconditions.checkState( - this.callback != null, "tryNext may only be called after a callback has been set."); - Preconditions.checkState( - this.state == State.CONSUMING, - "tryNext may only be called from a DataReady callback. Current state: " - + this.state.name()); - - if (finished && buffer.isEmpty()) { - cursorReturnedDoneOrException = true; - return CursorState.DONE; + if (!buffer.isEmpty()) { + currentRow = buffer.removeFirst(); + if (waitingForBufferSpace && hasBufferBatchSpace()) { + waitingForBufferSpace = false; + shouldExecuteProducer = prepareScheduleProducerLocked(); + } + } else { + currentRow = null; + if (executionException != null) { + cursorReturnedDoneOrException = true; + throw executionException; + } else if (finished) { + cursorReturnedDoneOrException = true; + return CursorState.DONE; + } else { + return CursorState.NOT_READY; + } } } - if (!buffer.isEmpty()) { - // Set the next row from the buffer as the current row of the StructReader. - replaceDelegate(currentRow = buffer.pop()); - synchronized (monitor) { - bufferConsumptionLatch.countDown(); - } - return CursorState.OK; + if (shouldExecuteProducer) { + executeProducer(); } - return CursorState.NOT_READY; + return CursorState.OK; + } + + @GuardedBy("monitor") + private boolean hasBufferBatchSpace() { + int minAvailableSlots = Math.min(maxBufferSize / 2 + 1, MAX_WAIT_FOR_BUFFER_CONSUMPTION); + return maxBufferSize - buffer.size() >= minAvailableSlots; } private void closeDelegateResultSet() { @@ -399,8 +451,8 @@ private void closeDelegateResultSet() { if (shouldClose) { try { delegateResultSet.get().close(); - } catch (Throwable t) { - log.log(Level.FINE, "Ignoring error from closing delegate result set", t); + } catch (Throwable throwable) { + log.log(Level.FINE, "Ignoring error from closing delegate result set", throwable); } } } @@ -414,10 +466,8 @@ private class CallbackRunnable implements Runnable { public void run() { try { while (true) { + ReadyCallback callback; synchronized (monitor) { - if (cursorReturnedDoneOrException) { - break; - } if (state == State.CANCELLED) { // The callback should always get at least one chance to catch the CANCELLED // exception. It is however possible that the callback does not call tryNext(), and @@ -425,68 +475,71 @@ public void run() { // also stop, even though the callback has not seen the CANCELLED state. cursorReturnedDoneOrException = true; } + callback = Preconditions.checkNotNull(AsyncResultSetImpl.this.callback); + callbackInvocationThread = Thread.currentThread(); } CallbackResponse response; try { - response = callback.cursorReady(AsyncResultSetImpl.this); - } catch (Throwable e) { + response = + Preconditions.checkNotNull( + callback.cursorReady(AsyncResultSetImpl.this), + "CallbackResponse may not be null"); + } catch (Throwable throwable) { + boolean shouldCloseDelegate = true; synchronized (monitor) { - if (cursorReturnedDoneOrException - && state == State.CANCELLED - && e instanceof SpannerException - && ((SpannerException) e).getErrorCode() == ErrorCode.CANCELLED) { + currentRow = null; + callbackInvocationThread = null; + cursorReturnedDoneOrException = true; + if (state == State.CANCELLED && throwable == cancelledException) { // The callback did not catch the cancelled exception (which it should have), but // we'll keep the cancelled state. - return; + shouldCloseDelegate = false; + } else { + executionException = SpannerExceptionFactory.asSpannerException(throwable); } - executionException = SpannerExceptionFactory.asSpannerException(e); - cursorReturnedDoneOrException = true; + } + if (shouldCloseDelegate) { + closeDelegateResultSet(); } return; } + boolean shouldCloseDelegate = false; + boolean shouldReturn = false; synchronized (monitor) { - if (state == State.CANCELLED) { - if (cursorReturnedDoneOrException) { - return; - } - } else { - switch (response) { - case DONE: - state = State.DONE; - cursorReturnedDoneOrException = true; - return; - case PAUSE: - state = State.PAUSED; - // Make sure no-one else is waiting on the current pause latch and create a new - // one. - pausedLatch.countDown(); - pausedLatch = new CountDownLatch(1); - return; - case CONTINUE: - if (buffer.isEmpty()) { - // Call the callback once more if the entire result set has been processed but - // the callback has not yet received a CursorState.DONE or a CANCELLED error. - if (finished && !cursorReturnedDoneOrException) { - break; - } - state = State.RUNNING; - return; - } - break; - default: - throw new IllegalStateException("Unknown response: " + response); + currentRow = null; + callbackInvocationThread = null; + if (response == CallbackResponse.DONE || cursorReturnedDoneOrException) { + if (state != State.CANCELLED) { + state = State.DONE; } + cursorReturnedDoneOrException = true; + shouldCloseDelegate = true; + shouldReturn = true; + } else if (state == State.CANCELLED) { + // cancel() occurred concurrently during cursorReady() before tryNext() observed + // CANCELLED, and callback returned PAUSE or CONTINUE. Loop once more so the + // callback gets its one guaranteed chance to catch CANCELLED. + } else if (response == CallbackResponse.PAUSE) { + state = State.PAUSED; + shouldReturn = true; + } else if (buffer.isEmpty() && !finished && executionException == null) { + state = State.RUNNING; + shouldReturn = true; } } + if (shouldCloseDelegate) { + closeDelegateResultSet(); + } + if (shouldReturn) { + return; + } } } finally { synchronized (monitor) { - // Count down all latches that the producer might be waiting on. - consumingLatch.countDown(); - while (bufferConsumptionLatch.getCount() > 0L) { - bufferConsumptionLatch.countDown(); - } + callbackRunning = false; } + scheduleCallbackIfNecessary(); + checkCompletion(); } } } @@ -496,271 +549,464 @@ public void run() { /** * {@link ProduceRowsRunnable} reads data from the underlying {@link ResultSet}, places these in * the buffer and dispatches the {@link CallbackRunnable} when data is ready to be consumed. + * + *

For {@link StreamingResultSet} delegates, this task yields back to the executor whenever + * {@link StreamingResultSet#isDataAvailable()} returns {@code false} or the row buffer reaches + * {@link #maxBufferSize}, and is re-scheduled by {@link #onStreamMessage} or consumer drain. A + * task thread may still block synchronously on non-streaming {@link ResultSet} implementations or + * mid-stream retry backoff inside {@link ResumableStreamIterator}. */ private class ProduceRowsRunnable implements Runnable { @Override public void run() { - boolean stop = false; - boolean hasNext = false; - ResultSet delegate = null; try { + boolean isStreaming; synchronized (monitor) { - stop = shouldStopProducing(); - } - if (!stop) { - delegate = getOrInitializeDelegate(); - hasNext = delegate.next(); - } - } catch (Throwable e) { - synchronized (monitor) { - executionException = SpannerExceptionFactory.asSpannerException(e); - stop = true; + if (shouldStopProducer()) { + return; + } + producerWakeupRequested = false; + isStreaming = streamingSupported; } - } - try { - while (!stop && hasNext && delegate != null) { - try { + ResultSet delegate = getOrInitializeDelegate(); + while (true) { + if (!isDataAvailable(delegate)) { synchronized (monitor) { - stop = shouldStopProducing(); + if (producerWakeupRequested && !shouldStopProducer()) { + producerWakeupRequested = false; + continue; + } } - if (!stop) { - while (buffer.remainingCapacity() == 0 && !stop) { - waitIfPaused(); - // The buffer is full and we should let the callback consume a number of rows before - // we proceed with producing any more rows to prevent us from potentially waiting on - // a full buffer repeatedly. - // Wait until at least half of the buffer is available, or if it's a bigger buffer, - // wait until at least 10 rows can be placed in it. - // TODO: Make this more dynamic / configurable? - startCallbackWithBufferLatchIfNecessary( - Math.min( - Math.min(buffer.size() / 2 + 1, buffer.size()), - MAX_WAIT_FOR_BUFFER_CONSUMPTION)); - bufferConsumptionLatch.await(); - synchronized (monitor) { - stop = shouldStopProducing(); - } + break; + } + boolean hasNext = delegate.next(); + if (hasNext) { + Struct row = delegate.getCurrentRowAsStruct(); + boolean shouldScheduleCallback; + synchronized (monitor) { + buffer.addLast(row); + if (buffer.size() >= maxBufferSize) { + waitingForBufferSpace = true; + break; } + if (shouldStopProducer()) { + break; + } + producerWakeupRequested = false; + shouldScheduleCallback = + !callbackRunning && (!isStreaming || buffer.size() >= DEFAULT_BUFFER_SIZE); } - if (!stop) { - buffer.put(delegate.getCurrentRowAsStruct()); - startCallbackIfNecessary(); - hasNext = delegate.next(); + if (shouldScheduleCallback) { + scheduleCallbackIfNecessary(); + synchronized (monitor) { + if (shouldStopProducer()) { + break; + } + } } - } catch (Throwable e) { + } else { + closeDelegateResultSet(); synchronized (monitor) { - executionException = SpannerExceptionFactory.asSpannerException(e); - stop = true; + finished = true; } + break; } } - // We don't need any more data from the underlying result set, so we close it as soon as - // possible. Any error that might occur during this will be ignored. - closeDelegateResultSet(); - - // Ensure that the callback has been called at least once, even if the result set was - // cancelled. + scheduleCallbackIfNecessary(); + } catch (Throwable throwable) { synchronized (monitor) { - finished = true; - stop = cursorReturnedDoneOrException; - } - // Call the callback if there are still rows in the buffer that need to be processed. - while (!stop) { - try { - waitIfPaused(); - startCallbackIfNecessary(); - // Make sure we wait until the callback runner has actually finished. - consumingLatch.await(); - synchronized (monitor) { - stop = cursorReturnedDoneOrException; - } - } catch (Throwable e) { - result.setException(e); - return; - } + setExecutionExceptionLocked(throwable); } + closeDelegateResultSet(); + scheduleCallbackIfNecessary(); } finally { - if (executorProvider.shouldAutoClose()) { - service.shutdown(); - } - List listenersToNotify = Collections.emptyList(); + boolean shouldExecuteProducer = false; synchronized (monitor) { - if (!listeners.isEmpty()) { - listenersToNotify = new ArrayList<>(listeners); + producerRunning = false; + if (producerWakeupRequested) { + producerWakeupRequested = false; + shouldExecuteProducer = prepareScheduleProducerLocked(); } } - for (Runnable listener : listenersToNotify) { - listener.run(); - } - synchronized (monitor) { - if (executionException != null) { - result.setException(executionException); - } else if (state == State.CANCELLED) { - result.setException(CANCELLED_EXCEPTION); - } else { - result.set(null); - } + if (shouldExecuteProducer) { + executeProducer(); } + checkCompletion(); } } + } + + private final ProduceRowsRunnable produceRowsRunnable = new ProduceRowsRunnable(); + + private static boolean isDataAvailable(ResultSet delegate) { + try { + return StreamingUtil.isDataAvailable(delegate); + } catch (Throwable throwable) { + // Returning true ensures that any exception encountered while checking for available data is + // not swallowed. The producer will proceed to invoke next(), where the exception is caught, + // recorded in executionException, and propagated to the caller. + return true; + } + } + + @GuardedBy("monitor") + private void setExecutionExceptionLocked(Throwable throwable) { + if (executionException == null && !state.shouldStop) { + executionException = SpannerExceptionFactory.asSpannerException(throwable); + } + } + + @GuardedBy("monitor") + private boolean shouldStopProducer() { + return finished + || cursorReturnedDoneOrException + || state.shouldStop + || state == State.PAUSED + || executionException != null; + } + + @GuardedBy("monitor") + private boolean canScheduleProducer() { + return !initiatingStreaming + && produceRowsInitiated + && !shouldStopProducer() + && !waitingForBufferSpace; + } - /** - * Returns true if no more rows should be produced. This is the case if the result set has been - * cancelled or is done, or if the callback will not be invoked anymore (e.g. because it threw - * an exception). Must be called while holding the monitor. - */ - private boolean shouldStopProducing() { - return state.shouldStop || cursorReturnedDoneOrException; + @GuardedBy("monitor") + private boolean prepareScheduleProducerLocked() { + if (producerRunning) { + if (!shouldStopProducer() && !waitingForBufferSpace) { + producerWakeupRequested = true; + } + return false; + } + if (!canScheduleProducer()) { + return false; } + producerRunning = true; + producerWakeupRequested = false; + return true; + } - private void waitIfPaused() throws InterruptedException { - CountDownLatch pause; + private void executeProducer() { + try { + service.execute(produceRowsRunnable); + } catch (Throwable throwable) { synchronized (monitor) { - pause = pausedLatch; + setExecutionExceptionLocked(throwable); + producerRunning = false; } - pause.await(); + closeDelegateResultSet(); + scheduleCallbackIfNecessary(); + checkCompletion(); } + } - private void startCallbackIfNecessary() { - startCallbackWithBufferLatchIfNecessary(0); + private void scheduleProducerIfNecessary() { + boolean shouldExecute; + synchronized (monitor) { + shouldExecute = prepareScheduleProducerLocked(); + } + if (shouldExecute) { + executeProducer(); } + } - private void startCallbackWithBufferLatchIfNecessary(int bufferLatch) { - boolean shouldExecute = false; - synchronized (monitor) { - if ((state == State.RUNNING || state == State.CANCELLED) - && !cursorReturnedDoneOrException) { - consumingLatch = new CountDownLatch(1); - if (bufferLatch > 0) { - bufferConsumptionLatch = new CountDownLatch(bufferLatch); - } - if (state == State.RUNNING) { - state = State.CONSUMING; - } - shouldExecute = true; + @GuardedBy("monitor") + private boolean canScheduleCallback() { + return !initiatingStreaming + && !cursorReturnedDoneOrException + && !callbackRunning + && (state == State.CANCELLED + || (state == State.RUNNING + && (!buffer.isEmpty() || finished || executionException != null))); + } + + private void scheduleCallbackIfNecessary() { + Executor callbackExecutor = null; + synchronized (monitor) { + if (canScheduleCallback()) { + if (state == State.RUNNING) { + state = State.CONSUMING; } + callbackRunning = true; + callbackExecutor = Preconditions.checkNotNull(this.executor); } - if (shouldExecute) { + } + if (callbackExecutor != null) { + try { + callbackExecutor.execute(callbackRunnable); + } catch (Throwable throwable) { + synchronized (monitor) { + setExecutionExceptionLocked(throwable); + callbackRunning = false; + cursorReturnedDoneOrException = true; + } + closeDelegateResultSet(); + checkCompletion(); + } + } + } + + private void checkCompletion() { + boolean shouldComplete = false; + synchronized (monitor) { + if (!completed + && cursorReturnedDoneOrException + && !initiatingStreaming + && !producerRunning + && !callbackRunning) { + if (state != State.CANCELLED) { + state = State.DONE; + } + completed = true; + shouldComplete = true; + } + } + if (shouldComplete) { + cleanupAndCompleteResult(); + } + } + + private void cleanupAndCompleteResult() { + closeDelegateResultSet(); + maybeNotifyStartOrClose(); + currentRow = null; + SpannerException finalException; + SpannerException finalCancelledException; + State finalState; + SettableApiFuture resultFuture; + List listenersToNotify = Collections.emptyList(); + synchronized (monitor) { + buffer.clear(); + finalException = executionException; + finalCancelledException = cancelledException; + finalState = state; + resultFuture = Preconditions.checkNotNull(result); + callback = null; + executor = null; + if (!listeners.isEmpty()) { + listenersToNotify = new ArrayList<>(listeners); + listeners.clear(); + } + } + try { + for (Runnable listener : listenersToNotify) { try { - executor.execute(callbackRunnable); - } catch (Throwable t) { - synchronized (monitor) { - consumingLatch.countDown(); - while (bufferConsumptionLatch.getCount() > 0L) { - bufferConsumptionLatch.countDown(); - } - if (state == State.CONSUMING) { - state = State.RUNNING; - } - } - throw t; + listener.run(); + } catch (Throwable throwable) { + log.log(Level.WARNING, "Listener threw exception", throwable); } } + if (executorProvider.shouldAutoClose()) { + service.shutdown(); + } + } finally { + if (finalException != null) { + resultFuture.setException(finalException); + } else if (finalState == State.CANCELLED) { + resultFuture.setException(Preconditions.checkNotNull(finalCancelledException)); + } else { + resultFuture.set(null); + } } } + /** + * Initializes the delegate {@link ResultSet} and starts streaming if supported. Note that + * obtaining the delegate or starting the stream may still block synchronously on future-backed + * {@link ResultSet} suppliers (such as {@link ResultSets#toAsyncResultSet(ApiFuture, + * ExecutorProvider, Options.ReadQueryUpdateTransactionOption...)}) or when waiting for an + * inlined-begin transaction ID on concurrent queries sharing a transaction. + */ private class InitiateStreamingRunnable implements Runnable { @Override public void run() { try { - // This method returns true if the underlying result set is a streaming result set (e.g. a - // GrpcResultSet). - // Those result sets will trigger initiateProduceRows() when the first results are received. - // Non-streaming result sets do not trigger this callback, and for those result sets, we - // need to eagerly start the ProduceRowsRunnable. - if (!initiateStreaming(AsyncResultSetImpl.this)) { - initiateProduceRows(); + boolean shouldStop; + synchronized (monitor) { + shouldStop = state.shouldStop; + } + if (shouldStop) { + closeDelegateResultSet(); + return; + } + // Initiate streaming on the underlying result set if it supports streaming (such as + // GrpcResultSet). Streaming result sets notify onStreamMessage() as chunks arrive. While + // initiatingStreaming is true, neither ProduceRowsRunnable nor CallbackRunnable may be + // dispatched so that delegate access remains strictly single-threaded until + // initiateStreaming() finishes. If the delegate is non-streaming or already has data or + // closure ready immediately after initiateStreaming() (for example, if the delegate was + // closed concurrently before starting an RPC), start producing rows immediately. + boolean isStreaming = initiateStreaming(AsyncResultSetImpl.this); + boolean startImmediately = !isStreaming; + if (!startImmediately) { + boolean alreadyInitiated; + synchronized (monitor) { + alreadyInitiated = produceRowsInitiated || state.shouldStop; + } + startImmediately = !alreadyInitiated && isDataAvailable(delegateResultSet.get()); + } + synchronized (monitor) { + streamingSupported = isStreaming; + if (startImmediately) { + produceRowsInitiated = true; + if (state == State.STREAMING_INITIALIZED) { + state = State.RUNNING; + } + } } } catch (Throwable exception) { + GrpcResultSet grpcDelegate = unwrapGrpcResultSet(); + if (grpcDelegate != null) { + exception = translateGrpcInitiateStreamingException(grpcDelegate, exception); + } + closeDelegateResultSet(); synchronized (monitor) { - executionException = SpannerExceptionFactory.asSpannerException(exception); + if (state == State.STREAMING_INITIALIZED) { + state = State.RUNNING; + } + setExecutionExceptionLocked(exception); } - initiateProduceRows(); + } finally { + boolean shouldExecuteProducer; + synchronized (monitor) { + initiatingStreaming = false; + shouldExecuteProducer = prepareScheduleProducerLocked(); + } + if (shouldExecuteProducer) { + executeProducer(); + } + scheduleCallbackIfNecessary(); + checkCompletion(); } } } + @Nullable + private GrpcResultSet unwrapGrpcResultSet() { + synchronized (monitor) { + if (!delegateInitialized || delegateClosed || state.shouldStop) { + return null; + } + } + try { + ResultSet current = delegateResultSet.get(); + while (current instanceof ForwardingResultSet) { + current = ((ForwardingResultSet) current).getDelegate(); + } + return current instanceof GrpcResultSet ? (GrpcResultSet) current : null; + } catch (Throwable ignored) { + return null; + } + } + + private static Throwable translateGrpcInitiateStreamingException( + GrpcResultSet grpcDelegate, Throwable exception) { + try { + if (grpcDelegate.isDataAvailable()) { + grpcDelegate.next(); + } + } catch (Throwable nextException) { + return nextException; + } + return exception; + } + /** Sets the callback for this {@link AsyncResultSet}. */ @Override - public ApiFuture setCallback(Executor exec, ReadyCallback cb) { - Preconditions.checkNotNull(exec, "exec cannot be null"); - Preconditions.checkNotNull(cb, "cb cannot be null"); - boolean shouldClose = false; + public ApiFuture setCallback(Executor executor, ReadyCallback callback) { + Preconditions.checkNotNull(executor, "exec cannot be null"); + Preconditions.checkNotNull(callback, "cb cannot be null"); + SettableApiFuture resultFuture = SettableApiFuture.create(); + synchronized (monitor) { + Preconditions.checkState(!closed, "This AsyncResultSet has been closed"); + Preconditions.checkState( + this.state == State.INITIALIZED, "callback may not be set multiple times"); + + // Start to fetch data and buffer these. + this.result = resultFuture; + this.executor = MoreExecutors.newSequentialExecutor(executor); + this.callback = callback; + this.state = State.STREAMING_INITIALIZED; + this.initiatingStreaming = true; + } try { + this.service.execute(new InitiateStreamingRunnable()); + } catch (Throwable throwable) { + boolean shouldRollback = false; synchronized (monitor) { - Preconditions.checkState(!closed, "This AsyncResultSet has been closed"); - Preconditions.checkState( - this.state == State.INITIALIZED, "callback may not be set multiple times"); - - // Start to fetch data and buffer these. - this.result = SettableApiFuture.create(); - this.executor = MoreExecutors.newSequentialExecutor(exec); - this.callback = cb; - this.state = State.STREAMING_INITIALIZED; - try { - this.service.execute(new InitiateStreamingRunnable()); - } catch (Throwable throwable) { + if (this.initiatingStreaming) { + this.initiatingStreaming = false; + this.cancelledException = null; + this.state = State.INITIALIZED; this.closed = true; - shouldClose = true; - throw throwable; + this.executor = null; + this.callback = null; + this.result = null; + shouldRollback = true; } - pausedLatch.countDown(); - return result; } - } finally { - if (shouldClose) { + if (shouldRollback) { closeDelegateResultSet(); maybeNotifyStartOrClose(); if (executorProvider.shouldAutoClose()) { service.shutdown(); } } + throw throwable; } + return resultFuture; } - private void initiateProduceRows() { - boolean shouldExecute = false; + @Nullable Future getResult() { synchronized (monitor) { - if (!produceRowsInitiated) { - produceRowsInitiated = true; - if (this.state == State.STREAMING_INITIALIZED) { - this.state = State.RUNNING; - } - shouldExecute = true; - } - } - if (shouldExecute) { - this.service.execute(new ProduceRowsRunnable()); + return result; } } - Future getResult() { - return result; - } - @Override public void cancel() { synchronized (monitor) { Preconditions.checkState( state != State.INITIALIZED && state != State.SYNC, "cannot cancel a result set without a callback"); + if (completed) { + return; + } + if (cancelledException == null) { + cancelledException = + SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "This AsyncResultSet has been cancelled"); + } + if (!cursorReturnedDoneOrException) { + executionException = null; + } state = State.CANCELLED; - pausedLatch.countDown(); } + closeDelegateResultSet(); + scheduleCallbackIfNecessary(); + checkCompletion(); } @Override public void resume() { + boolean shouldResume = false; synchronized (monitor) { Preconditions.checkState( state != State.INITIALIZED && state != State.SYNC, "cannot resume a result set without a callback"); if (state == State.PAUSED) { state = State.RUNNING; - pausedLatch.countDown(); + shouldResume = true; } } + if (shouldResume) { + scheduleCallbackIfNecessary(); + scheduleProducerIfNecessary(); + } } private static class CreateListCallback implements ReadyCallback { @@ -814,8 +1060,9 @@ public List toList(Function transformer) throws SpannerE return future.get(); } catch (ExecutionException e) { throw SpannerExceptionFactory.asSpannerException(e.getCause()); - } catch (Throwable e) { - throw SpannerExceptionFactory.asSpannerException(e); + } catch (InterruptedException e) { + cancel(); + throw SpannerExceptionFactory.propagateInterrupt(e); } } @@ -828,10 +1075,11 @@ public boolean next() throws SpannerException { "Cannot call next() on a result set with a callback."); this.state = State.SYNC; } + syncHasCurrentRow = false; ResultSet delegate = getOrInitializeDelegate(); - boolean res = delegate.next(); - currentRow = res ? delegate.getCurrentRowAsStruct() : null; - return res; + boolean hasNext = delegate.next(); + syncHasCurrentRow = hasNext; + return hasNext; } /** @@ -840,6 +1088,7 @@ public boolean next() throws SpannerException { * and finishing the query. */ @Override + @Nullable public ResultSetStats getStats() { return getOrInitializeDelegate().getStats(); } @@ -855,41 +1104,152 @@ public ResultSetMetadata getMetadata() { return getOrInitializeDelegate().getMetadata(); } + @VisibleForTesting boolean initiateStreaming(StreamMessageListener streamMessageListener) { return StreamingUtil.initiateStreaming(getOrInitializeDelegate(), streamMessageListener); } + private StructReader getSchemaReader() { + Struct row = getCurrentCallbackRow(); + if (row != null) { + return row; + } + checkValidStateSlow(/* allowAfterDone= */ true); + return getOrInitializeDelegate(); + } + + @Override + public Type getType() { + return getSchemaReader().getType(); + } + + @Override + public int getColumnCount() { + return getSchemaReader().getColumnCount(); + } + + @Override + public int getColumnIndex(String columnName) { + return getSchemaReader().getColumnIndex(columnName); + } + + @Override + public Type getColumnType(int columnIndex) { + return getSchemaReader().getColumnType(columnIndex); + } + + @Override + @Nullable + public Type getColumnType(String columnName) { + return getSchemaReader().getColumnType(columnName); + } + + private boolean isInCallbackInvocation() { + return callbackInvocationThread == Thread.currentThread(); + } + + @Nullable + private Struct getCurrentCallbackRow() { + return isInCallbackInvocation() ? currentRow : null; + } + @Override protected void checkValidState() { + if (getCurrentCallbackRow() != null) { + return; + } + checkValidStateSlow(/* allowAfterDone= */ false); + } + + private void checkValidStateSlow(boolean allowAfterDone) { synchronized (monitor) { + if (state == State.SYNC) { + Preconditions.checkState(!closed, "ResultSet is closed"); + return; + } Preconditions.checkState( - state == State.SYNC || state == State.CONSUMING || state == State.CANCELLED, + isInCallbackInvocation(), "only allowed after a next() call or from within a ReadyCallback#cursorReady callback"); - Preconditions.checkState(state != State.SYNC || !closed, "ResultSet is closed"); + Preconditions.checkState( + allowAfterDone && finished && cursorReturnedDoneOrException && state != State.CANCELLED, + "AsyncResultSet is not positioned on a row"); } } @Override public Struct getCurrentRowAsStruct() { - checkValidState(); - return currentRow; + Struct row = getCurrentCallbackRow(); + if (row != null) { + return row; + } + checkValidStateSlow(/* allowAfterDone= */ false); + Preconditions.checkState(syncHasCurrentRow, "next() call required"); + return getOrInitializeDelegate().getCurrentRowAsStruct(); } @Override public void onStreamMessage(PartialResultSet partialResultSet, boolean bufferIsFull) { + boolean shouldExecuteProducer; synchronized (monitor) { - if (produceRowsInitiated) { + if (state.shouldStop) { return; } - // if PartialResultSet contains a resume token or buffer size is full, or - // we have reached the end of the stream, we can start the thread. - boolean startJobThread = - !partialResultSet.getResumeToken().isEmpty() + if (!produceRowsInitiated + && (!partialResultSet.getResumeToken().isEmpty() || bufferIsFull - || partialResultSet == GrpcStreamIterator.END_OF_STREAM; - if (startJobThread || state != State.STREAMING_INITIALIZED) { - initiateProduceRows(); + || partialResultSet == GrpcStreamIterator.END_OF_STREAM + || ++initialChunksWithoutResumeToken > MAX_BUFFERED_CHUNKS)) { + produceRowsInitiated = true; + if (state == State.STREAMING_INITIALIZED) { + state = State.RUNNING; + } + } + shouldExecuteProducer = prepareScheduleProducerLocked(); + } + if (shouldExecuteProducer) { + executeProducer(); + } + } + + private static final class MemoizingSupplier implements Supplier { + private final Object lock = new Object(); + + @GuardedBy("lock") + @Nullable + private Supplier delegate; + + private volatile boolean initialized; + + @Nullable private ResultSet value; + @Nullable private Throwable exception; + + private MemoizingSupplier(Supplier delegate) { + this.delegate = delegate; + } + + @Override + public ResultSet get() { + if (!initialized) { + synchronized (lock) { + if (!initialized) { + Supplier supplier = Preconditions.checkNotNull(delegate); + delegate = null; + try { + value = Preconditions.checkNotNull(supplier.get()); + } catch (Throwable throwable) { + exception = throwable; + } finally { + initialized = true; + } + } + } + } + Throwable thrown = exception; + if (thrown != null) { + Throwables.throwIfUnchecked(thrown); + throw SpannerExceptionFactory.asSpannerException(thrown); } + return Preconditions.checkNotNull(value); } } } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java index 839202bb9fe3..64e4a8d318a4 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java @@ -32,7 +32,7 @@ /** Forwarding implements of StructReader */ public class ForwardingStructReader implements StructReader { - private Supplier delegate; + private volatile Supplier delegate; public ForwardingStructReader(StructReader delegate) { this.delegate = Suppliers.ofInstance(Preconditions.checkNotNull(delegate)); @@ -53,6 +53,10 @@ void replaceDelegate(StructReader newDelegate) { this.delegate = Suppliers.ofInstance(Preconditions.checkNotNull(newDelegate)); } + void replaceDelegateSupplier(Supplier newDelegate) { + this.delegate = Preconditions.checkNotNull(newDelegate); + } + /** * Called before each forwarding call to allow sub classes to do additional state checking. Sub * classes should throw an {@link Exception} if the current state is not valid for reading data @@ -152,11 +156,13 @@ public double getDouble(String columnName) { @Override public BigDecimal getBigDecimal(int columnIndex) { + checkValidState(); return delegate.get().getBigDecimal(columnIndex); } @Override public BigDecimal getBigDecimal(String columnName) { + checkValidState(); return delegate.get().getBigDecimal(columnName); } @@ -354,11 +360,13 @@ public List getDoubleList(String columnName) { @Override public List getBigDecimalList(int columnIndex) { + checkValidState(); return delegate.get().getBigDecimalList(columnIndex); } @Override public List getBigDecimalList(String columnName) { + checkValidState(); return delegate.get().getBigDecimalList(columnName); } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java new file mode 100644 index 000000000000..001d38e33a7e --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java @@ -0,0 +1,1269 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.spanner; + +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.executorProviderOf; +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.sneakyThrow; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.api.core.ApiFuture; +import com.google.api.gax.core.ExecutorProvider; +import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.ControllableStreamingDelegate; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.QueuedExecutorProvider; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.protobuf.Value; +import com.google.spanner.v1.PartialResultSet; +import com.google.spanner.v1.ResultSetMetadata; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for pause/resume races, cancellation concurrency, executor rejections, listener isolation, + * and supplier exception caching in {@link AsyncResultSetImpl}. + */ +@RunWith(JUnit4.class) +public class AsyncResultSetImplLifecycleAndConcurrencyTest { + private ExecutorProvider mockedProvider; + private SpannerOptions.CloseableExecutorProvider simpleProvider; + + @Before + public void setup() { + mockedProvider = executorProviderOf(mock(ScheduledExecutorService.class), false); + simpleProvider = SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + } + + @After + public void teardown() { + if (simpleProvider != null) { + simpleProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testPollingResumeDuringConsumingDoesNotBypassCallbackPause() throws Exception { + // Callers that coordinate externally (such as ReadAsyncTest#pauseResume and + // AsyncResultSetImplTest#testCallbackIsNotCalledWhilePaused) poll resume() concurrently while + // cursorReady() is still executing in State.CONSUMING. Returning CallbackResponse.PAUSE must + // still transition the cursor to State.PAUSED rather than consuming a pre-pause resume() call. + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(2); + List receivedIds = new ArrayList<>(); + AtomicInteger callbackInvocations = new AtomicInteger(); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(queuedProvider, stream.delegate, 10)) { + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + int call = callbackInvocations.incrementAndGet(); + if (call == 1) { + // Simulate an external coordinator polling resume() while cursorReady() is in + // State.CONSUMING before returning PAUSE. + cursor.resume(); + assertEquals(CursorState.OK, cursor.tryNext()); + receivedIds.add(cursor.getLong(0)); + return CallbackResponse.PAUSE; + } + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + stream.availableRows.set(2); + stream.emitEndOfStream(false); + queuedProvider.runNext(); // ProduceRowsRunnable -> buffers rows 1 & 2 + EOF + + assertEquals(Collections.singletonList(1L), receivedIds); + assertEquals(AsyncResultSetImpl.State.PAUSED, resultSet.getState()); + assertFalse(future.isDone()); + + resultSet.resume(); + assertTrue(future.isDone()); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), receivedIds); + } + } + + @Test(timeout = 10_000) + public void testResumeImmediatelyUponEnteringPausedStateDoesNotLoseWakeup() throws Exception { + final int totalRows = 80; + final int maxBufferSize = 3; + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + ExecutorService resumerExecutor = Executors.newFixedThreadPool(2); + ExecutorService streamFeederExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(totalRows); + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, maxBufferSize)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + resumerExecutor.execute( + () -> { + while (resultSet.getState() == AsyncResultSetImpl.State.CONSUMING) { + Thread.yield(); + } + resultSet.resume(); + }); + return CallbackResponse.PAUSE; + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + Future feederFuture = + streamFeederExecutor.submit( + () -> { + stream.awaitListener(); + for (int row = 1; row <= totalRows; row++) { + stream.availableRows.incrementAndGet(); + stream.emitFlushableChunk("r" + row, row % 4 == 0); + } + stream.emitEndOfStream(false); + return null; + }); + + feederFuture.get(5, TimeUnit.SECONDS); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(totalRows, receivedIds.size()); + for (int index = 0; index < totalRows; index++) { + assertEquals(Long.valueOf(index + 1L), receivedIds.get(index)); + } + } finally { + streamFeederExecutor.shutdownNow(); + resumerExecutor.shutdownNow(); + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testConcurrentStreamingPauseResumeWithSeededRandom() throws Exception { + final int totalRows = 150; + final int maxBufferSize = 4; + final Random random = new Random(42L); + ExecutorService callbackPool = Executors.newFixedThreadPool(2); + ExecutorService resumerExecutor = Executors.newSingleThreadExecutor(); + ExecutorService streamFeederExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(totalRows); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + AtomicBoolean currentlyPaused = new AtomicBoolean(false); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, maxBufferSize)) { + Executor notifyingCallbackExecutor = + command -> + callbackPool.execute( + () -> { + try { + command.run(); + } finally { + if (resultSet.getState() == AsyncResultSetImpl.State.PAUSED) { + resumerExecutor.execute( + () -> { + currentlyPaused.set(false); + resultSet.resume(); + }); + } + } + }); + + ApiFuture resultFuture = + resultSet.setCallback( + notifyingCallbackExecutor, + cursor -> { + assertFalse(currentlyPaused.get()); + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + if (random.nextInt(4) == 0) { + currentlyPaused.set(true); + return CallbackResponse.PAUSE; + } + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + Future feederFuture = + streamFeederExecutor.submit( + () -> { + AsyncResultSet.StreamMessageListener listener = stream.awaitListener(); + for (int row = 1; row <= totalRows; row++) { + listener.onStreamMessage( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue(String.valueOf(row))) + .build(), + false); + stream.availableRows.incrementAndGet(); + stream.emitFlushableChunk("r" + row, row % 3 == 0); + } + stream.emitEndOfStream(false); + return null; + }); + + feederFuture.get(5, TimeUnit.SECONDS); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(totalRows, receivedIds.size()); + for (int index = 0; index < totalRows; index++) { + assertEquals(Long.valueOf(index + 1L), receivedIds.get(index)); + } + } finally { + streamFeederExecutor.shutdownNow(); + resumerExecutor.shutdownNow(); + callbackPool.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelDuringCallbackReturningDoneDoesNotReinvokeCallback() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + CountDownLatch inDoneCallbackLatch = new CountDownLatch(1); + CountDownLatch allowDoneReturnLatch = new CountDownLatch(1); + AtomicInteger doneCallbackCount = new AtomicInteger(); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, false); + when(delegate.getCurrentRowAsStruct()).thenReturn(Struct.newBuilder().set("c").to(1L).build()); + + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + doneCallbackCount.incrementAndGet(); + assertEquals(CursorState.OK, cursor.tryNext()); + inDoneCallbackLatch.countDown(); + try { + assertTrue(allowDoneReturnLatch.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + return CallbackResponse.DONE; + }); + assertTrue(inDoneCallbackLatch.await(5, TimeUnit.SECONDS)); + resultSet.cancel(); + assertThrows(IllegalStateException.class, resultSet::tryNext); + allowDoneReturnLatch.countDown(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, doneCallbackCount.get()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelDuringCallbackReturningPauseOrContinueDeliversCancelledOnNextInvocation() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + try { + for (CallbackResponse firstResponse : + new CallbackResponse[] {CallbackResponse.PAUSE, CallbackResponse.CONTINUE}) { + CountDownLatch inFirstCallbackLatch = new CountDownLatch(1); + CountDownLatch allowFirstReturnLatch = new CountDownLatch(1); + AtomicInteger callbackCount = new AtomicInteger(); + AtomicBoolean observedCancelledInCallback = new AtomicBoolean(false); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, true, false); + when(delegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("c").to(1L).build()); + + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + int call = callbackCount.incrementAndGet(); + if (call == 1) { + assertEquals(CursorState.OK, cursor.tryNext()); + inFirstCallbackLatch.countDown(); + try { + assertTrue(allowFirstReturnLatch.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + return firstResponse; + } + try { + cursor.tryNext(); + } catch (SpannerException spannerException) { + if (spannerException.getErrorCode() == ErrorCode.CANCELLED) { + observedCancelledInCallback.set(true); + } + } + return CallbackResponse.CONTINUE; + }); + + assertTrue(inFirstCallbackLatch.await(5, TimeUnit.SECONDS)); + resultSet.cancel(); + allowFirstReturnLatch.countDown(); + + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, + ((SpannerException) executionException.getCause()).getErrorCode()); + assertTrue(observedCancelledInCallback.get()); + assertEquals(2, callbackCount.get()); + } + } + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelBeforeCallbackReturningContinueWithoutTryNextStopsAfterOneInvocation() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger noTryNextCallbackCount = new AtomicInteger(); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + noTryNextCallbackCount.incrementAndGet(); + return CallbackResponse.CONTINUE; + }); + resultSet.cancel(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, noTryNextCallbackCount.get()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelBeforeInitiateStreamingRunsSkipsDelegateInitialization() throws Exception { + CountDownLatch blockerStartedLatch = new CountDownLatch(1); + CountDownLatch releaseBlockerLatch = new CountDownLatch(1); + Future blockerFuture = + simpleProvider + .getExecutor() + .submit( + () -> { + blockerStartedLatch.countDown(); + try { + releaseBlockerLatch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + }); + + assertTrue(blockerStartedLatch.await(5, TimeUnit.SECONDS)); + AtomicInteger supplierCalls = new AtomicInteger(); + AtomicInteger onStartOrCloseCalls = new AtomicInteger(); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + supplierCalls.incrementAndGet(); + return mock(ResultSet.class); + }, + 4, + onStartOrCloseCalls::incrementAndGet)) { + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertThrows(IllegalStateException.class, cursor::getColumnCount); + SpannerException cancelled = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.CANCELLED, cancelled.getErrorCode()); + assertThrows(IllegalStateException.class, cursor::getColumnCount); + return CallbackResponse.DONE; + }); + resultSet.cancel(); + releaseBlockerLatch.countDown(); + blockerFuture.get(5, TimeUnit.SECONDS); + + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(0, supplierCalls.get()); + assertEquals(1, onStartOrCloseCalls.get()); + } + } + + @Test(timeout = 10_000) + public void testCancelDuringNonStreamingInitiateStreamingPreservesCancelledState() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + AtomicReference nonStreamingCancelHolder = new AtomicReference<>(); + ResultSet nonStreamingCancelDelegate = mock(ResultSet.class); + AsyncResultSetImpl nonStreamingCancelResultSet = + new AsyncResultSetImpl( + queuedProvider, + () -> { + nonStreamingCancelHolder.get().cancel(); + return nonStreamingCancelDelegate; + }, + 4); + nonStreamingCancelHolder.set(nonStreamingCancelResultSet); + try (AsyncResultSetImpl ignored = nonStreamingCancelResultSet) { + ApiFuture future = + nonStreamingCancelResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + ExecutionException cancelledExec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) cancelledExec.getCause()).getErrorCode()); + verify(nonStreamingCancelDelegate, never()).next(); + } + } + + @Test(timeout = 10_000) + public void testCancelRacingWithProducerWakeupExitsWithoutCallingNext() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate cancelRaceStream = new ControllableStreamingDelegate(1); + AtomicReference cancelRaceResultSetRef = new AtomicReference<>(); + AtomicInteger isDataAvailableCalls = new AtomicInteger(); + doAnswer( + invocation -> { + if (isDataAvailableCalls.incrementAndGet() == 2) { + cancelRaceStream.emitEndOfStream(true); + cancelRaceResultSetRef.get().cancel(); + } + return false; + }) + .when(cancelRaceStream.delegate) + .isDataAvailable(); + try (AsyncResultSetImpl cancelRaceResultSet = + new AsyncResultSetImpl(queuedProvider, cancelRaceStream.delegate, 4)) { + cancelRaceResultSetRef.set(cancelRaceResultSet); + ApiFuture future = + cancelRaceResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + cancelRaceStream.emitFlushableChunk("wake", false); + queuedProvider.runNext(); // ProduceRowsRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + ExecutionException cancelExec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.CANCELLED, ((SpannerException) cancelExec.getCause()).getErrorCode()); + verify(cancelRaceStream.delegate, never()).next(); + } + } + + @Test(timeout = 10_000) + public void testCallbackNullReturnAndUncaughtExceptionsOnCancel() { + ResultSet oneRowDelegate = mock(ResultSet.class); + when(oneRowDelegate.next()).thenReturn(true, false); + when(oneRowDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("c").to(1L).build()); + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, oneRowDelegate, 4)) { + ApiFuture future = + resultSet.setCallback(MoreExecutors.directExecutor(), cursor -> null); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNKNOWN, ((SpannerException) executionException.getCause()).getErrorCode()); + } + + StreamingResultSet cancelledStreamingDelegate = mock(StreamingResultSet.class); + when(cancelledStreamingDelegate.initiateStreaming( + any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + try (AsyncResultSetImpl uncaughtCancelledResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4); + AsyncResultSetImpl customUserCancelledResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4); + AsyncResultSetImpl customExceptionResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4); + AsyncResultSetImpl nonCancelledSpannerExceptionResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4)) { + ApiFuture uncaughtCancelledFuture = + uncaughtCancelledResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + uncaughtCancelledResultSet.cancel(); + ExecutionException cancelledException = + assertThrows( + ExecutionException.class, () -> uncaughtCancelledFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) cancelledException.getCause()).getErrorCode()); + + SpannerException userCustomCancelled = + SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "custom user cancel reason"); + ApiFuture userCancelledFuture = + customUserCancelledResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + throw userCustomCancelled; + }); + customUserCancelledResultSet.cancel(); + ExecutionException userCancelledExecutionException = + assertThrows( + ExecutionException.class, () -> userCancelledFuture.get(5, TimeUnit.SECONDS)); + assertSame(userCustomCancelled, userCancelledExecutionException.getCause()); + + ApiFuture customFuture = + customExceptionResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + throw new IllegalArgumentException("custom callback failure"); + }); + customExceptionResultSet.cancel(); + ExecutionException customException = + assertThrows(ExecutionException.class, () -> customFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNKNOWN, ((SpannerException) customException.getCause()).getErrorCode()); + assertTrue(customException.getCause().getMessage().contains("custom callback failure")); + + ApiFuture internalSpannerFuture = + nonCancelledSpannerExceptionResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.INTERNAL, "internal callback failure"); + }); + nonCancelledSpannerExceptionResultSet.cancel(); + ExecutionException internalException = + assertThrows( + ExecutionException.class, () -> internalSpannerFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.INTERNAL, ((SpannerException) internalException.getCause()).getErrorCode()); + } + } + + @Test(timeout = 10_000) + public void testExecutorRejectionsAndListenerIsolation() { + AtomicInteger serviceExecuteCalls = new AtomicInteger(); + ScheduledExecutorService customService = + mock( + ScheduledExecutorService.class, + invocation -> { + if ("execute".equals(invocation.getMethod().getName())) { + Runnable runnable = invocation.getArgument(0); + if (serviceExecuteCalls.incrementAndGet() == 1) { + runnable.run(); + return null; + } + throw new RejectedExecutionException("producer rejected on stream message"); + } + return null; + }); + ExecutorProvider rejectingProducerProvider = executorProviderOf(customService, true); + + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + AtomicInteger listenerCalls = new AtomicInteger(); + try (AsyncResultSetImpl producerRejectedResultSet = + new AsyncResultSetImpl(rejectingProducerProvider, streamingDelegate, 4)) { + producerRejectedResultSet.addListener( + () -> { + listenerCalls.incrementAndGet(); + throw new RuntimeException("listener failure 1"); + }); + producerRejectedResultSet.addListener(listenerCalls::incrementAndGet); + ApiFuture future = + producerRejectedResultSet.setCallback( + MoreExecutors.directExecutor(), cursor -> CallbackResponse.DONE); + producerRejectedResultSet.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + ExecutionException rejectedException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertTrue(rejectedException.getCause() instanceof SpannerException); + assertEquals(2, listenerCalls.get()); + assertThrows( + IllegalStateException.class, () -> producerRejectedResultSet.addListener(() -> {})); + } + + Executor rejectingCallbackExecutor = + command -> { + throw new RejectedExecutionException("callback executor shut down"); + }; + ResultSet emptyDelegate = mock(ResultSet.class); + when(emptyDelegate.next()).thenReturn(false); + try (AsyncResultSetImpl callbackRejectedResultSet = + new AsyncResultSetImpl(simpleProvider, emptyDelegate, 4)) { + ApiFuture future = + callbackRejectedResultSet.setCallback( + rejectingCallbackExecutor, cursor -> CallbackResponse.DONE); + ExecutionException callbackRejectedException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertTrue(callbackRejectedException.getCause() instanceof SpannerException); + verify(emptyDelegate).close(); + } + + ScheduledExecutorService nonAutoCloseRejectingService = mock(ScheduledExecutorService.class); + doThrow(new RejectedExecutionException("rejected")) + .when(nonAutoCloseRejectingService) + .execute(any(Runnable.class)); + ExecutorProvider nonAutoCloseProvider = executorProviderOf(nonAutoCloseRejectingService, false); + try (AsyncResultSetImpl rejectedNonAutoClose = + new AsyncResultSetImpl(nonAutoCloseProvider, mock(ResultSet.class), 4)) { + assertThrows( + RejectedExecutionException.class, + () -> + rejectedNonAutoClose.setCallback( + MoreExecutors.directExecutor(), cursor -> CallbackResponse.DONE)); + } + verify(nonAutoCloseRejectingService, never()).shutdown(); + } + + @Test(timeout = 10_000) + public void testListenerRemovalAndSwallowedDelegateCloseExceptions() throws Exception { + AtomicInteger removedListenerCalls = new AtomicInteger(); + AtomicInteger keptListenerCalls = new AtomicInteger(); + Runnable removedListener = removedListenerCalls::incrementAndGet; + Runnable keptListener = keptListenerCalls::incrementAndGet; + ResultSet emptySyncDelegate = mock(ResultSet.class); + when(emptySyncDelegate.next()).thenReturn(false); + try (AsyncResultSetImpl listenerResultSet = + new AsyncResultSetImpl(simpleProvider, emptySyncDelegate, 4)) { + listenerResultSet.addListener(removedListener); + listenerResultSet.addListener(keptListener); + listenerResultSet.removeListener(removedListener); + assertEquals( + 0, + listenerResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS) + .size()); + assertEquals(0, removedListenerCalls.get()); + assertEquals(1, keptListenerCalls.get()); + } + + ResultSet throwingLazyDelegate = mock(ResultSet.class); + ResultSetMetadata expectedMetadata = ResultSetMetadata.getDefaultInstance(); + when(throwingLazyDelegate.getMetadata()).thenReturn(expectedMetadata); + doThrow(new RuntimeException("lazy close failure")).when(throwingLazyDelegate).close(); + AsyncResultSetImpl closedBeforeInitResultSet = + new AsyncResultSetImpl(mockedProvider, () -> throwingLazyDelegate, 4); + closedBeforeInitResultSet.close(); + assertSame(expectedMetadata, closedBeforeInitResultSet.getMetadata()); + + ResultSet throwingInitializedDelegate = mock(ResultSet.class); + doThrow(new RuntimeException("eager close failure")).when(throwingInitializedDelegate).close(); + AsyncResultSetImpl initializedThrowingCloseResultSet = + new AsyncResultSetImpl(mockedProvider, throwingInitializedDelegate, 4); + initializedThrowingCloseResultSet.close(); + verify(throwingInitializedDelegate).close(); + } + + @Test(timeout = 10_000) + public void testToListInterruptedAndCachedSupplierExceptions() { + StreamingResultSet stalledDelegate = mock(StreamingResultSet.class); + when(stalledDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + try (AsyncResultSetImpl stalledResultSet = + new AsyncResultSetImpl(simpleProvider, stalledDelegate, 4)) { + Thread.currentThread().interrupt(); + try { + SpannerException interruptedSpannerException = + assertThrows( + SpannerException.class, () -> stalledResultSet.toList(reader -> reader.getLong(0))); + assertEquals(ErrorCode.CANCELLED, interruptedSpannerException.getErrorCode()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + + ScheduledExecutorService autoCloseService = mock(ScheduledExecutorService.class); + ExecutorProvider autoCloseProvider = executorProviderOf(autoCloseService, true); + AtomicInteger runtimeSupplierCalls = new AtomicInteger(); + try (AsyncResultSetImpl runtimeSupplierResultSet = + new AsyncResultSetImpl( + autoCloseProvider, + () -> { + runtimeSupplierCalls.incrementAndGet(); + throw new IllegalStateException("runtime supplier failure"); + }, + 4)) { + assertThrows(IllegalStateException.class, runtimeSupplierResultSet::getMetadata); + assertThrows(IllegalStateException.class, runtimeSupplierResultSet::getStats); + assertEquals(1, runtimeSupplierCalls.get()); + } + verify(autoCloseService).shutdown(); + + AtomicInteger errorSupplierCalls = new AtomicInteger(); + try (AsyncResultSetImpl errorSupplierResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + errorSupplierCalls.incrementAndGet(); + throw new AssertionError("fatal supplier error"); + }, + 4)) { + assertThrows(AssertionError.class, errorSupplierResultSet::getMetadata); + assertThrows(AssertionError.class, errorSupplierResultSet::getStats); + assertEquals(1, errorSupplierCalls.get()); + } + + AtomicInteger checkedSupplierCalls = new AtomicInteger(); + try (AsyncResultSetImpl checkedSupplierResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + checkedSupplierCalls.incrementAndGet(); + throw sneakyThrow(new IOException("checked supplier io failure")); + }, + 4)) { + assertThrows(SpannerException.class, checkedSupplierResultSet::getMetadata); + assertThrows(SpannerException.class, checkedSupplierResultSet::getStats); + assertEquals(1, checkedSupplierCalls.get()); + } + } + + @Test(timeout = 10_000) + public void testSetCallbackWithCallerRunsServiceDoesNotHoldMonitorDuringInitiateStreaming() + throws Exception { + ScheduledExecutorService callerRunsService = + mock( + ScheduledExecutorService.class, + invocation -> { + if ("execute".equals(invocation.getMethod().getName())) { + Runnable runnable = invocation.getArgument(0); + runnable.run(); + } + return null; + }); + ExecutorProvider callerRunsProvider = executorProviderOf(callerRunsService, false); + + ExecutorService externalObserverExecutor = Executors.newSingleThreadExecutor(); + AtomicReference resultSetRef = new AtomicReference<>(); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.isDataAvailable()).thenReturn(true); + when(streamingDelegate.next()).thenReturn(false); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + Future externalCall = + externalObserverExecutor.submit( + () -> { + assertEquals( + AsyncResultSetImpl.State.STREAMING_INITIALIZED, + resultSetRef.get().getState()); + listener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + return null; + }); + // If setCallback holds monitor across service.execute(...), externalCall deadlocks + // trying to acquire monitor in getState()/onStreamMessage() and times out here. + externalCall.get(1, TimeUnit.SECONDS); + return true; + }); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(callerRunsProvider, streamingDelegate, 4)) { + resultSetRef.set(resultSet); + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertEquals(CursorState.DONE, cursor.tryNext()); + return CallbackResponse.DONE; + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + } finally { + externalObserverExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testSetCallbackConcurrentCancelBeforeRejectedExecutionRollsBackCleanly() { + for (boolean alsoCloseBeforeReject : new boolean[] {false, true}) { + AtomicReference resultSetRef = new AtomicReference<>(); + ScheduledExecutorService cancelThenRejectService = + mock( + ScheduledExecutorService.class, + invocation -> { + if ("execute".equals(invocation.getMethod().getName())) { + // Simulate another thread calling cancel() (and optionally close()) right after + // setCallback transitions to STREAMING_INITIALIZED and releases monitor, before + // service.execute() throws RejectedExecutionException. + resultSetRef.get().cancel(); + if (alsoCloseBeforeReject) { + resultSetRef.get().close(); + } + throw new RejectedExecutionException("rejected after concurrent cancel"); + } + return null; + }); + ExecutorProvider provider = executorProviderOf(cancelThenRejectService, true); + + AtomicInteger runningAsyncOperations = new AtomicInteger(); + AtomicInteger callbackCount = new AtomicInteger(); + ResultSet delegate = mock(ResultSet.class); + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(provider, delegate, 4)) { + resultSetRef.set(resultSet); + Runnable listener = runningAsyncOperations::decrementAndGet; + assertThrows( + RejectedExecutionException.class, + () -> { + // Mirror TransactionRunnerImpl.TransactionContextAsyncResultSetImpl.setCallback. + runningAsyncOperations.incrementAndGet(); + resultSet.addListener(listener); + try { + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + callbackCount.incrementAndGet(); + return CallbackResponse.DONE; + }); + } catch (Throwable throwable) { + resultSet.removeListener(listener); + runningAsyncOperations.decrementAndGet(); + throw throwable; + } + }); + assertEquals(0, runningAsyncOperations.get()); + assertEquals(0, callbackCount.get()); + assertEquals(AsyncResultSetImpl.State.INITIALIZED, resultSet.getState()); + verify(delegate).close(); + verify(cancelThenRejectService).shutdown(); + } + } + } + + @Test(timeout = 10_000) + public void testCancelDuringInitiateStreamingDefersCallbackUntilInitiateStreamingCompletes() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger activeDelegateCalls = new AtomicInteger(); + AtomicInteger maxConcurrentDelegateCalls = new AtomicInteger(); + CountDownLatch insideInitiateStreaming = new CountDownLatch(1); + CountDownLatch allowInitiateStreamingToFinish = new CountDownLatch(1); + Runnable enterDelegate = + () -> { + int concurrent = activeDelegateCalls.incrementAndGet(); + maxConcurrentDelegateCalls.accumulateAndGet(concurrent, Math::max); + }; + + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + enterDelegate.run(); + try { + insideInitiateStreaming.countDown(); + assertTrue(allowInitiateStreamingToFinish.await(5, TimeUnit.SECONDS)); + return true; + } finally { + activeDelegateCalls.decrementAndGet(); + } + }); + when(streamingDelegate.getMetadata()) + .thenAnswer( + invocation -> { + enterDelegate.run(); + try { + return ResultSetMetadata.getDefaultInstance(); + } finally { + activeDelegateCalls.decrementAndGet(); + } + }); + + Runnable noopListener = () -> {}; + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 4)) { + resultSet.addListener(noopListener); + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + cursor.getMetadata(); + assertThrows(SpannerException.class, cursor::tryNext); + return CallbackResponse.DONE; + }); + + assertTrue(insideInitiateStreaming.await(5, TimeUnit.SECONDS)); + // removeListener must reject removal while active and not closed. + assertThrows(IllegalStateException.class, () -> resultSet.removeListener(noopListener)); + + // Cancel while InitiateStreamingRunnable is still inside initiateStreaming(); flush + // callbackExecutor to prove ReadyCallback was NOT scheduled while initiatingStreaming=true. + resultSet.cancel(); + callbackExecutor.submit(() -> null).get(5, TimeUnit.SECONDS); + assertEquals(1, activeDelegateCalls.get()); + + allowInitiateStreamingToFinish.countDown(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, maxConcurrentDelegateCalls.get()); + } finally { + allowInitiateStreamingToFinish.countDown(); + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelledExceptionDoesNotLeakSuppressedExceptionsAcrossQueries() + throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet delegate1 = mock(ResultSet.class); + try (AsyncResultSetImpl resultSet1 = new AsyncResultSetImpl(queuedProvider, delegate1, 4)) { + ApiFuture future1 = + resultSet1.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + try (AutoCloseable failingCloseable = + () -> { + throw new IOException("suppressed close failure"); + }) { + cursor.tryNext(); + } catch (Exception exception) { + // Also invoke cancel() a second time before rethrowing to ensure repeated + // cancel() calls keep the same per-instance cancelledException identity. + resultSet1.cancel(); + if (exception instanceof RuntimeException) { + throw (RuntimeException) exception; + } + throw new RuntimeException(exception); + } + return CallbackResponse.DONE; + }); + resultSet1.cancel(); + queuedProvider.runNext(); + ExecutionException exec1 = + assertThrows(ExecutionException.class, () -> future1.get(5, TimeUnit.SECONDS)); + SpannerException cancelled1 = (SpannerException) exec1.getCause(); + assertEquals(ErrorCode.CANCELLED, cancelled1.getErrorCode()); + assertEquals(1, cancelled1.getSuppressed().length); + } + + ResultSet delegate2 = mock(ResultSet.class); + try (AsyncResultSetImpl resultSet2 = new AsyncResultSetImpl(queuedProvider, delegate2, 4)) { + AtomicReference caughtInCallback = new AtomicReference<>(); + ApiFuture future2 = + resultSet2.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + caughtInCallback.set(thrown); + return CallbackResponse.DONE; + }); + resultSet2.cancel(); + queuedProvider.runNext(); + ExecutionException exec2 = + assertThrows(ExecutionException.class, () -> future2.get(5, TimeUnit.SECONDS)); + SpannerException cancelled2 = (SpannerException) exec2.getCause(); + assertEquals(ErrorCode.CANCELLED, cancelled2.getErrorCode()); + assertEquals(0, caughtInCallback.get().getSuppressed().length); + assertEquals(0, cancelled2.getSuppressed().length); + } + } + + @Test(timeout = 10_000) + public void testConcurrentLazySupplierFailureInvokesSupplierOnlyOnce() throws Exception { + SpannerException transientFailure = + SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "transient lazy supplier error"); + CountDownLatch firstThreadInSupplier = new CountDownLatch(1); + CountDownLatch allowSupplierToThrow = new CountDownLatch(1); + AtomicInteger supplierCalls = new AtomicInteger(); + ResultSet leakedSecondDelegate = mock(ResultSet.class); + + ExecutorService callerPool = Executors.newFixedThreadPool(2); + AtomicReference secondCallerThread = new AtomicReference<>(); + CountDownLatch secondCallerEntering = new CountDownLatch(1); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + int call = supplierCalls.incrementAndGet(); + if (call == 1) { + firstThreadInSupplier.countDown(); + try { + assertTrue(allowSupplierToThrow.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + throw transientFailure; + } + return leakedSecondDelegate; + }, + 4)) { + Future firstCall = + callerPool.submit(() -> assertThrows(SpannerException.class, resultSet::getMetadata)); + assertTrue(firstThreadInSupplier.await(5, TimeUnit.SECONDS)); + + Future secondCall = + callerPool.submit( + () -> { + secondCallerThread.set(Thread.currentThread()); + secondCallerEntering.countDown(); + return assertThrows(SpannerException.class, resultSet::getStats); + }); + assertTrue(secondCallerEntering.await(5, TimeUnit.SECONDS)); + while (secondCallerThread.get().getState() != Thread.State.BLOCKED && !secondCall.isDone()) { + Thread.yield(); + } + allowSupplierToThrow.countDown(); + + assertSame(transientFailure, firstCall.get(5, TimeUnit.SECONDS)); + assertSame(transientFailure, secondCall.get(5, TimeUnit.SECONDS)); + assertEquals(1, supplierCalls.get()); + } finally { + allowSupplierToThrow.countDown(); + callerPool.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelWithUndeliveredProducerExceptionResolvesFutureAsCancelled() + throws Exception { + SpannerException unavailableException = + SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "stream broken on row 2"); + + // 1. Producer buffers row 1 and records UNAVAILABLE on row 2 while callback has not yet + // observed UNAVAILABLE. Calling cancel() must cause both tryNext() and the setCallback() future + // to report CANCELLED rather than mismatching (tryNext -> CANCELLED, future -> UNAVAILABLE). + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet failingRow2Delegate = mock(ResultSet.class); + when(failingRow2Delegate.next()).thenReturn(true).thenThrow(unavailableException); + when(failingRow2Delegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(1L).build()); + AtomicReference callbackObservedCode = new AtomicReference<>(); + + try (AsyncResultSetImpl preemptedResultSet = + new AsyncResultSetImpl(queuedProvider, failingRow2Delegate, 4)) { + Executor deferredCallbackExecutor = queuedProvider.tasks::addLast; + ApiFuture future = + preemptedResultSet.setCallback( + deferredCallbackExecutor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + callbackObservedCode.set(thrown.getErrorCode()); + return CallbackResponse.DONE; + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable: buffers row 1, sets executionException + preemptedResultSet.cancel(); + while (!queuedProvider.tasks.isEmpty()) { + queuedProvider.runNext(); + } + + assertEquals(ErrorCode.CANCELLED, callbackObservedCode.get()); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + } + + // 2. Conversely, if tryNext() ALREADY delivered UNAVAILABLE before cancel() is invoked, the + // terminal UNAVAILABLE outcome was already observed and must be preserved on the future. + ResultSet alreadyDeliveredDelegate = mock(ResultSet.class); + when(alreadyDeliveredDelegate.next()).thenThrow(unavailableException); + try (AsyncResultSetImpl deliveredResultSet = + new AsyncResultSetImpl(simpleProvider, alreadyDeliveredDelegate, 4)) { + ApiFuture future = + deliveredResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + assertSame(unavailableException, thrown); + deliveredResultSet.cancel(); + return CallbackResponse.DONE; + }); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertSame(unavailableException, executionException.getCause()); + } + } + + @Test(timeout = 10_000) + public void testExternalThreadCannotReadActiveCallbackRow() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + CountDownLatch positionedOnRowLatch = new CountDownLatch(1); + CountDownLatch releaseCallbackLatch = new CountDownLatch(1); + ResultSet singleRowDelegate = mock(ResultSet.class); + when(singleRowDelegate.next()).thenReturn(true, false); + when(singleRowDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(42L).build()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, singleRowDelegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + assertEquals(42L, cursor.getLong(0)); + positionedOnRowLatch.countDown(); + try { + assertTrue(releaseCallbackLatch.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + assertTrue(positionedOnRowLatch.await(5, TimeUnit.SECONDS)); + // Even while currentRow is non-null inside an active callback invocation, external threads + // must be rejected across column, schema, and Struct readers. + assertThrows(IllegalStateException.class, () -> resultSet.getLong(0)); + assertThrows(IllegalStateException.class, resultSet::getType); + assertThrows(IllegalStateException.class, resultSet::getCurrentRowAsStruct); + + releaseCallbackLatch.countDown(); + assertNull(future.get(5, TimeUnit.SECONDS)); + } finally { + releaseCallbackLatch.countDown(); + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testInitializedDelegateCachedOnlyAfterStartOrCloseCompletes() { + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, false); + when(delegate.getLong(0)).thenReturn(99L); + + AtomicReference resultSetRef = new AtomicReference<>(); + AtomicReference delegateDuringStartCallback = new AtomicReference<>(); + AtomicInteger onStartOrCloseCalls = new AtomicInteger(); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + mockedProvider, + () -> delegate, + 4, + () -> { + onStartOrCloseCalls.incrementAndGet(); + // initializedDelegate must still be null while onStartOrClose.run() is executing so + // concurrent callers cannot fast-path past getOrInitializeDelegate() before lifecycle + // notification completes. + delegateDuringStartCallback.set(resultSetRef.get().initializedDelegate); + })) { + resultSetRef.set(resultSet); + assertNull(resultSet.initializedDelegate); + + assertTrue(resultSet.next()); + assertEquals(1, onStartOrCloseCalls.get()); + assertNull(delegateDuringStartCallback.get()); + assertSame(delegate, resultSet.initializedDelegate); + + assertEquals(99L, resultSet.getLong(0)); + assertFalse(resultSet.next()); + assertEquals(1, onStartOrCloseCalls.get()); + assertSame(delegate, resultSet.initializedDelegate); + } + + // Failing supplier must leave initializedDelegate null while still running onStartOrClose once. + AtomicInteger failingStartCalls = new AtomicInteger(); + try (AsyncResultSetImpl failingResultSet = + new AsyncResultSetImpl( + mockedProvider, + () -> { + throw new IllegalStateException("supplier failed"); + }, + 4, + failingStartCalls::incrementAndGet)) { + assertThrows(IllegalStateException.class, failingResultSet::getMetadata); + assertNull(failingResultSet.initializedDelegate); + assertEquals(1, failingStartCalls.get()); + assertThrows(IllegalStateException.class, failingResultSet::getMetadata); + assertNull(failingResultSet.initializedDelegate); + assertEquals(1, failingStartCalls.get()); + } + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java new file mode 100644 index 000000000000..130da13d4ed2 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java @@ -0,0 +1,1363 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.spanner; + +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.NO_OP_RESULT_SET_LISTENER; +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.drainLongIdsCallback; +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.singleInt64MetadataChunk; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.api.core.ApiFuture; +import com.google.api.core.SettableApiFuture; +import com.google.cloud.spanner.AbstractResultSet.CloseableIterator; +import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.AbstractCloseableIterator; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.ControllableStreamingDelegate; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.GrpcStreamingTestHarness; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.NoOpResultSetListener; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.QueuedExecutorProvider; +import com.google.common.base.Supplier; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.protobuf.ByteString; +import com.google.protobuf.Value; +import com.google.spanner.v1.PartialResultSet; +import com.google.spanner.v1.ResultSetMetadata; +import io.grpc.Status; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for event-driven streaming, non-blocking executor yielding, buffer hysteresis, and {@link + * GrpcResultSet} startup error translation in {@link AsyncResultSetImpl}. + */ +@RunWith(JUnit4.class) +public class AsyncResultSetImplStreamingTest { + private SpannerOptions.CloseableExecutorProvider simpleProvider; + + @Before + public void setup() { + simpleProvider = SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + } + + @After + public void teardown() { + if (simpleProvider != null) { + simpleProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testProducerYieldsSingleThreadExecutorWhenWaitingForStreamData() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(1); + CountDownLatch waitingForStreamDataLatch = new CountDownLatch(1); + CountDownLatch row1ConsumedLatch = new CountDownLatch(1); + doAnswer( + invocation -> { + if (stream.consumedRows.get() == 0) { + return stream.availableRows.get() > 0; + } + boolean available = stream.streamFinished.get(); + if (!available) { + waitingForStreamDataLatch.countDown(); + } + return available; + }) + .when(stream.delegate) + .isDataAvailable(); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + row1ConsumedLatch.countDown(); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + AsyncResultSet.StreamMessageListener listener = + stream.awaitStreamingInitialized(simpleProvider); + verify(stream.delegate, times(1)).isDataAvailable(); + + // Non-flushable partial chunk before resumeToken/bufferFull must not start the producer. + listener.onStreamMessage( + PartialResultSet.newBuilder().addValues(Value.newBuilder().setStringValue("1")).build(), + false); + verify(stream.delegate, times(1)).isDataAvailable(); + + // Flushable chunk starts the producer, delivers row 1, then yields when !isDataAvailable(). + stream.availableRows.set(1); + stream.emitFlushableChunk("tok1", false); + assertTrue(row1ConsumedLatch.await(5, TimeUnit.SECONDS)); + assertTrue(waitingForStreamDataLatch.await(5, TimeUnit.SECONDS)); + + // Single-thread executor must be free while waiting for the next gRPC chunk. + assertTrue(simpleProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + + stream.emitEndOfStream(false); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Collections.singletonList(1L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testImmediateEndOfStreamInitiatesRowProduction() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + StreamingResultSet emptyDelegate = mock(StreamingResultSet.class); + when(emptyDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener emptyListener = invocation.getArgument(0); + emptyListener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + return true; + }); + when(emptyDelegate.isDataAvailable()).thenReturn(true); + when(emptyDelegate.next()).thenReturn(false); + + try (AsyncResultSetImpl immediateEofResultSet = + new AsyncResultSetImpl(simpleProvider, emptyDelegate, 4)) { + ApiFuture emptyFuture = + immediateEofResultSet.setCallback( + callbackExecutor, + cursor -> { + assertEquals(CursorState.DONE, cursor.tryNext()); + return CallbackResponse.DONE; + }); + assertNull(emptyFuture.get(5, TimeUnit.SECONDS)); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testProducerYieldsSingleThreadExecutorWhenBufferIsFullAndResumesOnTryNext() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + final int totalRows = 5; + final int maxBufferSize = 2; + AtomicInteger producedRows = new AtomicInteger(); + CountDownLatch bufferFilledLatch = new CountDownLatch(maxBufferSize); + CountDownLatch pausedCallbackLatch = new CountDownLatch(1); + + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenAnswer(invocation -> producedRows.incrementAndGet() <= totalRows); + when(delegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> { + long id = producedRows.get(); + bufferFilledLatch.countDown(); + return Struct.newBuilder().set("id").to(id).build(); + }); + + AtomicBoolean pauseOnFirstCall = new AtomicBoolean(true); + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, delegate, maxBufferSize)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + if (pauseOnFirstCall.compareAndSet(true, false)) { + pausedCallbackLatch.countDown(); + return CallbackResponse.PAUSE; + } + return drainLongIdsCallback(receivedIds).cursorReady(cursor); + }); + + assertTrue(pausedCallbackLatch.await(5, TimeUnit.SECONDS)); + callbackExecutor.submit(() -> {}).get(5, TimeUnit.SECONDS); + assertTrue(bufferFilledLatch.await(5, TimeUnit.SECONDS)); + + // With buffer at capacity (2 rows), ProduceRowsRunnable returns without pinning the thread. + Future probeFuture = simpleProvider.getExecutor().submit(producedRows::get); + assertEquals(Integer.valueOf(maxBufferSize), probeFuture.get(5, TimeUnit.SECONDS)); + + resultSet.resume(); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L, 3L, 4L, 5L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testFastStreamMessageDuringInitiateStreamingDefersProducerWithoutLosingWakeup() + throws Exception { + SpannerOptions.CloseableExecutorProvider twoThreadProvider = + SpannerOptions.createAsyncExecutorProvider(2, 1L, TimeUnit.SECONDS); + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicBoolean streamPublished = new AtomicBoolean(false); + AtomicInteger availabilityChecksWhileInitiating = new AtomicInteger(); + AtomicInteger rowIndex = new AtomicInteger(); + + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + listener.onStreamMessage( + PartialResultSet.newBuilder() + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build(), + false); + listener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + assertTrue( + twoThreadProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + assertEquals(0, availabilityChecksWhileInitiating.get()); + streamPublished.set(true); + return true; + }); + when(streamingDelegate.isDataAvailable()) + .thenAnswer( + invocation -> { + boolean published = streamPublished.get(); + if (!published) { + availabilityChecksWhileInitiating.incrementAndGet(); + } + return published; + }); + when(streamingDelegate.next()).thenAnswer(invocation -> rowIndex.incrementAndGet() == 1); + when(streamingDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(42L).build()); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(twoThreadProvider, streamingDelegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback(callbackExecutor, drainLongIdsCallback(receivedIds)); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(0, availabilityChecksWhileInitiating.get()); + assertEquals(Collections.singletonList(42L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + twoThreadProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testCustomStreamingResultSetStartupFailureDoesNotCallNext() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + StreamingResultSet customFailingDelegate = mock(StreamingResultSet.class); + when(customFailingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenThrow( + SpannerExceptionFactory.newSpannerException( + ErrorCode.INVALID_ARGUMENT, "custom startup error")); + + try (AsyncResultSetImpl customFailingResultSet = + new AsyncResultSetImpl(simpleProvider, customFailingDelegate, 4)) { + ApiFuture customFailingFuture = + customFailingResultSet.setCallback( + callbackExecutor, + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + ExecutionException customExecutionException = + assertThrows( + ExecutionException.class, () -> customFailingFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.INVALID_ARGUMENT, + ((SpannerException) customExecutionException.getCause()).getErrorCode()); + verify(customFailingDelegate, never()).next(); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testFastEndOfStreamBeforeGrpcInitiateStreamingThrowsPreservesSingleConsumer() { + SpannerOptions.CloseableExecutorProvider twoThreadProvider = + SpannerOptions.createAsyncExecutorProvider(2, 1L, TimeUnit.SECONDS); + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger activeDelegateCalls = new AtomicInteger(); + AtomicInteger maxConcurrentDelegateCalls = new AtomicInteger(); + Runnable enterDelegate = + () -> { + int concurrent = activeDelegateCalls.incrementAndGet(); + maxConcurrentDelegateCalls.accumulateAndGet(concurrent, Math::max); + }; + AbstractResultSet.Listener translatingListener = + new NoOpResultSetListener() { + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + return SpannerExceptionFactory.newSpannerException( + ErrorCode.ABORTED, "translated startup error", exception); + } + }; + CloseableIterator failingIterator = + new AbstractCloseableIterator(true) { + @Override + public boolean initiateStreaming( + AsyncResultSet.StreamMessageListener streamMessageListener) { + enterDelegate.run(); + try { + streamMessageListener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + assertTrue( + twoThreadProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "raw startup error"); + } catch (InterruptedException | ExecutionException | TimeoutException exception) { + throw new RuntimeException(exception); + } finally { + activeDelegateCalls.decrementAndGet(); + } + } + + @Override + public boolean isDataAvailable() { + enterDelegate.run(); + try { + return true; + } finally { + activeDelegateCalls.decrementAndGet(); + } + } + + @Override + public boolean hasNext() { + enterDelegate.run(); + try { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "raw startup error"); + } finally { + activeDelegateCalls.decrementAndGet(); + } + } + }; + + try (AsyncResultSetImpl failingResultSet = + new AsyncResultSetImpl( + twoThreadProvider, () -> new GrpcResultSet(failingIterator, translatingListener), 4)) { + ApiFuture failingFuture = + failingResultSet.setCallback( + callbackExecutor, + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> failingFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.ABORTED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, maxConcurrentDelegateCalls.get()); + } finally { + callbackExecutor.shutdownNow(); + twoThreadProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testProducerWakeupInLoopAndInFinallyPreservesSingleConsumer() throws Exception { + ExecutorService callbackBackingExecutor = Executors.newSingleThreadExecutor(); + ExecutorService grpcDeliveryExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(2); + AtomicInteger activeDelegateCalls = new AtomicInteger(); + AtomicInteger maxConcurrentDelegateCalls = new AtomicInteger(); + AtomicInteger isDataAvailableCalls = new AtomicInteger(); + AtomicBoolean triggerFinallyWakeupOnCallbackSchedule = new AtomicBoolean(false); + + Runnable enterDelegateCall = + () -> { + int concurrent = activeDelegateCalls.incrementAndGet(); + maxConcurrentDelegateCalls.accumulateAndGet(concurrent, Math::max); + }; + + doAnswer( + invocation -> { + enterDelegateCall.run(); + try { + stream.listenerRef.set(invocation.getArgument(0)); + stream.listenerRegistered.countDown(); + return true; + } finally { + activeDelegateCalls.decrementAndGet(); + } + }) + .when(stream.delegate) + .initiateStreaming(any(AsyncResultSet.StreamMessageListener.class)); + doAnswer( + invocation -> { + enterDelegateCall.run(); + int call = isDataAvailableCalls.incrementAndGet(); + try { + if (call == 1) { + return false; + } + if (call == 2) { + grpcDeliveryExecutor + .submit(() -> stream.emitFlushableChunk("tok2", false)) + .get(5, TimeUnit.SECONDS); + return false; + } + if (call == 3 || call == 4) { + return true; + } + if (call == 5) { + triggerFinallyWakeupOnCallbackSchedule.set(true); + return false; + } + return stream.streamFinished.get(); + } finally { + activeDelegateCalls.decrementAndGet(); + } + }) + .when(stream.delegate) + .isDataAvailable(); + doAnswer( + invocation -> { + enterDelegateCall.run(); + try { + return stream.consumedRows.incrementAndGet() <= 2; + } finally { + activeDelegateCalls.decrementAndGet(); + } + }) + .when(stream.delegate) + .next(); + + Executor hookingCallbackExecutor = + command -> { + if (triggerFinallyWakeupOnCallbackSchedule.compareAndSet(true, false)) { + stream.emitEndOfStream(false); + } + callbackBackingExecutor.execute(command); + }; + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback(hookingCallbackExecutor, drainLongIdsCallback(receivedIds)); + + stream.awaitStreamingInitialized(simpleProvider); + stream.emitFlushableChunk("tok1", false); + + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), receivedIds); + assertEquals(1, maxConcurrentDelegateCalls.get()); + } finally { + grpcDeliveryExecutor.shutdownNow(); + callbackBackingExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testIsDataAvailableFailurePropagatesThroughNextToCallbackAndResultFuture() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + listener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + return true; + }); + when(streamingDelegate.isDataAvailable()) + .thenThrow(new IllegalStateException("unexpected availability failure")); + when(streamingDelegate.next()) + .thenThrow( + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "stream broken")); + + AtomicReference callbackObservedException = new AtomicReference<>(); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + callbackObservedException.set(thrown); + throw thrown; + }); + + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNAVAILABLE, ((SpannerException) executionException.getCause()).getErrorCode()); + assertNotNull(callbackObservedException.get()); + assertEquals(ErrorCode.UNAVAILABLE, callbackObservedException.get().getErrorCode()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testGrpcInitiateStreamingFailureTranslatesErrorViaListenerWithoutSecondRpc() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + SettableApiFuture transactionIdFuture = SettableApiFuture.create(); + List listenerEvents = Collections.synchronizedList(new ArrayList<>()); + AtomicInteger initiateStreamingCalls = new AtomicInteger(); + AtomicInteger hasNextCalls = new AtomicInteger(); + + AbstractResultSet.Listener listener = + new NoOpResultSetListener() { + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + listenerEvents.add("onError:" + withBeginTransaction); + SpannerException translated = + withBeginTransaction && exception.getErrorCode() == ErrorCode.CANCELLED + ? SpannerExceptionFactory.newSpannerException( + ErrorCode.ABORTED, "Transaction was aborted", exception) + : exception; + if (withBeginTransaction && !transactionIdFuture.isDone()) { + transactionIdFuture.setException(translated); + } + return translated; + } + + @Override + public void onDone(boolean withBeginTransaction) { + listenerEvents.add("onDone:" + withBeginTransaction); + } + }; + + SpannerException startupException = + SpannerExceptionFactory.asSpannerException( + Status.CANCELLED.withDescription("Transaction was aborted").asRuntimeException()); + + CloseableIterator failingIterator = + new AbstractCloseableIterator(true) { + @Override + public boolean initiateStreaming( + AsyncResultSet.StreamMessageListener streamMessageListener) { + initiateStreamingCalls.incrementAndGet(); + throw startupException; + } + + @Override + public boolean isDataAvailable() { + return initiateStreamingCalls.get() > 0; + } + + @Override + public boolean hasNext() { + hasNextCalls.incrementAndGet(); + throw startupException; + } + }; + + AtomicReference callbackException = new AtomicReference<>(); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, () -> new GrpcResultSet(failingIterator, listener), 4)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + callbackException.set(thrown); + throw thrown; + }); + + ExecutionException futureExecutionException = + assertThrows(ExecutionException.class, () -> resultFuture.get(5, TimeUnit.SECONDS)); + SpannerException futureException = (SpannerException) futureExecutionException.getCause(); + assertEquals(ErrorCode.ABORTED, futureException.getErrorCode()); + assertNotNull(callbackException.get()); + assertEquals(ErrorCode.ABORTED, callbackException.get().getErrorCode()); + + ExecutionException txExecutionException = + assertThrows( + ExecutionException.class, () -> transactionIdFuture.get(5, TimeUnit.SECONDS)); + assertSame(futureException, txExecutionException.getCause()); + assertEquals(1, initiateStreamingCalls.get()); + assertEquals(1, hasNextCalls.get()); + assertEquals(Arrays.asList("onError:true", "onDone:true"), listenerEvents); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testForwardingResultSetWrappingNonStreamingResultSetDeliversRowsIncrementally() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + CountDownLatch allowRow2Latch = new CountDownLatch(1); + AtomicInteger nextCalls = new AtomicInteger(); + ResultSet blockingNonStreaming = mock(ResultSet.class); + when(blockingNonStreaming.next()) + .thenAnswer( + invocation -> { + int call = nextCalls.incrementAndGet(); + if (call == 1) { + return true; + } + if (call == 2) { + assertTrue(allowRow2Latch.await(5, TimeUnit.SECONDS)); + return true; + } + return false; + }); + when(blockingNonStreaming.getCurrentRowAsStruct()) + .thenAnswer(invocation -> Struct.newBuilder().set("id").to((long) nextCalls.get()).build()); + + List received = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl wrappedBlocking = + new AsyncResultSetImpl(simpleProvider, new ForwardingResultSet(blockingNonStreaming), 10)) { + ApiFuture future = + wrappedBlocking.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + long id = cursor.getLong(0); + received.add(id); + if (id == 1L) { + allowRow2Latch.countDown(); + } + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), received); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testNonStreamingInlineCallbackPauseAndDoneStopsProducerImmediately() + throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + + // 1. Inline directExecutor() callback returning DONE after row 1 must stop ProduceRowsRunnable + // immediately without pulling row 2. + AtomicInteger doneNextCalls = new AtomicInteger(); + ResultSet doneDelegate = mock(ResultSet.class); + when(doneDelegate.next()).thenAnswer(invocation -> doneNextCalls.incrementAndGet() <= 3); + when(doneDelegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) doneNextCalls.get()).build()); + + try (AsyncResultSetImpl doneResultSet = + new AsyncResultSetImpl(queuedProvider, doneDelegate, 10)) { + ApiFuture doneFuture = + doneResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable + assertNull(doneFuture.get(5, TimeUnit.SECONDS)); + assertEquals(1, doneNextCalls.get()); + } + + // 2. Inline directExecutor() callback returning PAUSE after row 1 must stop ProduceRowsRunnable + // immediately until resume() is called. + AtomicInteger pauseNextCalls = new AtomicInteger(); + ResultSet pauseDelegate = mock(ResultSet.class); + when(pauseDelegate.next()).thenAnswer(invocation -> pauseNextCalls.incrementAndGet() <= 3); + when(pauseDelegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) pauseNextCalls.get()).build()); + + AtomicBoolean pauseOnFirstRow = new AtomicBoolean(true); + List receivedIds = new ArrayList<>(); + try (AsyncResultSetImpl pauseResultSet = + new AsyncResultSetImpl(queuedProvider, pauseDelegate, 10)) { + ApiFuture pauseFuture = + pauseResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + if (pauseOnFirstRow.compareAndSet(true, false)) { + assertEquals(CursorState.OK, cursor.tryNext()); + receivedIds.add(cursor.getLong(0)); + return CallbackResponse.PAUSE; + } + return drainLongIdsCallback(receivedIds).cursorReady(cursor); + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable -> row 1 -> inline PAUSE -> breaks! + assertEquals(1, pauseNextCalls.get()); + assertEquals(AsyncResultSetImpl.State.PAUSED, pauseResultSet.getState()); + + pauseResultSet.resume(); + queuedProvider.runNext(); // ProduceRowsRunnable -> rows 2 and 3 + EOF + assertNull(pauseFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L, 3L), receivedIds); + } + } + + @Test(timeout = 10_000) + public void testForwardingResultSetWrappingGrpcResultSetAndFailingLazySupplier() { + AbstractResultSet.Listener translatingListener = + new NoOpResultSetListener() { + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + return SpannerExceptionFactory.newSpannerException( + ErrorCode.ABORTED, "wrapped grpc startup translated", exception); + } + }; + CloseableIterator failingIterator = + new AbstractCloseableIterator(true) { + @Override + public boolean initiateStreaming(AsyncResultSet.StreamMessageListener listener) { + throw new UnsupportedOperationException("grpc startup failed"); + } + + @Override + public boolean hasNext() { + throw SpannerExceptionFactory.newSpannerException(ErrorCode.CANCELLED, "raw cancelled"); + } + }; + ResultSet doubleWrappedGrpc = + new ForwardingResultSet( + new ForwardingResultSet(new GrpcResultSet(failingIterator, translatingListener))); + try (AsyncResultSetImpl wrappedGrpcResultSet = + new AsyncResultSetImpl(simpleProvider, doubleWrappedGrpc, 4)) { + ExecutionException failure = + assertThrows( + ExecutionException.class, + () -> + wrappedGrpcResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.ABORTED, ((SpannerException) failure.getCause()).getErrorCode()); + } + + ForwardingResultSet brokenLazyWrapper = + new ForwardingResultSet( + (Supplier) + () -> { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAUTHENTICATED, "lazy delegate supplier failed"); + }); + try (AsyncResultSetImpl brokenWrapperResultSet = + new AsyncResultSetImpl(simpleProvider, brokenLazyWrapper, 4)) { + ExecutionException failure = + assertThrows( + ExecutionException.class, + () -> + brokenWrapperResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNAUTHENTICATED, ((SpannerException) failure.getCause()).getErrorCode()); + } + } + + @Test(timeout = 10_000) + public void testGrpcInitiateStreamingFailureEdgeCases() { + // mode 0: !isDataAvailable() preserves startup exception. + // mode 1: isDataAvailable() == true and next() genuinely returns false (valid metadata chunk + // followed by EOF) without throwing, preserving the original UNKNOWN startup exception. + // mode 2: cancel() during initiateStreaming() skips next() and completes with CANCELLED. + for (int mode = 0; mode < 3; mode++) { + final int currentMode = mode; + final AtomicBoolean metadataEmitted = new AtomicBoolean(false); + CloseableIterator iterator = + new AbstractCloseableIterator(false) { + @Override + public boolean isDataAvailable() { + return currentMode == 1; + } + + @Override + public boolean initiateStreaming(AsyncResultSet.StreamMessageListener listener) { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.UNKNOWN, "startup failure " + currentMode); + } + + @Override + public boolean hasNext() { + return currentMode == 1 && !metadataEmitted.get(); + } + + @Override + public PartialResultSet next() { + if (currentMode == 1 && metadataEmitted.compareAndSet(false, true)) { + return singleInt64MetadataChunk(); + } + throw new NoSuchElementException(); + } + }; + GrpcResultSet grpcDelegate = new GrpcResultSet(iterator, NO_OP_RESULT_SET_LISTENER); + AtomicReference holder = new AtomicReference<>(); + AsyncResultSetImpl grpcAsyncResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + if (currentMode == 2) { + holder.get().cancel(); + } + return grpcDelegate; + }, + 4); + holder.set(grpcAsyncResultSet); + try (AsyncResultSetImpl ignored = grpcAsyncResultSet) { + ExecutionException failure = + assertThrows( + ExecutionException.class, + () -> + grpcAsyncResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS)); + SpannerException cause = (SpannerException) failure.getCause(); + if (currentMode == 2) { + assertEquals(ErrorCode.CANCELLED, cause.getErrorCode()); + } else { + assertEquals(ErrorCode.UNKNOWN, cause.getErrorCode()); + assertTrue(cause.getMessage().contains("startup failure " + currentMode)); + } + } + } + } + + @Test(timeout = 10_000) + public void testBufferHysteresisPartialConsumptionDispatchesZeroExtraProducerTasks() + throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate partialStream = new ControllableStreamingDelegate(3); + List partialReceived = new ArrayList<>(); + try (AsyncResultSetImpl partialResultSet = + new AsyncResultSetImpl(queuedProvider, partialStream.delegate, 10)) { + ApiFuture future = + partialResultSet.setCallback( + MoreExecutors.directExecutor(), drainLongIdsCallback(partialReceived)); + + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); // InitiateStreamingRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + + partialStream.availableRows.set(3); + partialStream.emitFlushableChunk("chunk1", false); + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); // ProduceRowsRunnable + assertEquals(Arrays.asList(1L, 2L, 3L), partialReceived); + assertTrue(queuedProvider.tasks.isEmpty()); + + partialStream.emitEndOfStream(false); + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); + assertNull(future.get(5, TimeUnit.SECONDS)); + } + } + + @Test(timeout = 10_000) + public void testBufferHysteresisBatchThresholdDispatchesSingleRefillTask() throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate batchStream = new ControllableStreamingDelegate(15); + List batchReceived = new ArrayList<>(); + AtomicBoolean pauseAfterEachRow = new AtomicBoolean(true); + try (AsyncResultSetImpl batchResultSet = + new AsyncResultSetImpl(queuedProvider, batchStream.delegate, 10)) { + ApiFuture future = + batchResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + batchReceived.add(cursor.getLong(0)); + if (pauseAfterEachRow.get()) { + return CallbackResponse.PAUSE; + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + + batchStream.availableRows.set(15); + batchStream.emitEndOfStream(true); + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); // ProduceRowsRunnable buffers 10 rows -> callback reads row 1 + assertEquals(10, batchStream.consumedRows.get()); + assertEquals(1, batchReceived.size()); + assertTrue(queuedProvider.tasks.isEmpty()); + + // Incoming stream message while waitingForBufferSpace is true schedules 0 tasks. + batchStream.emitEndOfStream(true); + assertTrue(queuedProvider.tasks.isEmpty()); + + for (int expectedConsumed = 2; expectedConsumed <= 5; expectedConsumed++) { + batchResultSet.resume(); + assertEquals(expectedConsumed, batchReceived.size()); + assertTrue(queuedProvider.tasks.isEmpty()); + } + + pauseAfterEachRow.set(false); + batchResultSet.resume(); + assertEquals(10, batchReceived.size()); + assertEquals(1, queuedProvider.tasks.size()); + + queuedProvider.runNext(); + assertTrue(queuedProvider.tasks.isEmpty()); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(15, batchReceived.size()); + } + } + + @Test(timeout = 10_000) + public void testPreClosedStreamingDelegateCompletesWhenDataImmediatelyAvailable() { + StreamingResultSet preClosedStreamingDelegate = mock(StreamingResultSet.class); + when(preClosedStreamingDelegate.initiateStreaming( + any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + when(preClosedStreamingDelegate.isDataAvailable()).thenReturn(true); + when(preClosedStreamingDelegate.next()).thenReturn(false); + try (AsyncResultSetImpl preClosedResultSet = + new AsyncResultSetImpl(simpleProvider, preClosedStreamingDelegate, 4)) { + assertTrue(preClosedResultSet.toList(reader -> reader.getLong(0)).isEmpty()); + } + } + + @Test(timeout = 10_000) + public void testMidStreamErrorReinvokesCallbackAfterPartialConsumption() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet oneRowThenErrorDelegate = mock(ResultSet.class); + when(oneRowThenErrorDelegate.next()) + .thenReturn(true) + .thenThrow( + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "mid-stream fail")); + when(oneRowThenErrorDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(1L).build()); + BlockingDeque gatedCallbacks = new LinkedBlockingDeque<>(); + try (AsyncResultSetImpl midStreamErrorResultSet = + new AsyncResultSetImpl(queuedProvider, oneRowThenErrorDelegate, 4)) { + AtomicInteger callbackInvocations = new AtomicInteger(); + ApiFuture future = + midStreamErrorResultSet.setCallback( + gatedCallbacks::addLast, + cursor -> { + if (callbackInvocations.incrementAndGet() == 1) { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + return CallbackResponse.CONTINUE; + } + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); + queuedProvider.runNext(); + assertTrue(queuedProvider.tasks.isEmpty()); + assertEquals(1, gatedCallbacks.size()); + gatedCallbacks.removeFirst().run(); + ExecutionException midStreamFailure = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNAVAILABLE, ((SpannerException) midStreamFailure.getCause()).getErrorCode()); + assertEquals(2, callbackInvocations.get()); + } + } + + @Test(timeout = 10_000) + public void testLateStreamMessageAfterInitiateStreamingFailureDoesNotClobberConsumingState() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + AtomicReference lateErrorListenerRef = + new AtomicReference<>(); + StreamingResultSet failingAfterRegisterDelegate = mock(StreamingResultSet.class); + when(failingAfterRegisterDelegate.initiateStreaming( + any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + lateErrorListenerRef.set(invocation.getArgument(0)); + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "init failed after register"); + }); + BlockingDeque lateErrorCallbacks = new LinkedBlockingDeque<>(); + try (AsyncResultSetImpl lateErrorResultSet = + new AsyncResultSetImpl(queuedProvider, failingAfterRegisterDelegate, 4)) { + ApiFuture future = + lateErrorResultSet.setCallback( + lateErrorCallbacks::addLast, + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable -> catches error -> CONSUMING + assertEquals(AsyncResultSetImpl.State.CONSUMING, lateErrorResultSet.getState()); + lateErrorListenerRef.get().onStreamMessage(GrpcStreamIterator.END_OF_STREAM, true); + assertEquals(AsyncResultSetImpl.State.CONSUMING, lateErrorResultSet.getState()); + assertTrue(queuedProvider.tasks.isEmpty()); + lateErrorCallbacks.removeFirst().run(); + ExecutionException exec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.UNAVAILABLE, ((SpannerException) exec.getCause()).getErrorCode()); + } + } + + @Test(timeout = 10_000) + public void testSingleRowPerCallbackContinueReachesDoneAfterLastBufferedRow() throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet twoRowDelegate = mock(ResultSet.class); + when(twoRowDelegate.next()).thenReturn(true, true, false); + when(twoRowDelegate.getCurrentRowAsStruct()) + .thenReturn( + Struct.newBuilder().set("id").to(1L).build(), + Struct.newBuilder().set("id").to(2L).build()); + BlockingDeque gatedCallbacks = new LinkedBlockingDeque<>(); + List receivedIds = new ArrayList<>(); + AtomicInteger callbackInvocations = new AtomicInteger(); + try (AsyncResultSetImpl singleRowConsumerResultSet = + new AsyncResultSetImpl(queuedProvider, twoRowDelegate, 4)) { + ApiFuture future = + singleRowConsumerResultSet.setCallback( + gatedCallbacks::addLast, + cursor -> { + callbackInvocations.incrementAndGet(); + switch (cursor.tryNext()) { + case OK: + receivedIds.add(cursor.getLong(0)); + return CallbackResponse.CONTINUE; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + default: + throw new AssertionError("Unexpected CursorState"); + } + }); + // Run InitiateStreamingRunnable + ProduceRowsRunnable so both rows and finished=true are + // buffered before CallbackRunnable executes. + queuedProvider.runNext(); + queuedProvider.runNext(); + assertTrue(queuedProvider.tasks.isEmpty()); + assertEquals(1, gatedCallbacks.size()); + gatedCallbacks.removeFirst().run(); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), receivedIds); + assertEquals(3, callbackInvocations.get()); + } + } + + @Test(timeout = 10_000) + public void testStreamingFlushesWhenChunksWithoutResumeTokenExceedMaxBufferedChunks() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + final int maxBufferedChunks = 512; + final int prefetchChunks = 1000; + final int unflushedChunkCount = maxBufferedChunks + 1; + GrpcStreamingTestHarness harness = + new GrpcStreamingTestHarness(maxBufferedChunks, prefetchChunks); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch flushedBeforeEofLatch = new CountDownLatch(1); + try (GrpcResultSet grpcResultSet = harness.newGrpcResultSet(); + AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, grpcResultSet, 64)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + receivedIds.add(cursor.getLong(0)); + if (receivedIds.size() == unflushedChunkCount) { + flushedBeforeEofLatch.countDown(); + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + GrpcStreamIterator grpcStream = harness.awaitStreamingInitialized(simpleProvider); + for (int chunkIndex = 1; chunkIndex <= unflushedChunkCount; chunkIndex++) { + PartialResultSet.Builder chunkBuilder = + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue(String.valueOf(chunkIndex))); + if (chunkIndex == 1) { + chunkBuilder.setMetadata(singleInt64MetadataChunk().getMetadata()); + } + grpcStream.consumer().onPartialResultSet(chunkBuilder.build()); + } + + // Even though no resumeToken arrived, bufferIsFull is false (513 < 1000), and the stream has + // not completed yet, ResumableStreamIterator has exceeded maxBufferedChunks (512) and all + // 513 rows must be flushed to the callback without stalling. + assertTrue(flushedBeforeEofLatch.await(2, TimeUnit.SECONDS)); + assertEquals(unflushedChunkCount, receivedIds.size()); + + grpcStream.consumer().onCompleted(); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(unflushedChunkCount, receivedIds.size()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testLargeBufferSizeSchedulesCallbackAtDefaultBatchThresholdBeforeBlockingNext() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger producedCount = new AtomicInteger(); + CountDownLatch firstBatchConsumedLatch = new CountDownLatch(1); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + listener.onStreamMessage( + PartialResultSet.newBuilder() + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build(), + false); + return true; + }); + when(streamingDelegate.isDataAvailable()).thenReturn(true); + when(streamingDelegate.next()) + .thenAnswer( + invocation -> { + int current = producedCount.incrementAndGet(); + if (current <= AsyncResultSetImpl.DEFAULT_BUFFER_SIZE) { + return true; + } + // Simulate row 11 blocking in mid-stream retry backoff; rows 1..10 must already have + // been dispatched to callbackExecutor even though maxBufferSize (100) is not full. + assertTrue(firstBatchConsumedLatch.await(2, TimeUnit.SECONDS)); + return false; + }); + when(streamingDelegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) producedCount.get()).build()); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 100)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + receivedIds.add(cursor.getLong(0)); + if (receivedIds.size() == AsyncResultSetImpl.DEFAULT_BUFFER_SIZE) { + firstBatchConsumedLatch.countDown(); + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(AsyncResultSetImpl.DEFAULT_BUFFER_SIZE, receivedIds.size()); + assertEquals(Long.valueOf(1L), receivedIds.get(0)); + assertEquals(Long.valueOf(10L), receivedIds.get(9)); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testChunkedStringValueSplitAcrossChunksYieldsAndMergesCleanly() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + GrpcStreamingTestHarness harness = new GrpcStreamingTestHarness(16, 8); + ResultSetMetadata stringColumnMetadata = + ResultSetMetadata.newBuilder() + .setRowType( + Type.struct(Type.StructField.of("payload", Type.string())) + .toProto() + .getStructType()) + .build(); + + List receivedValues = Collections.synchronizedList(new ArrayList<>()); + try (GrpcResultSet grpcResultSet = harness.newGrpcResultSet(); + AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, grpcResultSet, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + receivedValues.add(cursor.getString(0)); + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + GrpcStreamIterator grpcStream = harness.awaitStreamingInitialized(simpleProvider); + + // Deliver chunk 1 with chunked_value=true and a resume token: ProduceRowsRunnable wakes up, + // sees GrpcValueIterator#isDataAvailable() == false because the trailing string is still + // incomplete, and yields the single-thread executor cleanly without blocking. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .setMetadata(stringColumnMetadata) + .addValues(Value.newBuilder().setStringValue("hello-")) + .setChunkedValue(true) + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build()); + assertTrue(simpleProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + assertEquals(0, receivedValues.size()); + + // Deliver chunk 2 completing the split string, followed by end-of-stream. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("world")) + .setChunkedValue(false) + .setResumeToken(ByteString.copyFromUtf8("r2")) + .build()); + grpcStream.consumer().onCompleted(); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Collections.singletonList("hello-world"), receivedValues); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testPrefetchChunksReplenishmentDoesNotStallWhenEarlyChunksArriveDuringInitiation() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + final int prefetchChunks = 2; + // Deliver chunk 1 (without resumeToken) during startStream() before InitiateStreamingRunnable + // runs its initial isDataAvailable() check, so InitiateStreamingRunnable drains 1 chunk into + // ResumableStreamIterator.buffer and replenishes gRPC flow control via request(1). + GrpcStreamingTestHarness harness = + new GrpcStreamingTestHarness( + 512, + prefetchChunks, + grpcStream -> + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .setMetadata(singleInt64MetadataChunk().getMetadata()) + .addValues(Value.newBuilder().setStringValue("1")) + .build())); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (GrpcResultSet grpcResultSet = harness.newGrpcResultSet(); + AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, grpcResultSet, 4)) { + ApiFuture future = + resultSet.setCallback(callbackExecutor, drainLongIdsCallback(receivedIds)); + + GrpcStreamIterator grpcStream = harness.awaitStreamingInitialized(simpleProvider); + verify(harness.streamingCall, times(1)).request(prefetchChunks); + verify(harness.streamingCall, times(1)).request(1); + + // Deliver prefetchChunks (2) more non-resume-token chunks: chunk 3 fills GrpcStreamIterator + // (bufferIsFull == true), flipping produceRowsInitiated = true and waking ProduceRowsRunnable + // to drain both chunks into ResumableStreamIterator.buffer and replenish request(1) twice. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("2")) + .build()); + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("3")) + .build()); + assertTrue(simpleProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + verify(harness.streamingCall, times(3)).request(1); + + // Deliver chunk 4 with a resume token + EOF and verify all 4 rows arrive in order. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("4")) + .setResumeToken(ByteString.copyFromUtf8("r4")) + .build()); + grpcStream.consumer().onCompleted(); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L, 3L, 4L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + } + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java index 13e4d784a589..372d0dfa6305 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -37,6 +38,8 @@ import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; import com.google.cloud.spanner.AsyncResultSet.CursorState; import com.google.cloud.spanner.AsyncResultSet.ReadyCallback; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.ControllableStreamingDelegate; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.QueuedExecutorProvider; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.Range; @@ -46,6 +49,9 @@ import com.google.spanner.v1.PartialResultSet; import com.google.spanner.v1.ResultSetMetadata; import com.google.spanner.v1.ResultSetStats; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CountDownLatch; @@ -59,18 +65,19 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.mockito.Mockito; +import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @RunWith(JUnit4.class) public class AsyncResultSetImplTest { private ExecutorProvider mockedProvider; - private ExecutorProvider simpleProvider; + private SpannerOptions.CloseableExecutorProvider simpleProvider; @Before public void setup() { @@ -79,6 +86,13 @@ public void setup() { simpleProvider = SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); } + @After + public void teardown() { + if (simpleProvider != null) { + simpleProvider.close(); + } + } + @SuppressWarnings("unchecked") @Test public void close() { @@ -399,44 +413,54 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { } } - @Test - public void testCallbackIsNotCalledWhilePausedAndCanceled() { + @Test(timeout = 10_000) + public void testCallbackIsNotCalledWhilePausedAndCanceled() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); final AtomicInteger callbackCounter = new AtomicInteger(); + final CountDownLatch pausedLatch = new CountDownLatch(1); ApiFuture callbackResult; - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenAnswer( answer -> { - rs.onStreamMessage(PartialResultSet.newBuilder().build(), false); - return null; + resultSet.onStreamMessage( + PartialResultSet.newBuilder() + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build(), + false); + return Boolean.TRUE; }); + when(delegate.isDataAvailable()).thenReturn(true); callbackResult = - rs.setCallback( + resultSet.setCallback( executor, - resultSet -> { + cursor -> { callbackCounter.getAndIncrement(); + pausedLatch.countDown(); return CallbackResponse.PAUSE; }); - rs.cancel(); + assertTrue(pausedLatch.await(5, TimeUnit.SECONDS)); + resultSet.cancel(); SpannerException exception = assertThrows(SpannerException.class, () -> get(callbackResult)); assertEquals(ErrorCode.CANCELLED, exception.getErrorCode()); - assertEquals(1, callbackCounter.get()); + // 1 callback before cancel() returning PAUSE + 1 post-cancel callback given a chance to + // catch CANCELLED and stopping cleanly when it returns PAUSE without calling tryNext(). + assertEquals(2, callbackCounter.get()); } finally { - executor.shutdown(); + executor.shutdownNow(); } } - @Test + @Test(timeout = 10_000) public void cancel() throws InterruptedException { - Executor executor = Executors.newSingleThreadExecutor(); + ExecutorService executor = Executors.newSingleThreadExecutor(); ResultSet delegate = mock(ResultSet.class); when(delegate.next()).thenReturn(true, true, true, false); when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); @@ -485,12 +509,14 @@ public void cancel() throws InterruptedException { } assertThat(callbackCounter.get()).isIn(Range.closed(2, 4)); assertThat(rowCounter).isIn(Range.closed(2, 3)); + } finally { + executor.shutdownNow(); } } - @Test + @Test(timeout = 10_000) public void callbackReturnsError() throws InterruptedException { - Executor executor = Executors.newSingleThreadExecutor(); + ExecutorService executor = Executors.newSingleThreadExecutor(); ResultSet delegate = mock(ResultSet.class); when(delegate.next()).thenReturn(true, true, true, false); when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); @@ -509,6 +535,8 @@ public void callbackReturnsError() throws InterruptedException { assertThat(se.getErrorCode()).isEqualTo(ErrorCode.UNKNOWN); assertThat(se.getMessage()).contains("async test"); assertThat(callbackCounter.get()).isEqualTo(1); + } finally { + executor.shutdownNow(); } } @@ -539,7 +567,7 @@ public void callbackReturnsErrorWhileBufferIsFull_shouldStopProducer() throws Ex assertThat(se.getErrorCode()).isEqualTo(ErrorCode.UNKNOWN); assertThat(se.getMessage()).contains("async test"); // The producer should stop and release the underlying result set. - Mockito.verify(delegate).close(); + verify(delegate).close(); assertThat(producedRows.get()).isLessThan(simulatedRows); } finally { executor.shutdown(); @@ -548,74 +576,97 @@ public void callbackReturnsErrorWhileBufferIsFull_shouldStopProducer() throws Ex @Test public void callbackReturnsDoneBeforeEnd_shouldStopIteration() throws Exception { - Executor executor = Executors.newSingleThreadExecutor(); - ResultSet delegate = mock(ResultSet.class); - when(delegate.next()).thenReturn(true, true, true, false); - when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); - try (AsyncResultSetImpl rs = - new AsyncResultSetImpl(simpleProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { - rs.setCallback( - executor, - // Not calling resultSet.tryNext() means that it will also never return DONE. - // Instead the callback indicates that it does not want any more rows. - ignored -> CallbackResponse.DONE); - rs.getResult().get(10L, TimeUnit.SECONDS); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, true, true, false); + when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { + resultSet.setCallback( + executor, + // Not calling resultSet.tryNext() means that it will also never return DONE. + // Instead the callback indicates that it does not want any more rows. + ignored -> CallbackResponse.DONE); + resultSet.getResult().get(10L, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); } } @Test public void testOnStreamMessageWhenResumeTokenIsPresent() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(mockedProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { // Marking Streaming as supported - Mockito.when( - delegate.initiateStreaming(Mockito.any(AsyncResultSet.StreamMessageListener.class))) + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenReturn(true); - rs.setCallback(Executors.newSingleThreadExecutor(), ignored -> CallbackResponse.DONE); - rs.onStreamMessage( + resultSet.setCallback(callbackExecutor, ignored -> CallbackResponse.DONE); + ArgumentCaptor runnableCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(mockedProvider.getExecutor(), times(1)).execute(runnableCaptor.capture()); + runnableCaptor.getValue().run(); + verify(mockedProvider.getExecutor(), times(1)).execute(any()); + + resultSet.onStreamMessage( PartialResultSet.newBuilder().addValues(Value.newBuilder().build()).build(), false); + verify(mockedProvider.getExecutor(), times(1)).execute(any()); - rs.onStreamMessage( + resultSet.onStreamMessage( PartialResultSet.newBuilder().setResumeToken(ByteString.copyFromUtf8("test")).build(), false); - Mockito.verify(mockedProvider.getExecutor(), times(2)).execute(Mockito.any()); + verify(mockedProvider.getExecutor(), times(2)).execute(any()); + } finally { + callbackExecutor.shutdownNow(); } } @Test public void testOnStreamMessageWhenCurrentBufferSizeReachedPrefetchChunkSize() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(mockedProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { // Marking Streaming as supported - Mockito.when( - delegate.initiateStreaming(Mockito.any(AsyncResultSet.StreamMessageListener.class))) + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenReturn(true); - rs.setCallback(Executors.newSingleThreadExecutor(), ignored -> CallbackResponse.DONE); - rs.onStreamMessage( + resultSet.setCallback(callbackExecutor, ignored -> CallbackResponse.DONE); + ArgumentCaptor runnableCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(mockedProvider.getExecutor(), times(1)).execute(runnableCaptor.capture()); + runnableCaptor.getValue().run(); + + resultSet.onStreamMessage( PartialResultSet.newBuilder().addValues(Value.newBuilder().build()).build(), true); - Mockito.verify(mockedProvider.getExecutor(), times(2)).execute(Mockito.any()); + verify(mockedProvider.getExecutor(), times(2)).execute(any()); + } finally { + callbackExecutor.shutdownNow(); } } @Test public void testOnStreamMessageWhenAsyncResultIsCancelled() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(mockedProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { // Marking Streaming as supported - Mockito.when( - delegate.initiateStreaming(Mockito.any(AsyncResultSet.StreamMessageListener.class))) + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenReturn(true); - rs.setCallback(Executors.newSingleThreadExecutor(), ignored -> CallbackResponse.DONE); - rs.cancel(); - rs.onStreamMessage( + resultSet.setCallback(callbackExecutor, ignored -> CallbackResponse.DONE); + resultSet.cancel(); + resultSet.onStreamMessage( PartialResultSet.newBuilder().addValues(Value.newBuilder().build()).build(), false); - Mockito.verify(mockedProvider.getExecutor(), times(2)).execute(Mockito.any()); + // Once cancelled, cancel() schedules the callback directly and incoming stream messages must + // not dispatch a wasted ProduceRowsRunnable onto the producer executor. + verify(mockedProvider.getExecutor(), times(1)).execute(any()); + } finally { + callbackExecutor.shutdownNow(); } } @@ -876,20 +927,19 @@ public void testOnStartOrCloseExceptionDoesNotMaskPrimaryException() { public void testSetCallbackRejectsNullArguments() { ResultSet delegate = mock(ResultSet.class); AtomicInteger count = new AtomicInteger(); - AsyncResultSetImpl asyncResultSet = - new AsyncResultSetImpl(simpleProvider, () -> delegate, 10, count::incrementAndGet); - - assertThrows( - NullPointerException.class, - () -> asyncResultSet.setCallback(null, ignored -> CallbackResponse.DONE)); - assertThrows( - NullPointerException.class, - () -> asyncResultSet.setCallback(MoreExecutors.directExecutor(), null)); + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(simpleProvider, () -> delegate, 10, count::incrementAndGet)) { + assertThrows( + NullPointerException.class, + () -> asyncResultSet.setCallback(null, ignored -> CallbackResponse.DONE)); + assertThrows( + NullPointerException.class, + () -> asyncResultSet.setCallback(MoreExecutors.directExecutor(), null)); - // Because arguments were null, setCallback failed before mutating state. - // The result set should still be closeable cleanly, notifying start or close once. - assertEquals(0, count.get()); - asyncResultSet.close(); + // Because arguments were null, setCallback failed before mutating state. + // The result set should still be closeable cleanly, notifying start or close once. + assertEquals(0, count.get()); + } assertEquals(1, count.get()); } @@ -902,22 +952,25 @@ public void testSetCallbackRejectedExecutionNotifiesStartOrClose() { when(provider.shouldAutoClose()).thenReturn(true); AtomicInteger count = new AtomicInteger(); - AsyncResultSetImpl asyncResultSet = - new AsyncResultSetImpl(provider, () -> mock(ResultSet.class), 10, count::incrementAndGet); + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(provider, () -> mock(ResultSet.class), 10, count::incrementAndGet)) { + assertThrows( + RejectedExecutionException.class, + () -> + asyncResultSet.setCallback( + MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); - assertThrows( - RejectedExecutionException.class, - () -> - asyncResultSet.setCallback( - MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); + // State is rolled back to INITIALIZED so cancel() and resume() reject calls cleanly. + assertThrows(IllegalStateException.class, asyncResultSet::cancel); + assertThrows(IllegalStateException.class, asyncResultSet::resume); - // Rejection should immediately trigger start or close notification so that callers - // waiting on query initialization are unblocked. - assertEquals(1, count.get()); - verify(mockService).shutdown(); + // Rejection should immediately trigger start or close notification so that callers + // waiting on query initialization are unblocked. + assertEquals(1, count.get()); + verify(mockService).shutdown(); + } // Closing afterwards is a no-op and does not notify a second time. - asyncResultSet.close(); assertEquals(1, count.get()); } @@ -949,13 +1002,15 @@ public void testSetCallbackRejectedExecutionClosesInitializedDelegate() { @Test public void testRemoveListenerAfterCloseDoesNotThrow() { ResultSet delegate = mock(ResultSet.class); - AsyncResultSetImpl asyncResultSet = new AsyncResultSetImpl(simpleProvider, () -> delegate, 10); Runnable listener = () -> {}; - asyncResultSet.addListener(listener); - asyncResultSet.close(); + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(simpleProvider, () -> delegate, 10)) { + asyncResultSet.addListener(listener); + asyncResultSet.close(); - // Calling removeListener after close should not throw IllegalStateException - asyncResultSet.removeListener(listener); + // Calling removeListener after close should not throw IllegalStateException + asyncResultSet.removeListener(listener); + } } @Test @@ -970,4 +1025,498 @@ public void testToListAsyncRejectsNullArguments() { NullPointerException.class, () -> asyncResultSet.toListAsync(reader -> null, null)); } } + + private static void assertAllSchemaMethodsThrowIllegalState(StructReader reader) { + assertThrows(IllegalStateException.class, reader::getType); + assertThrows(IllegalStateException.class, reader::getColumnCount); + assertThrows(IllegalStateException.class, () -> reader.getColumnIndex("id")); + assertThrows(IllegalStateException.class, () -> reader.getColumnType(0)); + assertThrows(IllegalStateException.class, () -> reader.getColumnType("id")); + } + + @Test(timeout = 10_000) + public void testStaleCurrentRowClearedAcrossNotReadyPauseAndDone() throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + Type rowSchema = Type.struct(Type.StructField.of("id", Type.int64())); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(2); + when(stream.delegate.getType()).thenReturn(rowSchema); + when(stream.delegate.getColumnCount()).thenReturn(1); + when(stream.delegate.getColumnIndex("id")).thenReturn(0); + when(stream.delegate.getColumnType(0)).thenReturn(Type.int64()); + when(stream.delegate.getColumnType("id")).thenReturn(Type.int64()); + + AtomicInteger callbackStep = new AtomicInteger(); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(queuedProvider, stream.delegate, 10)) { + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + int step = callbackStep.incrementAndGet(); + if (step == 1) { + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + assertEquals(1L, cursor.getCurrentRowAsStruct().getLong(0)); + assertEquals(rowSchema, cursor.getType()); + + // Next tryNext() returns NOT_READY: stale Row 1 must be cleared! + assertEquals(CursorState.NOT_READY, cursor.tryNext()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + return CallbackResponse.CONTINUE; + } + if (step == 2) { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(2L, cursor.getLong(0)); + // Return PAUSE while still positioned on Row 2 (without calling tryNext() again). + return CallbackResponse.PAUSE; + } + // Step 3: resumed after PAUSE. Before calling tryNext(), stale Row 2 must be + // cleared even if stream already reached finished = true! + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + + assertEquals(CursorState.DONE, cursor.tryNext()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertEquals(rowSchema, cursor.getType()); + return CallbackResponse.DONE; + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + stream.availableRows.set(1); + stream.emitFlushableChunk("c1", false); + queuedProvider.runNext(); // ProduceRowsRunnable -> Row 1 + NOT_READY + + stream.availableRows.set(2); + stream.emitEndOfStream(false); + queuedProvider.runNext(); // ProduceRowsRunnable -> Row 2 + finished=true -> PAUSE + resultSet.resume(); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(3, callbackStep.get()); + } + } + + @Test(timeout = 10_000) + public void testSchemaMethodsOnDoneForMultiRowAndEmptyResultSets() throws Exception { + Type rowSchema = + Type.struct( + Type.StructField.of("id", Type.int64()), Type.StructField.of("name", Type.string())); + + // 1. Empty PrePopulatedResultSet (0 rows): on DONE, all schema methods (including returning + // null for getColumnType("nonexistent")) succeed while row value getters throw. + ResultSet zeroRowDelegate = ResultSets.forRows(rowSchema, Collections.emptyList()); + try (AsyncResultSetImpl zeroRowResultSet = + new AsyncResultSetImpl(simpleProvider, zeroRowDelegate, 4)) { + ApiFuture future = + zeroRowResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertAllSchemaMethodsThrowIllegalState(cursor); + assertEquals(CursorState.DONE, cursor.tryNext()); + assertEquals(rowSchema, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(0, cursor.getColumnIndex("id")); + assertEquals(1, cursor.getColumnIndex("name")); + assertEquals(Type.int64(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType("name")); + assertNull(cursor.getColumnType("nonexistent")); + assertThrows( + IllegalArgumentException.class, () -> cursor.getColumnIndex("nonexistent")); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + return CallbackResponse.DONE; + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertAllSchemaMethodsThrowIllegalState(zeroRowResultSet); + } + + // 2. Multi-rowResultSet: on OK, schema methods read from currentRow without touching delegate + // schema methods; on DONE, schema methods delegate to underlying ResultSet. + ResultSet twoRowDelegate = + ResultSets.forRows( + rowSchema, + Arrays.asList( + Struct.newBuilder().set("id").to(10L).set("name").to("a").build(), + Struct.newBuilder().set("id").to(20L).set("name").to("b").build())); + try (AsyncResultSetImpl multiRowResultSet = + new AsyncResultSetImpl(simpleProvider, twoRowDelegate, 4)) { + ApiFuture future = + multiRowResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + assertEquals(rowSchema, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(0, cursor.getColumnIndex("id")); + assertEquals(Type.int64(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType("name")); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + assertEquals(rowSchema, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(1, cursor.getColumnIndex("name")); + assertEquals(Type.int64(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType("name")); + assertNull(cursor.getColumnType("nonexistent")); + return CallbackResponse.DONE; + } + } + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + } + } + + @Test(timeout = 10_000) + public void testStaleCurrentRowClearedOnCancelAndMidStreamError() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + Type rowSchema = Type.struct(Type.StructField.of("id", Type.int64())); + ResultSet twoRowSync = + ResultSets.forRows( + rowSchema, + Arrays.asList( + Struct.newBuilder().set("id").to(1L).build(), + Struct.newBuilder().set("id").to(2L).build())); + BlockingDeque gatedCallbacks = new LinkedBlockingDeque<>(); + try (AsyncResultSetImpl cancelAfterRow1 = + new AsyncResultSetImpl(queuedProvider, twoRowSync, 10)) { + ApiFuture future = + cancelAfterRow1.setCallback( + gatedCallbacks::addLast, + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + cancelAfterRow1.cancel(); + SpannerException cancelled = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.CANCELLED, cancelled.getErrorCode()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable (reads both rows + finished = true) + gatedCallbacks.removeFirst().run(); + ExecutionException exec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.CANCELLED, ((SpannerException) exec.getCause()).getErrorCode()); + } + + ResultSet row1ThenError = mock(ResultSet.class); + when(row1ThenError.next()) + .thenReturn(true) + .thenThrow( + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "mid-stream boom")); + when(row1ThenError.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(9L).build()); + try (AsyncResultSetImpl errorAfterRow1 = + new AsyncResultSetImpl(queuedProvider, row1ThenError, 10)) { + ApiFuture future = + errorAfterRow1.setCallback( + gatedCallbacks::addLast, + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(9L, cursor.getLong(0)); + SpannerException err = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.UNAVAILABLE, err.getErrorCode()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable (buffers row 1 + records UNAVAILABLE) + gatedCallbacks.removeFirst().run(); + ExecutionException exec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.UNAVAILABLE, ((SpannerException) exec.getCause()).getErrorCode()); + } + } + + @Test + public void testBigDecimalStateValidationAndDelegation() { + AtomicInteger unstartedSupplierCalls = new AtomicInteger(); + AsyncResultSetImpl closedBeforeStart = + new AsyncResultSetImpl( + simpleProvider, + () -> { + unstartedSupplierCalls.incrementAndGet(); + return mock(ResultSet.class); + }, + 4); + closedBeforeStart.close(); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimal(0)); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimal("n")); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimalList(0)); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimalList("na")); + assertEquals(0, unstartedSupplierCalls.get()); + + BigDecimal expectedDecimal = new BigDecimal("12.34"); + List expectedDecimalList = Arrays.asList(expectedDecimal, new BigDecimal("56.78")); + Struct numericRow = + Struct.newBuilder() + .set("n") + .to(expectedDecimal) + .set("na") + .toNumericArray(expectedDecimalList) + .build(); + ResultSet numericDelegate = + ResultSets.forRows(numericRow.getType(), Collections.singletonList(numericRow)); + try (AsyncResultSetImpl numericResultSet = + new AsyncResultSetImpl(simpleProvider, numericDelegate, 4)) { + List results = + numericResultSet.toList( + reader -> { + assertEquals(expectedDecimal, reader.getBigDecimal(0)); + assertEquals(expectedDecimal, reader.getBigDecimal("n")); + assertEquals(expectedDecimalList, reader.getBigDecimalList(1)); + assertEquals(expectedDecimalList, reader.getBigDecimalList("na")); + return reader.getBigDecimal(0); + }); + assertEquals(Collections.singletonList(expectedDecimal), results); + } + } + + @Test + public void testSyncModeStateValidation() { + assertThrows( + IllegalArgumentException.class, + () -> new AsyncResultSetImpl(simpleProvider, mock(ResultSet.class), 0)); + + Type syncSchema = Type.struct(Type.StructField.of("id", Type.int64())); + Struct singleRow = Struct.newBuilder().set("id").to(7L).build(); + ResultSet syncDelegate = ResultSets.forRows(syncSchema, Collections.singletonList(singleRow)); + try (AsyncResultSetImpl syncResultSet = + new AsyncResultSetImpl(simpleProvider, syncDelegate, 4)) { + assertThrows(IllegalStateException.class, syncResultSet::tryNext); + assertThrows(IllegalStateException.class, syncResultSet::cancel); + assertThrows(IllegalStateException.class, syncResultSet::resume); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(syncResultSet); + + assertTrue(syncResultSet.next()); + assertThrows(IllegalStateException.class, syncResultSet::cancel); + assertThrows(IllegalStateException.class, syncResultSet::resume); + assertThrows( + IllegalStateException.class, + () -> + syncResultSet.setCallback( + MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); + assertEquals(7L, syncResultSet.getLong(0)); + assertEquals(singleRow, syncResultSet.getCurrentRowAsStruct()); + assertEquals(syncSchema, syncResultSet.getType()); + assertEquals(1, syncResultSet.getColumnCount()); + assertEquals(0, syncResultSet.getColumnIndex("id")); + assertEquals(Type.int64(), syncResultSet.getColumnType(0)); + assertEquals(Type.int64(), syncResultSet.getColumnType("id")); + + assertFalse(syncResultSet.next()); + assertEquals(syncSchema, syncResultSet.getType()); + assertEquals(1, syncResultSet.getColumnCount()); + assertEquals(0, syncResultSet.getColumnIndex("id")); + assertEquals(Type.int64(), syncResultSet.getColumnType(0)); + assertEquals(Type.int64(), syncResultSet.getColumnType("id")); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + + syncResultSet.close(); + assertThrows(IllegalStateException.class, () -> syncResultSet.getLong(0)); + assertAllSchemaMethodsThrowIllegalState(syncResultSet); + } + } + + @Test + public void testSyncModeTransientSupplierFailureCachesExceptionWithoutLeakingDelegate() { + SpannerException transientFailure = + SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "transient supplier failure"); + AtomicInteger supplierCalls = new AtomicInteger(); + ResultSet leakedDelegate = mock(ResultSet.class); + + try (AsyncResultSetImpl syncResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + if (supplierCalls.incrementAndGet() == 1) { + throw transientFailure; + } + return leakedDelegate; + }, + 4)) { + assertSame(transientFailure, assertThrows(SpannerException.class, syncResultSet::next)); + assertEquals(1, supplierCalls.get()); + + // Every StructReader and schema/metadata method in SYNC mode must route through + // getOrInitializeDelegate(), rethrowing the cached supplierException without invoking the + // underlying Supplier a second time or leaking a newly created ResultSet. + assertSame( + transientFailure, assertThrows(SpannerException.class, () -> syncResultSet.getLong(0))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getString("id"))); + assertSame( + transientFailure, assertThrows(SpannerException.class, () -> syncResultSet.isNull(0))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getBigDecimal(0))); + assertSame(transientFailure, assertThrows(SpannerException.class, syncResultSet::getType)); + assertSame( + transientFailure, assertThrows(SpannerException.class, syncResultSet::getColumnCount)); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getColumnIndex("id"))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getColumnType(0))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getColumnType("id"))); + assertSame(transientFailure, assertThrows(SpannerException.class, syncResultSet::getStats)); + assertSame( + transientFailure, assertThrows(SpannerException.class, syncResultSet::getMetadata)); + assertEquals(1, supplierCalls.get()); + } + assertEquals(1, supplierCalls.get()); + } + + @Test + public void testSyncModeNextExceptionClearsStaleCurrentRow() { + Struct row1 = Struct.newBuilder().set("id").to(1L).build(); + SpannerException row2Failure = + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "row 2 stream failure"); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true).thenThrow(row2Failure); + when(delegate.getCurrentRowAsStruct()).thenReturn(row1); + when(delegate.getLong(0)).thenReturn(1L).thenThrow(new IllegalStateException("invalid row")); + + try (AsyncResultSetImpl syncResultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + assertTrue(syncResultSet.next()); + assertEquals(1L, syncResultSet.getLong(0)); + assertEquals(row1, syncResultSet.getCurrentRowAsStruct()); + + assertSame(row2Failure, assertThrows(SpannerException.class, syncResultSet::next)); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + assertThrows(IllegalStateException.class, () -> syncResultSet.getLong(0)); + } + } + + @Test(timeout = 10_000) + public void testExternalTryNextAndStructReaderRejectedAcrossAsyncStates() throws Exception { + Struct singleRow = Struct.newBuilder().set("id").to(7L).build(); + CountDownLatch callbackQueuedLatch = new CountDownLatch(1); + CountDownLatch releaseQueuedCallbackLatch = new CountDownLatch(1); + CountDownLatch pausedLatch = new CountDownLatch(1); + ExecutorService callbackBackingExecutor = Executors.newSingleThreadExecutor(); + Executor gatedCallbackExecutor = + command -> { + if (callbackQueuedLatch.getCount() > 0) { + callbackBackingExecutor.execute( + () -> { + callbackQueuedLatch.countDown(); + try { + releaseQueuedCallbackLatch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + return; + } + command.run(); + }); + } else { + callbackBackingExecutor.execute(command); + } + }; + + ResultSet asyncDelegate = mock(ResultSet.class); + when(asyncDelegate.next()).thenReturn(true, false); + when(asyncDelegate.getCurrentRowAsStruct()).thenReturn(singleRow); + AtomicInteger callbackInvocations = new AtomicInteger(); + + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(simpleProvider, asyncDelegate, 4)) { + ApiFuture resultFuture = + asyncResultSet.setCallback( + gatedCallbackExecutor, + cursor -> { + int call = callbackInvocations.incrementAndGet(); + if (call == 1) { + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(7L, cursor.getLong(0)); + assertEquals(singleRow, cursor.getCurrentRowAsStruct()); + pausedLatch.countDown(); + return CallbackResponse.PAUSE; + } + assertEquals(CursorState.DONE, cursor.tryNext()); + return CallbackResponse.PAUSE; + }); + + assertThrows( + IllegalStateException.class, + () -> + asyncResultSet.setCallback( + MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); + assertThrows(IllegalStateException.class, asyncResultSet::next); + assertThrows(IllegalStateException.class, () -> asyncResultSet.removeListener(() -> {})); + + assertTrue(callbackQueuedLatch.await(5, TimeUnit.SECONDS)); + assertEquals(AsyncResultSetImpl.State.CONSUMING, asyncResultSet.getState()); + assertThrows(IllegalStateException.class, asyncResultSet::tryNext); + assertThrows(IllegalStateException.class, asyncResultSet::getCurrentRowAsStruct); + assertThrows(IllegalStateException.class, () -> asyncResultSet.getLong(0)); + + releaseQueuedCallbackLatch.countDown(); + assertTrue(pausedLatch.await(5, TimeUnit.SECONDS)); + callbackBackingExecutor.submit(() -> {}).get(5, TimeUnit.SECONDS); + + assertEquals(AsyncResultSetImpl.State.PAUSED, asyncResultSet.getState()); + assertThrows(IllegalStateException.class, asyncResultSet::tryNext); + assertThrows(IllegalStateException.class, asyncResultSet::getCurrentRowAsStruct); + + asyncResultSet.resume(); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + + assertEquals(AsyncResultSetImpl.State.DONE, asyncResultSet.getState()); + asyncResultSet.cancel(); + asyncResultSet.resume(); + assertEquals(AsyncResultSetImpl.State.DONE, asyncResultSet.getState()); + assertThrows(IllegalStateException.class, asyncResultSet::tryNext); + assertThrows(IllegalStateException.class, asyncResultSet::getCurrentRowAsStruct); + } finally { + callbackBackingExecutor.shutdownNow(); + } + } + + @Test + public void testSyncModeNextDoesNotCopyCurrentRowAsStructUnlessRequested() { + Struct row2Struct = Struct.newBuilder().set("id").to(20L).build(); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, true, false); + when(delegate.getLong(0)).thenReturn(10L, 20L); + when(delegate.getCurrentRowAsStruct()).thenReturn(row2Struct); + + try (AsyncResultSetImpl syncResultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + assertTrue(syncResultSet.next()); + assertEquals(10L, syncResultSet.getLong(0)); + verify(delegate, never()).getCurrentRowAsStruct(); + + assertTrue(syncResultSet.next()); + assertEquals(20L, syncResultSet.getLong(0)); + verify(delegate, never()).getCurrentRowAsStruct(); + assertSame(row2Struct, syncResultSet.getCurrentRowAsStruct()); + verify(delegate, times(1)).getCurrentRowAsStruct(); + + assertFalse(syncResultSet.next()); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + verify(delegate, times(1)).getCurrentRowAsStruct(); + } + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java new file mode 100644 index 000000000000..c20d35cb1715 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java @@ -0,0 +1,298 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.spanner; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.api.gax.core.ExecutorProvider; +import com.google.api.gax.retrying.RetrySettings; +import com.google.cloud.spanner.AbstractResultSet.CloseableIterator; +import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; +import com.google.cloud.spanner.AsyncResultSet.ReadyCallback; +import com.google.cloud.spanner.ErrorHandler.DefaultErrorHandler; +import com.google.cloud.spanner.XGoogSpannerRequestId.NoopRequestIdCreator; +import com.google.cloud.spanner.spi.v1.SpannerRpc; +import com.google.cloud.spanner.v1.stub.SpannerStubSettings; +import com.google.protobuf.ByteString; +import com.google.spanner.v1.MultiplexedSessionPrecommitToken; +import com.google.spanner.v1.PartialResultSet; +import com.google.spanner.v1.ResultSetMetadata; +import com.google.spanner.v1.Transaction; +import io.opencensus.trace.Tracing; +import io.opentelemetry.api.OpenTelemetry; +import java.time.Duration; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import org.jspecify.annotations.Nullable; + +/** Shared test fixtures for {@link AsyncResultSetImpl} unit tests. */ +final class AsyncResultSetImplTestUtil { + + static class NoOpResultSetListener implements AbstractResultSet.Listener { + @Override + public void onTransactionMetadata(Transaction transaction, boolean shouldIncludeId) {} + + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + return exception; + } + + @Override + public void onDone(boolean withBeginTransaction) {} + + @Override + public void onPrecommitToken(MultiplexedSessionPrecommitToken token) {} + } + + static final AbstractResultSet.Listener NO_OP_RESULT_SET_LISTENER = new NoOpResultSetListener(); + + abstract static class AbstractCloseableIterator implements CloseableIterator { + private final boolean withBeginTransaction; + + AbstractCloseableIterator(boolean withBeginTransaction) { + this.withBeginTransaction = withBeginTransaction; + } + + @Override + public void close(@Nullable String message) {} + + @Override + public boolean isWithBeginTransaction() { + return withBeginTransaction; + } + + @Override + public boolean isLastStatement() { + return false; + } + + @Override + public PartialResultSet next() { + throw new NoSuchElementException(); + } + } + + static final class QueuedExecutorProvider implements ExecutorProvider { + final BlockingDeque tasks = new LinkedBlockingDeque<>(); + final ScheduledExecutorService service = mock(ScheduledExecutorService.class); + private final boolean autoClose; + + QueuedExecutorProvider(boolean autoClose) { + this.autoClose = autoClose; + doAnswer( + invocation -> { + tasks.addLast(invocation.getArgument(0)); + return null; + }) + .when(service) + .execute(any(Runnable.class)); + } + + @Override + public boolean shouldAutoClose() { + return autoClose; + } + + @Override + public ScheduledExecutorService getExecutor() { + return service; + } + + void runNext() { + tasks.removeFirst().run(); + } + } + + static final class ControllableStreamingDelegate { + final StreamingResultSet delegate = mock(StreamingResultSet.class); + final AtomicReference listenerRef = + new AtomicReference<>(); + final CountDownLatch listenerRegistered = new CountDownLatch(1); + final AtomicInteger availableRows = new AtomicInteger(); + final AtomicInteger consumedRows = new AtomicInteger(); + final AtomicBoolean streamFinished = new AtomicBoolean(); + + ControllableStreamingDelegate(int totalRows) { + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + listenerRef.set(invocation.getArgument(0)); + listenerRegistered.countDown(); + return true; + }); + when(delegate.isDataAvailable()) + .thenAnswer( + invocation -> streamFinished.get() || consumedRows.get() < availableRows.get()); + when(delegate.next()).thenAnswer(invocation -> consumedRows.incrementAndGet() <= totalRows); + when(delegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) consumedRows.get()).build()); + } + + AsyncResultSet.StreamMessageListener awaitListener() throws InterruptedException { + assertTrue(listenerRegistered.await(5, TimeUnit.SECONDS)); + return listenerRef.get(); + } + + /** + * Waits until {@code initiateStreaming} has registered the listener AND {@code + * InitiateStreamingRunnable} has finished its initial availability check and yielded on {@code + * provider}'s single-thread executor. + */ + AsyncResultSet.StreamMessageListener awaitStreamingInitialized(ExecutorProvider provider) + throws Exception { + AsyncResultSet.StreamMessageListener listener = awaitListener(); + assertTrue(provider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + return listener; + } + + void emitFlushableChunk(String token, boolean bufferIsFull) { + listenerRef + .get() + .onStreamMessage( + PartialResultSet.newBuilder().setResumeToken(ByteString.copyFromUtf8(token)).build(), + bufferIsFull); + } + + void emitEndOfStream(boolean bufferIsFull) { + streamFinished.set(true); + listenerRef.get().onStreamMessage(GrpcStreamIterator.END_OF_STREAM, bufferIsFull); + } + } + + static final class GrpcStreamingTestHarness { + final SpannerRpc.StreamingCall streamingCall = mock(SpannerRpc.StreamingCall.class); + final ResumableStreamIterator resumableIterator; + private final AtomicReference grpcStreamRef = new AtomicReference<>(); + private final CountDownLatch streamStartedLatch = new CountDownLatch(1); + + GrpcStreamingTestHarness(int maxBufferSize, int prefetchChunks) { + this(maxBufferSize, prefetchChunks, ignored -> {}); + } + + GrpcStreamingTestHarness( + int maxBufferSize, int prefetchChunks, Consumer onStartStream) { + TraceWrapper tracer = + new TraceWrapper(Tracing.getTracer(), OpenTelemetry.noop().getTracer(""), false); + ISpan parentSpan = tracer.spanBuilder("test"); + RetrySettings retrySettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofMillis(10)) + .setMaxRetryDelayDuration(Duration.ofMillis(100)) + .build(); + this.resumableIterator = + new ResumableStreamIterator( + maxBufferSize, + "query", + parentSpan, + tracer, + DefaultErrorHandler.INSTANCE, + retrySettings, + SpannerStubSettings.newBuilder().executeStreamingSqlSettings().getRetryableCodes(), + NoopRequestIdCreator.INSTANCE) { + @Override + CloseableIterator startStream( + ByteString resumeToken, + AsyncResultSet.StreamMessageListener streamMessageListener, + XGoogSpannerRequestId requestId) { + GrpcStreamIterator grpcStream = new GrpcStreamIterator(false, prefetchChunks, false); + if (streamMessageListener != null) { + grpcStream.registerListener(streamMessageListener); + } + grpcStream.setCall(streamingCall); + onStartStream.accept(grpcStream); + grpcStreamRef.set(grpcStream); + streamStartedLatch.countDown(); + return grpcStream; + } + }; + } + + GrpcResultSet newGrpcResultSet() { + return new GrpcResultSet(resumableIterator, NO_OP_RESULT_SET_LISTENER); + } + + GrpcStreamIterator awaitStreamingInitialized(ExecutorProvider provider) throws Exception { + assertTrue(streamStartedLatch.await(5, TimeUnit.SECONDS)); + assertTrue(provider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + GrpcStreamIterator grpcStream = grpcStreamRef.get(); + assertNotNull(grpcStream); + return grpcStream; + } + } + + static ExecutorProvider executorProviderOf(ScheduledExecutorService service, boolean autoClose) { + return new ExecutorProvider() { + @Override + public boolean shouldAutoClose() { + return autoClose; + } + + @Override + public ScheduledExecutorService getExecutor() { + return service; + } + }; + } + + static PartialResultSet singleInt64MetadataChunk() { + return PartialResultSet.newBuilder() + .setMetadata( + ResultSetMetadata.newBuilder() + .setRowType( + Type.struct(Type.StructField.of("id", Type.int64())).toProto().getStructType())) + .build(); + } + + static ReadyCallback drainLongIdsCallback(List sink) { + return cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + sink.add(cursor.getLong(0)); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }; + } + + @SuppressWarnings("unchecked") + static RuntimeException sneakyThrow(Throwable throwable) throws E { + throw (E) throwable; + } + + private AsyncResultSetImplTestUtil() {} +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java index 1251ee270faf..10d0f07eab22 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java @@ -19,7 +19,11 @@ import static com.google.cloud.spanner.MockSpannerTestUtil.*; import static com.google.cloud.spanner.SpannerApiFutures.get; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.api.core.ApiFuture; @@ -28,16 +32,19 @@ import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.cloud.NoCredentials; import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime; import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; import com.google.common.collect.ContiguousSet; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; +import com.google.spanner.v1.ExecuteSqlRequest; import io.grpc.Server; import io.grpc.Status; import io.grpc.inprocess.InProcessServerBuilder; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.LinkedList; @@ -49,6 +56,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -431,6 +440,203 @@ public void cancel() throws Exception { assertThat(values).containsExactly("v1"); } + @Test(timeout = 10_000) + public void concurrentQueriesOnSingleThreadAsyncExecutorDoNotBlockWhenPausedOrFrozen() + throws Exception { + Statement tenRowStatement = + Statement.of("SELECT * FROM TestTable WHERE Key BETWEEN 'k1' AND 'k10'"); + mockSpanner.putStatementResult( + StatementResult.query( + tenRowStatement, generateKeyValueResultSet(ContiguousSet.closed(1, 10)))); + List expectedValues = + Arrays.asList("v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10"); + + SpannerOptions.CloseableExecutorProvider singleThreadAsyncProvider = + SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + ExecutorService pausedCallbackExecutor = Executors.newSingleThreadExecutor(); + try (Spanner singleThreadSpanner = createSingleThreadSpanner(singleThreadAsyncProvider)) { + DatabaseClient singleThreadClient = + singleThreadSpanner.getDatabaseClient( + DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE)); + + // Warm up session initialization before freezing mockSpanner so executeQueryAsync starts + // ExecuteStreamingSql directly without waiting on CreateSession. + try (AsyncResultSet warmup = + singleThreadClient.singleUse().executeQueryAsync(READ_ONE_KEY_VALUE_STATEMENT)) { + assertEquals( + Collections.singletonList("v1"), + warmup.toListAsync(row -> row.getString("Value"), executor).get(5, TimeUnit.SECONDS)); + } + + // 1. Stalled server stream (mockSpanner.freeze()) must not pin the 1 async executor thread. + mockSpanner.freeze(); + ApiFuture> frozenRowsFuture; + try (AsyncResultSet frozenResultSet = + singleThreadClient.singleUse().executeQueryAsync(tenRowStatement)) { + frozenRowsFuture = frozenResultSet.toListAsync(row -> row.getString("Value"), executor); + assertTrue( + singleThreadAsyncProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + assertFalse(frozenRowsFuture.isDone()); + mockSpanner.unfreeze(); + assertEquals(expectedValues, frozenRowsFuture.get(5, TimeUnit.SECONDS)); + } finally { + mockSpanner.unfreeze(); + } + + // 2. A PAUSED query with a full row buffer (bufferRows(2)) on a 10-row stream must yield the + // 1 async executor thread so 3 concurrent streaming queries complete to DONE without + // deadlocking before the paused query is resumed. + CountDownLatch firstRowPausedLatch = new CountDownLatch(1); + AtomicBoolean pauseOnFirstRow = new AtomicBoolean(true); + List pausedValues = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSet pausedResultSet = + singleThreadClient + .singleUse() + .executeQueryAsync(tenRowStatement, Options.bufferRows(2))) { + ApiFuture pausedFinished = + pausedResultSet.setCallback( + pausedCallbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + pausedValues.add(cursor.getString("Value")); + if (pauseOnFirstRow.compareAndSet(true, false)) { + firstRowPausedLatch.countDown(); + return CallbackResponse.PAUSE; + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + assertTrue(firstRowPausedLatch.await(5, TimeUnit.SECONDS)); + pausedCallbackExecutor.submit(() -> {}).get(5, TimeUnit.SECONDS); + singleThreadAsyncProvider.getExecutor().submit(() -> null).get(5, TimeUnit.SECONDS); + + List>> concurrentFutures = new ArrayList<>(); + for (int queryIndex = 0; queryIndex < 3; queryIndex++) { + try (AsyncResultSet concurrentResultSet = + singleThreadClient.singleUse().executeQueryAsync(tenRowStatement)) { + concurrentFutures.add( + concurrentResultSet.toListAsync(row -> row.getString("Value"), executor)); + } + } + List> concurrentResults = + ApiFutures.allAsList(concurrentFutures).get(5, TimeUnit.SECONDS); + for (List rows : concurrentResults) { + assertEquals(expectedValues, rows); + } + assertFalse(pausedFinished.isDone()); + + pausedResultSet.resume(); + assertNull(pausedFinished.get(5, TimeUnit.SECONDS)); + assertEquals(expectedValues, pausedValues); + } + } finally { + mockSpanner.unfreeze(); + pausedCallbackExecutor.shutdownNow(); + singleThreadAsyncProvider.close(); + } + } + + @Test(timeout = 10_000) + public void midStreamUnavailableResumesCleanlyOnSingleThreadAsyncExecutor() throws Exception { + Statement tenRowStatement = + Statement.of("SELECT * FROM TestTable WHERE Key BETWEEN 'k1' AND 'k10' ORDER BY Key"); + mockSpanner.putStatementResult( + StatementResult.query( + tenRowStatement, generateKeyValueResultSet(ContiguousSet.closed(1, 10)))); + List expectedValues = + Arrays.asList("v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10"); + + SpannerOptions.CloseableExecutorProvider singleThreadAsyncProvider = + SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + try (Spanner singleThreadSpanner = createSingleThreadSpanner(singleThreadAsyncProvider)) { + DatabaseClient singleThreadClient = + singleThreadSpanner.getDatabaseClient( + DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE)); + + mockSpanner.clearRequests(); + mockSpanner.setExecuteStreamingSqlExecutionTime( + SimulatedExecutionTime.ofStreamException(Status.UNAVAILABLE.asRuntimeException(), 1)); + try (AsyncResultSet resultSet = + singleThreadClient.singleUse().executeQueryAsync(tenRowStatement)) { + List actualValues = + resultSet.toListAsync(row -> row.getString("Value"), executor).get(5, TimeUnit.SECONDS); + assertEquals(expectedValues, actualValues); + } + + List sqlRequests = mockSpanner.getRequestsOfType(ExecuteSqlRequest.class); + assertEquals(2, sqlRequests.size()); + assertTrue(sqlRequests.get(0).getResumeToken().isEmpty()); + assertFalse(sqlRequests.get(1).getResumeToken().isEmpty()); + } finally { + singleThreadAsyncProvider.close(); + } + } + + @Test(timeout = 10_000) + public void schemaGettersWorkOnDoneForMultiRowAndEmptyQueries() throws Exception { + assertSchemaGettersWorkOnDone( + READ_MULTIPLE_KEY_VALUE_STATEMENT, Arrays.asList("v1", "v2", "v3")); + assertSchemaGettersWorkOnDone(READ_ONE_EMPTY_KEY_VALUE_STATEMENT, Collections.emptyList()); + } + + private void assertSchemaGettersWorkOnDone(Statement statement, List expectedValues) + throws Exception { + List actualValues = Collections.synchronizedList(new ArrayList<>()); + AtomicBoolean assertedOnDone = new AtomicBoolean(false); + try (AsyncResultSet resultSet = client.singleUse().executeQueryAsync(statement)) { + ApiFuture finished = + resultSet.setCallback( + executor, + cursor -> { + while (true) { + CursorState state = cursor.tryNext(); + switch (state) { + case OK: + actualValues.add(cursor.getString("Value")); + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + assertEquals(READ_TABLE_TYPE, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(0, cursor.getColumnIndex("Key")); + assertEquals(1, cursor.getColumnIndex("Value")); + assertEquals(Type.string(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType(1)); + assertEquals(Type.string(), cursor.getColumnType("Key")); + assertEquals(Type.string(), cursor.getColumnType("Value")); + assertedOnDone.set(true); + return CallbackResponse.DONE; + } + } + }); + assertNull(finished.get(5, TimeUnit.SECONDS)); + } + assertTrue(assertedOnDone.get()); + assertEquals(expectedValues, actualValues); + } + + private Spanner createSingleThreadSpanner( + SpannerOptions.CloseableExecutorProvider asyncExecutorProvider) { + return SpannerOptions.newBuilder() + .setProjectId(TEST_PROJECT) + .setChannelProvider(channelProvider) + .setCredentials(NoCredentials.getInstance()) + .setAsyncExecutorProvider(asyncExecutorProvider) + .setSessionPoolOption( + SessionPoolOptions.newBuilder().setFailOnSessionLeak().setMinSessions(0).build()) + .build() + .getService(); + } + private boolean isMultiplexedSessionsEnabled() { if (spanner.getOptions() == null || spanner.getOptions().getSessionPoolOptions() == null) { return false; From 31fb81aaf3b333598a3dcd7ed1dddebceb63721c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Knut=20Olav=20L=C3=B8ite?= Date: Mon, 30 Nov 2026 10:22:09 +0100 Subject: [PATCH 2/2] chore: address review comment + add tests --- .../cloud/spanner/AsyncResultSetImpl.java | 6 +- ...ultSetImplLifecycleAndConcurrencyTest.java | 53 ++++++++++++ .../google/cloud/spanner/ReadAsyncTest.java | 82 +++++++++++++++++++ 3 files changed, 137 insertions(+), 4 deletions(-) diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java index f10b2b0d3695..108414fe7233 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java @@ -973,7 +973,7 @@ public void cancel() { Preconditions.checkState( state != State.INITIALIZED && state != State.SYNC, "cannot cancel a result set without a callback"); - if (completed) { + if (completed || state == State.DONE || cursorReturnedDoneOrException) { return; } if (cancelledException == null) { @@ -981,9 +981,7 @@ public void cancel() { SpannerExceptionFactory.newSpannerException( ErrorCode.CANCELLED, "This AsyncResultSet has been cancelled"); } - if (!cursorReturnedDoneOrException) { - executionException = null; - } + executionException = null; state = State.CANCELLED; } closeDelegateResultSet(); diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java index 001d38e33a7e..1139795d66fc 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java @@ -1266,4 +1266,57 @@ public void testInitializedDelegateCachedOnlyAfterStartOrCloseCompletes() { assertEquals(1, failingStartCalls.get()); } } + + @Test(timeout = 60_000) + public void testCancelAfterCallbackDoneWhileProducerStillRunningPreservesDoneState() + throws Exception { + CountDownLatch producerInRow2Latch = new CountDownLatch(1); + CountDownLatch releaseProducerLatch = new CountDownLatch(1); + CountDownLatch callbackInvokedLatch = new CountDownLatch(1); + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + ResultSet slowRow2Delegate = mock(ResultSet.class); + AtomicInteger nextCalls = new AtomicInteger(); + when(slowRow2Delegate.next()) + .thenAnswer( + invocation -> { + if (nextCalls.incrementAndGet() == 1) { + return true; + } + producerInRow2Latch.countDown(); + assertTrue(releaseProducerLatch.await(30, TimeUnit.SECONDS)); + return false; + }); + when(slowRow2Delegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(1L).build()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, slowRow2Delegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + callbackInvokedLatch.countDown(); + return CallbackResponse.DONE; + }); + + assertTrue(producerInRow2Latch.await(30, TimeUnit.SECONDS)); + assertTrue(callbackInvokedLatch.await(30, TimeUnit.SECONDS)); + callbackExecutor.submit(() -> null).get(30, TimeUnit.SECONDS); + + assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState()); + assertFalse(future.isDone()); + + resultSet.cancel(); + assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState()); + + releaseProducerLatch.countDown(); + assertNull(future.get(30, TimeUnit.SECONDS)); + assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState()); + } finally { + releaseProducerLatch.countDown(); + callbackExecutor.shutdownNow(); + } + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java index 10d0f07eab22..6721ad6e9047 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java @@ -52,6 +52,7 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; @@ -624,6 +625,87 @@ private void assertSchemaGettersWorkOnDone(Statement statement, List exp assertEquals(expectedValues, actualValues); } + @Test(timeout = 60_000) + public void cancelAfterCursorStateDonePreservesSuccess() throws Exception { + List actualValues = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch doneObservedLatch = new CountDownLatch(1); + CountDownLatch cancelCalledLatch = new CountDownLatch(1); + try (AsyncResultSet resultSet = + client.singleUse().executeQueryAsync(READ_MULTIPLE_KEY_VALUE_STATEMENT)) { + ApiFuture finished = + resultSet.setCallback( + executor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + actualValues.add(cursor.getString("Value")); + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + doneObservedLatch.countDown(); + try { + assertTrue(cancelCalledLatch.await(30, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + throw new RuntimeException(interruptedException); + } + assertEquals(READ_TABLE_TYPE, cursor.getType()); + return CallbackResponse.DONE; + } + } + }); + + assertTrue(doneObservedLatch.await(30, TimeUnit.SECONDS)); + resultSet.cancel(); + cancelCalledLatch.countDown(); + assertNull(finished.get(30, TimeUnit.SECONDS)); + } finally { + cancelCalledLatch.countDown(); + } + assertEquals(Arrays.asList("v1", "v2", "v3"), actualValues); + } + + @Test(timeout = 60_000) + public void cancelAfterCursorExceptionPreservesOriginalError() throws Exception { + Statement failingStatement = Statement.of("SELECT * FROM MissingTable"); + mockSpanner.putStatementResult( + StatementResult.exception( + failingStatement, + Status.INVALID_ARGUMENT.withDescription("missing table").asRuntimeException())); + CountDownLatch exceptionObservedLatch = new CountDownLatch(1); + CountDownLatch cancelCalledLatch = new CountDownLatch(1); + try (AsyncResultSet resultSet = client.singleUse().executeQueryAsync(failingStatement)) { + ApiFuture finished = + resultSet.setCallback( + executor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.INVALID_ARGUMENT, thrown.getErrorCode()); + exceptionObservedLatch.countDown(); + try { + assertTrue(cancelCalledLatch.await(30, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + throw new RuntimeException(interruptedException); + } + return CallbackResponse.DONE; + }); + + assertTrue(exceptionObservedLatch.await(30, TimeUnit.SECONDS)); + resultSet.cancel(); + cancelCalledLatch.countDown(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> finished.get(30, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.INVALID_ARGUMENT, + ((SpannerException) executionException.getCause()).getErrorCode()); + } finally { + cancelCalledLatch.countDown(); + } + } + private Spanner createSingleThreadSpanner( SpannerOptions.CloseableExecutorProvider asyncExecutorProvider) { return SpannerOptions.newBuilder()