Skip to content

Commit 1d01c6c

Browse files
chore(spanner): bound streaming server retry delays and fall back on non-positive values (#15074)
Sanitize server-supplied `RetryInfo` delays when resuming interrupted Cloud Spanner streaming reads and queries so zero, negative, or oversized retry trailers cannot trigger zero-delay retry spin loops or stall consumer threads for hours. - Fall back to exponential backoff (`>= 1 ms`) when a server retry delay is zero, sub-millisecond, or negative instead of retrying immediately without sleeping. - Cap positive server retry delays at the configured maximum retry delay on streaming retry settings (defaulting to `32s` when unset or non-positive) before evaluating the remaining total timeout budget. - Use the same `32s` ceiling for client-side exponential backoff when maximum retry delay is unset on streaming retry settings.
1 parent cff532d commit 1d01c6c

4 files changed

Lines changed: 447 additions & 51 deletions

File tree

‎java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java‎

Lines changed: 56 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import io.grpc.Context;
3838
import io.opentelemetry.api.common.Attributes;
3939
import java.io.IOException;
40+
import java.time.Duration;
4041
import java.util.ArrayDeque;
4142
import java.util.Set;
4243
import java.util.concurrent.CountDownLatch;
@@ -62,7 +63,9 @@
6263
* token that differs from the last seen resume token) resets both, so a long-running stream that
6364
* regularly makes progress is not terminated by an occasional transient error. The default settings
6465
* have no maximum number of attempts or total timeout. Setting maxAttempts to 1 disables streaming
65-
* retries.
66+
* retries. Positive server-supplied retry delays are capped at {@link
67+
* RetrySettings#getMaxRetryDelayDuration()} (defaulting to 32s when unset or non-positive), and
68+
* missing or non-positive server retry delays fall back to exponential backoff.
6669
*
6770
* <p>These limits bound the number of streams that this iterator starts. Each (re)started stream is
6871
* a call through the underlying GAX callable, and GAX applies the same {@link RetrySettings} to
@@ -89,6 +92,7 @@ abstract class ResumableStreamIterator extends AbstractIterator<PartialResultSet
8992
@Nullable private volatile StreamMessageListener streamMessageListener;
9093
private final RetrySettings streamingRetrySettings;
9194
private final Set<Code> retryableCodes;
95+
private static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 32_000L;
9296
private static final Logger logger = Logger.getLogger(ResumableStreamIterator.class.getName());
9397
@Nullable private BackOff backOff;
9498
private final ArrayDeque<PartialResultSet> buffer = new ArrayDeque<>();
@@ -200,8 +204,9 @@ private boolean maxAttemptsExhausted() {
200204
* zero means that no total timeout has been set, and that only maxAttempts (if set) limits the
201205
* retries. This mirrors the interpretation of these values in GAX.
202206
*/
203-
private boolean totalTimeoutExceeded(long proposedDelayMillis) {
204-
long totalTimeoutMillis = streamingRetrySettings.getTotalTimeout().toMillis();
207+
@VisibleForTesting
208+
boolean totalTimeoutExceeded(long proposedDelayMillis) {
209+
long totalTimeoutMillis = streamingRetrySettings.getTotalTimeoutDuration().toMillis();
205210
if (totalTimeoutMillis <= 0L) {
206211
return false;
207212
}
@@ -215,23 +220,45 @@ private boolean totalTimeoutExceeded(long proposedDelayMillis) {
215220
return Math.max(proposedDelayMillis, 0L) >= totalTimeoutMillis - elapsedMillis;
216221
}
217222

218-
private ExponentialBackOff newBackOff() {
223+
/**
224+
* Converts {@code duration} to positive milliseconds (floored at 1ms for positive sub-millisecond
225+
* durations and saturated at {@code maxMillis} on overflow), or returns {@code
226+
* nonPositiveDefaultMillis} when {@code duration} is zero or negative.
227+
*/
228+
private static long saturatedDurationMillis(
229+
Duration duration, long nonPositiveDefaultMillis, long maxMillis) {
230+
if (duration.isZero() || duration.isNegative()) {
231+
return nonPositiveDefaultMillis;
232+
}
233+
try {
234+
return Math.max(1L, Math.min(duration.toMillis(), maxMillis));
235+
} catch (ArithmeticException overflow) {
236+
return maxMillis;
237+
}
238+
}
239+
240+
private long effectiveMaxRetryDelayMillis() {
241+
return saturatedDurationMillis(
242+
streamingRetrySettings.getMaxRetryDelayDuration(),
243+
DEFAULT_MAX_RETRY_DELAY_MILLIS,
244+
Long.MAX_VALUE);
245+
}
246+
247+
@VisibleForTesting
248+
BackOff newBackOff() {
249+
int initialIntervalMillis =
250+
(int)
251+
saturatedDurationMillis(
252+
streamingRetrySettings.getInitialRetryDelayDuration(), 1L, Integer.MAX_VALUE);
253+
int maxIntervalMillis =
254+
Math.max(
255+
initialIntervalMillis,
256+
(int) Math.min(effectiveMaxRetryDelayMillis(), Integer.MAX_VALUE));
219257
return new ExponentialBackOff.Builder()
220258
.setMultiplier(streamingRetrySettings.getRetryDelayMultiplier())
221259
// All of these values must be > 0.
222-
.setInitialIntervalMillis(
223-
Math.max(
224-
1,
225-
(int)
226-
Math.min(
227-
streamingRetrySettings.getInitialRetryDelay().toMillis(),
228-
Integer.MAX_VALUE)))
229-
.setMaxIntervalMillis(
230-
Math.max(
231-
1,
232-
(int)
233-
Math.min(
234-
streamingRetrySettings.getMaxRetryDelay().toMillis(), Integer.MAX_VALUE)))
260+
.setInitialIntervalMillis(initialIntervalMillis)
261+
.setMaxIntervalMillis(maxIntervalMillis)
235262
// The total timeout is enforced explicitly in computeNext(), based on the elapsed time
236263
// since the first failure of the current retry sequence. Prevent the backoff from
237264
// returning BackOff.STOP, as that would misinterpret a total timeout of zero (that is, no
@@ -248,7 +275,8 @@ private static long nextBackOffMillis(BackOff backoff) throws SpannerException {
248275
}
249276
}
250277

251-
private void backoffSleep(Context context, long backoffMillis) throws SpannerException {
278+
@VisibleForTesting
279+
void backoffSleep(Context context, long backoffMillis) throws SpannerException {
252280
tracer.getCurrentSpan().addAnnotation("Backing off", "Delay", backoffMillis);
253281
final CountDownLatch latch = new CountDownLatch(1);
254282
final Context.CancellationListener listener =
@@ -261,7 +289,7 @@ private void backoffSleep(Context context, long backoffMillis) throws SpannerExc
261289
try {
262290
if (backoffMillis == BackOff.STOP) {
263291
// Highly unlikely but we handle it just in case.
264-
backoffMillis = streamingRetrySettings.getMaxRetryDelay().toMillis();
292+
backoffMillis = effectiveMaxRetryDelayMillis();
265293
}
266294
if (latch.await(backoffMillis, TimeUnit.MILLISECONDS)) {
267295
// Woken by context cancellation.
@@ -478,14 +506,19 @@ long checkRetryBudgetAndGetDelay(SpannerException spannerException) {
478506
spannerException);
479507
throw spannerException;
480508
}
481-
// Determine the retry delay: either the delay that the server included in the error, or
482-
// otherwise a delay determined by the exponential backoff.
509+
// Determine the retry delay: use a positive server-supplied retry delay (clamped to the
510+
// effective max retry delay), or fall back to exponential backoff when absent or non-positive.
483511
long delayMillis = spannerException.getRetryDelayInMillis();
484-
if (delayMillis == -1L) {
512+
long maxRetryDelayMillis = effectiveMaxRetryDelayMillis();
513+
if (delayMillis <= 0L) {
485514
if (this.backOff == null) {
486515
this.backOff = newBackOff();
487516
}
488-
delayMillis = nextBackOffMillis(this.backOff);
517+
long backOffMillis = nextBackOffMillis(this.backOff);
518+
delayMillis =
519+
backOffMillis == BackOff.STOP ? maxRetryDelayMillis : Math.max(1L, backOffMillis);
520+
} else {
521+
delayMillis = Math.min(delayMillis, maxRetryDelayMillis);
489522
}
490523
// The total timeout budget applies regardless of whether the delay came from the server
491524
// or from the backoff.

‎java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpc.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,13 +276,14 @@ public class GapicSpannerRpc implements SpannerRpc {
276276
private static final CallOptions.Key<Boolean> BASE_CONTEXT_MARKER_KEY =
277277
CallOptions.Key.create("BASE_CONTEXT_MARKER_KEY");
278278

279-
// Normalize the generated placeholder to the historical streaming resume policy.
279+
// Normalize the generated placeholder to the historical streaming resume policy, while allowing
280+
// server-supplied retry delays up to the standard 32s unary max retry delay.
280281
static final RetrySettings DEFAULT_STREAMING_RETRY_SETTINGS =
281282
RetrySettings.newBuilder()
282283
.setTotalTimeoutDuration(Duration.ZERO)
283284
.setMaxAttempts(0)
284285
.setInitialRetryDelayDuration(Duration.ofMillis(10))
285-
.setMaxRetryDelayDuration(Duration.ofMillis(1000))
286+
.setMaxRetryDelayDuration(Duration.ofSeconds(32))
286287
.build();
287288

288289
/** Fallback states owned by this rpc, one per grpc-gcp pool. */

0 commit comments

Comments
 (0)