diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java index e13245b1ef1d..507d1d59ba41 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java @@ -481,11 +481,18 @@ long checkRetryBudgetAndGetDelay(SpannerException spannerException) { // Determine the retry delay: either the delay that the server included in the error, or // otherwise a delay determined by the exponential backoff. long delayMillis = spannerException.getRetryDelayInMillis(); - if (delayMillis == -1L) { + if (delayMillis <= 0L) { if (this.backOff == null) { this.backOff = newBackOff(); } delayMillis = nextBackOffMillis(this.backOff); + } else { + long configuredMaxDelayMillis = + streamingRetrySettings != null && streamingRetrySettings.getMaxRetryDelay() != null + ? streamingRetrySettings.getMaxRetryDelay().toMillis() + : 0L; + long maxDelayMillis = configuredMaxDelayMillis > 0L ? configuredMaxDelayMillis : 32_000L; + delayMillis = Math.min(delayMillis, maxDelayMillis); } // The total timeout budget applies regardless of whether the delay came from the server // or from the backoff. diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Statement.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Statement.java index 40a57bd76ced..579908c9aa68 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Statement.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Statement.java @@ -359,10 +359,18 @@ public Statement of(String sql) { * @see DatabaseClient#getStatementFactory */ public Statement withUnnamedParameters(String sql, Object... values) { - Map parameters = getUnnamedParametersMap(values); + Preconditions.checkNotNull(values); AbstractStatementParser statementParser = AbstractStatementParser.getInstance(this.dialect); ParametersInfo parametersInfo = statementParser.convertPositionalParametersToNamedParameters('?', sql); + if (parametersInfo.numberOfParameters != values.length) { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.INVALID_ARGUMENT, + String.format( + "The number of parameter values (%d) does not match the number of positional parameters (%d) in the SQL statement.", + values.length, parametersInfo.numberOfParameters)); + } + Map parameters = getUnnamedParametersMap(values); return new Statement(parametersInfo.sqlWithNamedParameters, parameters, null); } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/AbstractMultiUseTransaction.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/AbstractMultiUseTransaction.java index ca78c3e5aeaf..7c6f8de99066 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/AbstractMultiUseTransaction.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/AbstractMultiUseTransaction.java @@ -174,6 +174,10 @@ ImmutableList getSavepoints() { return ImmutableList.copyOf(savepoints); } + void clearSavepoints() { + savepoints.clear(); + } + @Override public void savepoint(@Nonnull String name, @Nonnull Dialect dialect) { if (dialect != Dialect.POSTGRESQL) { diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionImpl.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionImpl.java index cadd63757398..3f177a678a93 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionImpl.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionImpl.java @@ -1422,6 +1422,15 @@ public T runTransaction(TransactionCallable callable) { } void resetForRetry(UnitOfWork retryUnitOfWork) { + this.connectionState.rollback(); + if (isBatchActive()) { + abortBatch(); + } + transactionBeginMarked = true; + if (isAutocommit()) { + inTransaction = true; + } + setConnectionPropertyValue(RETRY_ABORTS_INTERNALLY, false, true); retryUnitOfWork.resetForRetry(); this.currentUnitOfWork = retryUnitOfWork; } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ReadWriteTransaction.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ReadWriteTransaction.java index 246c203c8674..5cc3f78999b4 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ReadWriteTransaction.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ReadWriteTransaction.java @@ -1380,7 +1380,20 @@ private ApiFuture rollbackAsync(CallType callType, boolean updateStatusAnd @Override public void resetForRetry() { - txContextFuture = ApiFutures.immediateFuture(txManager.resetForRetry()); + this.state = UnitOfWorkState.STARTED; + this.abortedException = null; + this.rolledBackToSavepointException = null; + this.timedOutOrCancelled = false; + this.commitResponseFuture = null; + this.mutations.clear(); + this.statements.clear(); + this.autoSavepoint = null; + clearSavepoints(); + if (txManager != null) { + txContextFuture = ApiFutures.immediateFuture(txManager.resetForRetry()); + } else { + txContextFuture = null; + } } @Override diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/TransactionRunnerImpl.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/TransactionRunnerImpl.java index 504b084dba32..ab709947f8a6 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/TransactionRunnerImpl.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/TransactionRunnerImpl.java @@ -23,6 +23,8 @@ import com.google.cloud.spanner.connection.Connection.TransactionCallable; import com.google.cloud.spanner.connection.ConnectionImpl.Caller; import com.google.cloud.spanner.connection.UnitOfWork.CallType; +import com.google.cloud.spanner.connection.UnitOfWork.UnitOfWorkState; +import java.util.concurrent.ThreadLocalRandom; class TransactionRunnerImpl { private final ConnectionImpl connection; @@ -43,20 +45,34 @@ T run(TransactionCallable callable) { return result; } catch (AbortedException abortedException) { try { - //noinspection BusyWait - Thread.sleep(abortedException.getRetryDelayInMillis()); + long retryDelayMillis = abortedException.getRetryDelayInMillis(); + if (retryDelayMillis > 0L) { + //noinspection BusyWait + Thread.sleep(retryDelayMillis); + } else if (abortedException.isEmulatorOnlySupportsOneTransactionException()) { + //noinspection BusyWait + Thread.sleep(ThreadLocalRandom.current().nextInt(1, 5)); + } connection.resetForRetry(transaction); } catch (InterruptedException interruptedException) { - connection.rollbackAsync(CallType.SYNC, Caller.TRANSACTION_RUNNER); + rollbackIfActive(transaction); throw SpannerExceptionFactory.propagateInterrupt(interruptedException); } catch (Throwable t) { - connection.rollbackAsync(CallType.SYNC, Caller.TRANSACTION_RUNNER); + rollbackIfActive(transaction); throw t; } } catch (Throwable t) { - connection.rollbackAsync(CallType.SYNC, Caller.TRANSACTION_RUNNER); + rollbackIfActive(transaction); throw t; } } } + + private void rollbackIfActive(UnitOfWork transaction) { + if (connection.isInTransaction() + && (transaction.getState() == UnitOfWorkState.STARTED + || transaction.getState() == UnitOfWorkState.ABORTED)) { + connection.rollbackAsync(CallType.SYNC, Caller.TRANSACTION_RUNNER); + } + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java index 12a00a990c05..472fcd47c066 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java @@ -525,17 +525,18 @@ private boolean totalTimeoutExceeded(long timeoutMillis, long elapsedMillis, lon initWithLimitAndRetrySettings( Integer.MAX_VALUE, RetrySettings.newBuilder() + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(Long.MAX_VALUE)) .setTotalTimeoutDuration(java.time.Duration.ofMillis(timeoutMillis)) .build()); SpannerException exception = Mockito.spy(new RetryableException(errorCodeParameter, "failed by test")); - when(exception.getRetryDelayInMillis()).thenReturn(0L); + when(exception.getRetryDelayInMillis()).thenReturn(1L); nanoTime = () -> 0L; - assertEquals(0L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); nanoTime = () -> TimeUnit.MILLISECONDS.toNanos(elapsedMillis); when(exception.getRetryDelayInMillis()).thenReturn(delayMillis); try { - assertEquals(delayMillis, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); + resumableStreamIterator.checkRetryBudgetAndGetDelay(exception); return false; } catch (SpannerException e) { assertThat(e).isSameInstanceAs(exception); @@ -561,6 +562,83 @@ public void retryBudget_usesConfiguredBackoffWithoutRetryInfo() { assertThat(delayMillis).isAtMost(150L); } + @Test + public void retryInfoWithZeroOrNegativeDelay_usesExponentialBackoff() { + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(100)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(100)) + .build()); + Metadata.Key key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + + Metadata zeroTrailers = new Metadata(); + zeroTrailers.put( + key, + RetryInfo.newBuilder() + .setRetryDelay(Duration.newBuilder().setSeconds(0L).setNanos(0)) + .build()); + SpannerException zeroDelayException = + new RetryableException( + errorCodeParameter, + "zero retry delay", + errorCodeParameter.getGrpcStatus().asRuntimeException(zeroTrailers)); + long zeroFallbackDelay = + resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException); + assertThat(zeroFallbackDelay).isAtLeast(50L); + assertThat(zeroFallbackDelay).isAtMost(150L); + + Metadata negativeTrailers = new Metadata(); + negativeTrailers.put( + key, + RetryInfo.newBuilder() + .setRetryDelay(Duration.newBuilder().setSeconds(-1L).setNanos(0)) + .build()); + SpannerException negativeDelayException = + new RetryableException( + errorCodeParameter, + "negative retry delay", + errorCodeParameter.getGrpcStatus().asRuntimeException(negativeTrailers)); + long negativeFallbackDelay = + resumableStreamIterator.checkRetryBudgetAndGetDelay(negativeDelayException); + assertThat(negativeFallbackDelay).isAtLeast(50L); + assertThat(negativeFallbackDelay).isAtMost(150L); + } + + @Test + public void retryInfoWithMultiHourDelay_clampsToMaxRetryDelay() { + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(32)) + .setTotalTimeoutDuration(java.time.Duration.ofHours(24)) + .build()); + Metadata.Key key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + Metadata trailers = new Metadata(); + trailers.put( + key, + RetryInfo.newBuilder() + .setRetryDelay( + Duration.newBuilder().setSeconds(TimeUnit.HOURS.toSeconds(10L)).setNanos(0)) + .build()); + SpannerException multiHourException = + new RetryableException( + errorCodeParameter, + "multi-hour retry delay", + errorCodeParameter.getGrpcStatus().asRuntimeException(trailers)); + long clampedDelay = resumableStreamIterator.checkRetryBudgetAndGetDelay(multiHourException); + assertEquals(TimeUnit.SECONDS.toMillis(32L), clampedDelay); + + // Also verify default 32s cap when maxRetryDelay is not configured (0ms). + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + RetrySettings.newBuilder().setTotalTimeoutDuration(java.time.Duration.ofHours(24)).build()); + long defaultClampedDelay = + resumableStreamIterator.checkRetryBudgetAndGetDelay(multiHourException); + assertEquals(TimeUnit.SECONDS.toMillis(32L), defaultClampedDelay); + } + @Test public void rawGapicSettings_useConfiguredTimeoutWithoutSpecialCase() { RetrySettings settings = @@ -568,8 +646,10 @@ public void rawGapicSettings_useConfiguredTimeoutWithoutSpecialCase() { initWithLimitAndRetrySettings(Integer.MAX_VALUE, settings); SpannerException exception = Mockito.spy(new RetryableException(errorCodeParameter, "failed by test")); - when(exception.getRetryDelayInMillis()) - .thenReturn(settings.getTotalTimeoutDuration().toMillis()); + when(exception.getRetryDelayInMillis()).thenReturn(1L); + nanoTime = () -> 0L; + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); + nanoTime = () -> settings.getTotalTimeoutDuration().toNanos(); assertThat( assertThrows( SpannerException.class, diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StatementTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StatementTest.java index 9381d17ed1ce..a0e9ecc84429 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StatementTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StatementTest.java @@ -200,4 +200,41 @@ public void testGetParameterName() { assertSame(Statement.getParameterName(i), Statement.getParameterName(i)); } } + + @Test + public void testWithUnnamedParametersCountMismatchThrowsInvalidArgument() { + for (Dialect dialect : Dialect.values()) { + Statement.StatementFactory factory = new Statement.StatementFactory(dialect); + + // Matching positional parameter count succeeds, ignoring '?' inside literals and comments. + Statement valid = + factory.withUnnamedParameters( + "SELECT '?' AS q, /* ? */ * FROM Users WHERE Id = ? AND Status = ?", 1234L, "ACTIVE"); + assertEquals(Value.toValue(1234L), valid.getParameters().get("p1")); + assertEquals(Value.toValue("ACTIVE"), valid.getParameters().get("p2")); + + // Too few parameter values throws INVALID_ARGUMENT. + SpannerException tooFew = + assertThrows( + SpannerException.class, + () -> + factory.withUnnamedParameters( + "SELECT * FROM Users WHERE Id = ? AND Status = ?", 1234L)); + assertEquals(ErrorCode.INVALID_ARGUMENT, tooFew.getErrorCode()); + + // Too many parameter values throws INVALID_ARGUMENT. + SpannerException tooMany = + assertThrows( + SpannerException.class, + () -> + factory.withUnnamedParameters( + "SELECT '?' AS q, /* ? */ * FROM Users WHERE Id = ?", 1234L, "EXTRA")); + assertEquals(ErrorCode.INVALID_ARGUMENT, tooMany.getErrorCode()); + + // Null values array throws NullPointerException. + assertThrows( + NullPointerException.class, + () -> factory.withUnnamedParameters("SELECT * FROM Users WHERE Id = ?", (Object[]) null)); + } + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionImplTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionImplTest.java index 97534f7a27e5..b7b886f335af 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionImplTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionImplTest.java @@ -57,6 +57,7 @@ import com.google.cloud.spanner.Dialect; import com.google.cloud.spanner.ErrorCode; import com.google.cloud.spanner.ForwardingResultSet; +import com.google.cloud.spanner.Mutation; import com.google.cloud.spanner.Options; import com.google.cloud.spanner.Options.QueryOption; import com.google.cloud.spanner.ReadContext.QueryAnalyzeMode; @@ -2087,4 +2088,117 @@ UnitOfWork getCurrentUnitOfWorkOrStartNewUnitOfWork( assertNull(connection.getProtoDescriptors()); } } + + @Test + public void testRunTransactionCommitAbortedResetsStateSavepointsAndMutations() { + ConnectionOptions options = + ConnectionOptions.newBuilder() + .setCredentials(NoCredentials.getInstance()) + .setUri(URI) + .build(); + Spanner spanner = mock(Spanner.class); + io.opentelemetry.api.OpenTelemetry openTelemetry = io.opentelemetry.api.OpenTelemetry.noop(); + com.google.cloud.spanner.SpannerOptions spannerOptions = + mock(com.google.cloud.spanner.SpannerOptions.class); + when(spannerOptions.getOpenTelemetry()).thenReturn(openTelemetry); + when(spanner.getOptions()).thenReturn(spannerOptions); + SpannerPool spannerPool = mock(SpannerPool.class); + when(spannerPool.getSpanner(any(ConnectionOptions.class), any(ConnectionImpl.class))) + .thenReturn(spanner); + DdlClient ddlClient = createDefaultMockDdlClient(); + DatabaseClient dbClient = mock(DatabaseClient.class); + when(dbClient.getDialect()).thenReturn(Dialect.GOOGLE_STANDARD_SQL); + + final java.util.List committedMutations = new java.util.ArrayList<>(); + final java.util.concurrent.atomic.AtomicInteger commitCalls = + new java.util.concurrent.atomic.AtomicInteger(); + final java.util.concurrent.atomic.AtomicInteger resetForRetryCalls = + new java.util.concurrent.atomic.AtomicInteger(); + when(dbClient.transactionManager(any())) + .thenAnswer( + invocation -> { + TransactionContext txContext = mock(TransactionContext.class); + when(txContext.executeUpdate(Statement.of(UPDATE))).thenReturn(1L); + Mockito.doAnswer( + bufInvocation -> { + Iterable mutations = bufInvocation.getArgument(0); + for (Mutation m : mutations) { + committedMutations.add(m); + } + return null; + }) + .when(txContext) + .buffer(Mockito.>any()); + return new SimpleTransactionManager(txContext, false) { + @Override + public void commit() { + int call = commitCalls.incrementAndGet(); + if (call == 1 || call == 3) { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.ABORTED, "commit aborted without retry info"); + } + super.commit(); + } + + @Override + public TransactionContext resetForRetry() { + resetForRetryCalls.incrementAndGet(); + committedMutations.clear(); + return super.resetForRetry(); + } + }; + }); + + try (ConnectionImpl connection = + new ConnectionImpl(options, spannerPool, ddlClient, dbClient, mock(BatchClient.class))) { + // 1. Verify autocommit=true restores inTransaction, RETRY_ABORTS_INTERNALLY=false, and clears + // savepoints. + connection.setAutocommit(true); + connection.setSavepointSupport(SavepointSupport.ENABLED); + final java.util.concurrent.atomic.AtomicInteger autocommitAttempts = + new java.util.concurrent.atomic.AtomicInteger(); + + connection.runTransaction( + transaction -> { + autocommitAttempts.incrementAndGet(); + assertTrue(transaction.isInTransaction()); + assertFalse(transaction.isRetryAbortsInternally()); + transaction.savepoint("s1"); + assertEquals(1L, transaction.executeUpdate(Statement.of(UPDATE))); + return null; + }); + + assertEquals(2, autocommitAttempts.get()); + assertEquals(2, commitCalls.get()); + assertEquals(1, resetForRetryCalls.get()); + assertFalse(connection.isInTransaction()); + assertTrue(connection.isRetryAbortsInternally()); + + // 2. Verify autocommit=false clears buffered mutations and savepoints across commit abort + // retry. + connection.setAutocommit(false); + committedMutations.clear(); + final java.util.concurrent.atomic.AtomicInteger transactionalAttempts = + new java.util.concurrent.atomic.AtomicInteger(); + + connection.runTransaction( + transaction -> { + int attempt = transactionalAttempts.incrementAndGet(); + assertTrue(transaction.isInTransaction()); + assertFalse(transaction.isRetryAbortsInternally()); + transaction.savepoint("s1"); + transaction.bufferedWrite( + Mutation.newInsertBuilder("FOO").set("ID").to((long) attempt).build()); + assertEquals(1L, transaction.executeUpdate(Statement.of(UPDATE))); + return null; + }); + + assertEquals(2, transactionalAttempts.get()); + assertEquals(4, commitCalls.get()); + assertEquals(2, resetForRetryCalls.get()); + assertEquals(1, committedMutations.size()); + assertFalse(connection.isTransactionStarted()); + assertTrue(connection.isRetryAbortsInternally()); + } + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionMockServerTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionMockServerTest.java new file mode 100644 index 000000000000..c1b01e65ffe0 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionMockServerTest.java @@ -0,0 +1,64 @@ +/* + * 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.connection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import com.google.cloud.spanner.AbortedException; +import com.google.cloud.spanner.DatabaseClient; +import com.google.cloud.spanner.DatabaseId; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class ConnectionMockServerTest extends AbstractMockServerTest { + + @Test + public void testCommitAbortedWithRetryAbortsInternallyDisabledReleasesSession() throws Exception { + try (Connection connection = createConnection()) { + connection.setAutocommit(false); + connection.setRetryAbortsInternally(false); + connection.getDialect(); + + DatabaseClient dbClient = + connection.getSpanner().getDatabaseClient(DatabaseId.of("proj", "inst", "db")); + Field muxField = dbClient.getClass().getDeclaredField("multiplexedSessionDatabaseClient"); + muxField.setAccessible(true); + Object muxClient = muxField.get(dbClient); + Method getReleased = muxClient.getClass().getDeclaredMethod("getNumSessionsReleased"); + getReleased.setAccessible(true); + AtomicLong numSessionsReleased = (AtomicLong) getReleased.invoke(muxClient); + long releasedBefore = numSessionsReleased.get(); + + assertEquals(1L, connection.executeUpdate(INSERT_STATEMENT)); + mockSpanner.abortNextStatement(); + assertThrows(AbortedException.class, connection::commit); + + assertEquals(releasedBefore + 1L, numSessionsReleased.get()); + + // Starting and committing a subsequent transaction succeeds cleanly. + assertEquals(1L, connection.executeUpdate(INSERT_STATEMENT)); + connection.commit(); + assertEquals(releasedBefore + 2L, numSessionsReleased.get()); + } + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/RunTransactionMockServerTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/RunTransactionMockServerTest.java index d4af5dd4e7e8..b587723fe3f5 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/RunTransactionMockServerTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/RunTransactionMockServerTest.java @@ -27,6 +27,7 @@ import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime; import com.google.cloud.spanner.ResultSet; import com.google.cloud.spanner.SpannerException; +import com.google.protobuf.ByteString; import com.google.spanner.v1.BeginTransactionRequest; import com.google.spanner.v1.CommitRequest; import com.google.spanner.v1.ExecuteSqlRequest; @@ -279,4 +280,95 @@ public void testRollbackInRunTransaction() { assertEquals(1, mockSpanner.countRequestsOfType(CommitRequest.class)); assertEquals(0, mockSpanner.countRequestsOfType(RollbackRequest.class)); } + + @Test + public void testRunTransactionCommitAbortedWithAutocommitRetriesInTransaction() { + final AtomicInteger attempts = new AtomicInteger(); + try (Connection connection = createConnection()) { + connection.setAutocommit(true); + connection.setSavepointSupport(SavepointSupport.ENABLED); + connection.runTransaction( + transaction -> { + int attempt = attempts.incrementAndGet(); + assertTrue(transaction.isInTransaction()); + assertFalse(transaction.isRetryAbortsInternally()); + transaction.savepoint("s1"); + assertEquals(1L, transaction.executeUpdate(INSERT_STATEMENT)); + assertEquals(1L, transaction.executeUpdate(INSERT_STATEMENT)); + if (attempt == 1) { + mockSpanner.abortNextStatement(); + } + return null; + }); + assertTrue(connection.isAutocommit()); + assertFalse(connection.isInTransaction()); + assertTrue(connection.isRetryAbortsInternally()); + } + assertEquals(2, attempts.get()); + assertEquals(4, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class)); + assertEquals(2, mockSpanner.countRequestsOfType(CommitRequest.class)); + assertEquals(0, mockSpanner.countRequestsOfType(BeginTransactionRequest.class)); + + CommitRequest firstCommit = mockSpanner.getRequestsOfType(CommitRequest.class).get(0); + ExecuteSqlRequest firstRetrySql = mockSpanner.getRequestsOfType(ExecuteSqlRequest.class).get(2); + assertTrue(firstRetrySql.hasTransaction()); + assertTrue(firstRetrySql.getTransaction().hasBegin()); + ByteString prevTxId = + firstRetrySql + .getTransaction() + .getBegin() + .getReadWrite() + .getMultiplexedSessionPreviousTransactionId(); + assertEquals(firstCommit.getTransactionId(), prevTxId); + } + + @Test + public void testRunTransactionCommitNonAbortedErrorPropagatesOriginalException() { + try (Connection connection = createConnection()) { + connection.setAutocommit(true); + SpannerException exception = + assertThrows( + SpannerException.class, + () -> + connection.runTransaction( + transaction -> { + assertEquals(1L, transaction.executeUpdate(INSERT_STATEMENT)); + mockSpanner.setCommitExecutionTime( + SimulatedExecutionTime.ofException( + Status.INVALID_ARGUMENT + .withDescription("commit invalid argument") + .asRuntimeException())); + return null; + })); + assertEquals(ErrorCode.INVALID_ARGUMENT, exception.getErrorCode()); + assertTrue( + exception.getMessage(), exception.getMessage().contains("commit invalid argument")); + } + assertEquals(1, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class)); + assertEquals(1, mockSpanner.countRequestsOfType(CommitRequest.class)); + assertEquals(0, mockSpanner.countRequestsOfType(RollbackRequest.class)); + } + + @Test + public void testRunTransactionCommitAbortedWithoutRetryInfoRetries() { + final AtomicInteger attempts = new AtomicInteger(); + try (Connection connection = createConnection()) { + connection.setAutocommit(true); + connection.runTransaction( + transaction -> { + assertEquals(1L, transaction.executeUpdate(INSERT_STATEMENT)); + if (attempts.incrementAndGet() == 1) { + mockSpanner.setCommitExecutionTime( + SimulatedExecutionTime.ofException( + Status.ABORTED + .withDescription("Transaction was aborted without RetryInfo") + .asRuntimeException())); + } + return null; + }); + } + assertEquals(2, attempts.get()); + assertEquals(2, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class)); + assertEquals(2, mockSpanner.countRequestsOfType(CommitRequest.class)); + } }