Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
import com.google.api.gax.tracing.ApiTracer;
import com.google.api.gax.tracing.MethodName;
import com.google.api.gax.tracing.MetricsTracer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;

/**
Expand All @@ -36,13 +36,13 @@ class BuiltInMetricsTracer extends MetricsTracer implements ApiTracer {

private final BuiltInMetricsRecorder builtInOpenTelemetryMetricsRecorder;
// These are RPC specific attributes and pertain to a specific API Trace
private final Map<String, String> attributes = new HashMap<>();
private Float gfeLatency = null;
private Float afeLatency = null;
private final Map<String, String> attributes = new ConcurrentHashMap<>();
private volatile Float gfeLatency = null;
private volatile Float afeLatency = null;
private final TraceWrapper traceWrapper;
private final ISpan currentSpan;
private boolean isDirectPathUsed;
private boolean isAfeEnabled;
private volatile boolean isDirectPathUsed;
private volatile boolean isAfeEnabled;

BuiltInMetricsTracer(
MethodName methodName,
Expand All @@ -56,6 +56,25 @@ class BuiltInMetricsTracer extends MetricsTracer implements ApiTracer {
this.currentSpan = currentSpan;
}

@Override
public void attemptStarted(Object request, int attemptNumber) {
this.gfeLatency = null;
this.afeLatency = null;
this.isDirectPathUsed = false;
this.isAfeEnabled = false;
super.attemptStarted(request, attemptNumber);
}

@Override
@SuppressWarnings("deprecation")
public void attemptStarted(int attemptNumber) {
this.gfeLatency = null;
this.afeLatency = null;
this.isDirectPathUsed = false;
this.isAfeEnabled = false;
super.attemptStarted(attemptNumber);
}

/**
* Adds an annotation that the attempt succeeded. Successful attempt add "OK" value to the status
* attribute key.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,11 @@ CommitResponse writeAtLeastOnceWithOptions(
* <li>{@link Options#priority(com.google.cloud.spanner.Options.RpcPriority)}: The {@link
* RpcPriority} to use for the batch write request.
* <li>{@link Options#tag(String)}: The transaction tag to use for the batch write request.
* <li>{@link Options#excludeTxnFromChangeStreams()}: Excludes the transaction from change
* streams with the DDL option {@code allow_txn_exclusion=true}.
* <li>{@link Options#clientContext(com.google.spanner.v1.RequestOptions.ClientContext)}: The
* {@link com.google.spanner.v1.RequestOptions.ClientContext} to attach to the batch write
* request.
* </ul>
*/
ServerStream<BatchWriteResponse> batchWriteAtLeastOnce(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.google.spanner.v1.TransactionOptions.IsolationLevel;
import io.opentelemetry.api.common.Attributes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
Expand Down Expand Up @@ -169,7 +170,9 @@ public ServerStream<BatchWriteResponse> batchWriteAtLeastOnce(
throws SpannerException {
ISpan span = tracer.spanBuilder(READ_WRITE_TRANSACTION, databaseAttributes, options);
try (IScope s = tracer.withSpan(span)) {
return multiplexedSessionDatabaseClient.batchWriteAtLeastOnce(mutationGroups, options);
List<MutationGroup> materializedGroups =
SessionImpl.materializeMutationGroups(mutationGroups);
return multiplexedSessionDatabaseClient.batchWriteAtLeastOnce(materializedGroups, options);
} catch (RuntimeException e) {
span.setStatus(e);
throw e;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import com.google.cloud.spanner.Options.UpdateOption;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.spanner.v1.BatchWriteResponse;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
Expand Down Expand Up @@ -185,11 +186,12 @@ public CommitResponse writeWithOptions(Iterable<Mutation> mutations, Transaction
public ServerStream<BatchWriteResponse> batchWriteAtLeastOnce(
Iterable<MutationGroup> mutationGroups, TransactionOption... options)
throws SpannerException {
List<MutationGroup> materializedGroups = SessionImpl.materializeMutationGroups(mutationGroups);
SessionReference sessionReference = getSessionReference();
try (MultiplexedSessionTransaction transaction =
new MultiplexedSessionTransaction(
client, span, sessionReference, NO_CHANNEL_HINT, /* singleUse= */ true)) {
return transaction.batchWriteAtLeastOnce(mutationGroups, options);
client, span, sessionReference, NO_CHANNEL_HINT, /* singleUse= */ false)) {
return transaction.batchWriteAtLeastOnce(materializedGroups, options);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import java.util.BitSet;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
Expand Down Expand Up @@ -650,8 +651,9 @@ public CommitResponse writeAtLeastOnceWithOptions(
public ServerStream<BatchWriteResponse> batchWriteAtLeastOnce(
Iterable<MutationGroup> mutationGroups, TransactionOption... options)
throws SpannerException {
return createMultiplexedSessionTransaction(/* singleUse= */ true)
.batchWriteAtLeastOnce(mutationGroups, options);
List<MutationGroup> materializedGroups = SessionImpl.materializeMutationGroups(mutationGroups);
return createMultiplexedSessionTransaction(/* singleUse= */ false)
.batchWriteAtLeastOnce(materializedGroups, options);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
import com.google.cloud.spanner.SessionClient.SessionOption;
import com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl;
import com.google.cloud.spanner.spi.v1.SpannerRpc;
import com.google.common.base.Preconditions;
import com.google.common.base.Ticker;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.ByteString;
Expand Down Expand Up @@ -311,19 +313,25 @@ public CommitResponse writeAtLeastOnceWithOptions(
}
}

static ImmutableList<MutationGroup> materializeMutationGroups(
Iterable<MutationGroup> mutationGroups) {
return ImmutableList.copyOf(Preconditions.checkNotNull(mutationGroups));
}

private RequestOptions getRequestOptions(TransactionOption... transactionOptions) {
Options requestOptions = Options.fromTransactionOptions(transactionOptions);
if (requestOptions.hasPriority() || requestOptions.hasTag()) {
RequestOptions.Builder requestOptionsBuilder = RequestOptions.newBuilder();
if (requestOptions.hasPriority()) {
requestOptionsBuilder.setPriority(requestOptions.priority());
}
if (requestOptions.hasTag()) {
requestOptionsBuilder.setTransactionTag(requestOptions.tag());
RequestOptions.Builder requestOptionsBuilder =
requestOptions.toRequestOptionsProto(/* isTransactionOption= */ true).toBuilder();
RequestOptions.ClientContext defaultClientContext = spanner.getOptions().getClientContext();
if (defaultClientContext != null) {
RequestOptions.ClientContext.Builder clientContextBuilder = defaultClientContext.toBuilder();
if (requestOptionsBuilder.hasClientContext()) {
clientContextBuilder.mergeFrom(requestOptionsBuilder.getClientContext());
}
return requestOptionsBuilder.build();
requestOptionsBuilder.setClientContext(clientContextBuilder.build());
}
return null;
RequestOptions built = requestOptionsBuilder.build();
return built.equals(RequestOptions.getDefaultInstance()) ? null : built;
}

private Map<SpannerRpc.Option, ?> getSingleUseWriteChannelHintOptions() {
Expand All @@ -339,7 +347,7 @@ public ServerStream<BatchWriteResponse> batchWriteAtLeastOnce(
throws SpannerException {
setActive(null);
List<BatchWriteRequest.MutationGroup> mutationGroupsProto =
MutationGroup.toListProto(mutationGroups);
MutationGroup.toListProto(materializeMutationGroups(mutationGroups));
final BatchWriteRequest.Builder requestBuilder =
BatchWriteRequest.newBuilder()
.setSession(getName())
Expand All @@ -349,7 +357,9 @@ public ServerStream<BatchWriteResponse> batchWriteAtLeastOnce(
if (batchWriteRequestOptions != null) {
requestBuilder.setRequestOptions(batchWriteRequestOptions);
}
if (allOptions.withExcludeTxnFromChangeStreams() == Boolean.TRUE) {
if (allOptions.withExcludeTxnFromChangeStreams() == Boolean.TRUE
|| (allOptions.withExcludeTxnFromChangeStreams() == null
&& defaultTransactionOptions().getExcludeTxnFromChangeStreams())) {
requestBuilder.setExcludeTxnFromChangeStreams(true);
}
ISpan span = tracer.spanBuilder(SpannerImpl.BATCH_WRITE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,12 @@ <ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> metho
return method == SpannerGrpc.getExecuteBatchDmlMethod();
}
},
BATCH_WRITE {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
return method == SpannerGrpc.getBatchWriteMethod();
}
},

PARTITION_QUERY {
@Override
Expand Down Expand Up @@ -578,6 +584,7 @@ public static class SpannerCallContextTimeoutConfigurator implements CallContext
private Duration executeQueryTimeout;
private Duration executeUpdateTimeout;
private Duration batchUpdateTimeout;
private Duration batchWriteTimeout;
private Duration readTimeout;

private Duration partitionQueryTimeout;
Expand All @@ -602,6 +609,12 @@ public <ReqT, RespT> ApiCallContext configure(
return batchUpdateTimeout == null
? null
: callContext.withTimeoutDuration(batchUpdateTimeout);
case BATCH_WRITE:
return batchWriteTimeout == null
? null
: callContext
.withTimeoutDuration(batchWriteTimeout)
.withStreamWaitTimeoutDuration(batchWriteTimeout);
case COMMIT:
return commitTimeout == null ? null : callContext.withTimeoutDuration(commitTimeout);
case EXECUTE_QUERY:
Expand Down Expand Up @@ -818,6 +831,16 @@ public SpannerCallContextTimeoutConfigurator withPartitionReadTimeoutDuration(
this.partitionReadTimeout = partitionReadTimeout;
return this;
}

public Duration getBatchWriteTimeoutDuration() {
return batchWriteTimeout;
}

public SpannerCallContextTimeoutConfigurator withBatchWriteTimeoutDuration(
Duration batchWriteTimeout) {
this.batchWriteTimeout = batchWriteTimeout;
return this;
}
}

/** Default implementation of {@code SpannerFactory}. */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* 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.spi.v1;

import com.google.api.gax.grpc.GrpcStatusCode;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.spanner.v1.BatchWriteRequest;
import com.google.spanner.v1.BatchWriteResponse;
import io.grpc.Status;
import java.util.List;

/**
* Pure state tracker for {@code BatchWrite} mutation groups across stream resumption attempts.
*
* <p>Tracks which mutation groups remain unacknowledged, builds compacted retry requests containing
* only remaining groups, and translates attempt-local response indices back to the caller's
* original index space while releasing acknowledged payloads for immediate garbage collection.
*
* <p>Not thread-safe; callers must synchronize access externally.
*/
final class BatchWriteResumptionState {

// Metadata-only template (session, request_options, exclude_txn_from_change_streams) with
// mutation_groups cleared so acknowledged payloads can be garbage-collected mid-stream.
private final BatchWriteRequest requestTemplate;
// Entries are nulled once acknowledged so large mutation payloads can be GC'd immediately.
private final BatchWriteRequest.MutationGroup[] pending;
private int remaining;
private int[] streamIndexes = new int[0];

BatchWriteResumptionState(BatchWriteRequest initialRequest) {
this.requestTemplate = initialRequest.toBuilder().clearMutationGroups().build();
int count = initialRequest.getMutationGroupsCount();
this.pending = new BatchWriteRequest.MutationGroup[count];
for (int i = 0; i < count; i++) {
this.pending[i] = initialRequest.getMutationGroups(i);
}
this.remaining = count;
}
Comment thread
alkatrivedi marked this conversation as resolved.
Resolved

boolean isAllAcknowledged() {
return remaining == 0;
}

int getRemainingCount() {
return remaining;
}

int getTotalCount() {
return pending.length;
}

BatchWriteRequest getRequestTemplate() {
return requestTemplate;
}

/**
* Builds the request for the next stream attempt containing only unacknowledged mutation groups
* and updates the relative-to-original index mapping for that attempt.
*/
BatchWriteRequest buildNextAttemptRequest() {
BatchWriteRequest.Builder builder = requestTemplate.toBuilder();
int[] nextIndexes = new int[remaining];
int pos = 0;
for (int i = 0; i < pending.length; i++) {
BatchWriteRequest.MutationGroup group = pending[i];
if (group != null) {
builder.addMutationGroups(group);
nextIndexes[pos++] = i;
}
}
this.streamIndexes = nextIndexes;
return builder.build();
}

/**
* Validates all indices in {@code response}, translates them back to the caller's original index
* space, and marks those mutation groups as acknowledged.
*
* @throws ApiException with {@link Status.Code#INTERNAL} (non-retryable) if any index is out of
* bounds; tracking state is left unmodified when this exception is thrown.
*/
BatchWriteResponse translateAndAcknowledge(BatchWriteResponse response) {
List<Integer> relIndexes = response.getIndexesList();
// Validate all indices before mutating tracking state.
for (int i = 0; i < relIndexes.size(); i++) {
int relIdx = relIndexes.get(i);
if (relIdx < 0 || relIdx >= streamIndexes.length) {
throw ApiExceptionFactory.createException(
String.format(
"Spanner returned mutation group index %d out of bounds for BatchWrite"
+ " stream with %d mutation groups",
relIdx, streamIndexes.length),
null,
GrpcStatusCode.of(Status.Code.INTERNAL),
/* retryable= */ false);
}
}

BatchWriteResponse.Builder translated = response.toBuilder().clearIndexes();
for (int i = 0; i < relIndexes.size(); i++) {
int origIdx = streamIndexes[relIndexes.get(i)];
translated.addIndexes(origIdx);
if (pending[origIdx] != null) {
pending[origIdx] = null;
remaining--;
}
}
return translated.build();
}
}
Loading
Loading