Skip to content

Commit ca3d306

Browse files
test: deflake TestRetryBehavior
Eliminate wall-clock timing sensitivity, cold-start jitter, and thread-safety races in TestRetryBehavior: - Read the wire grpc-timeout header (GrpcUtil.TIMEOUT_KEY) instead of Context.current().getDeadline().timeRemaining(MILLISECONDS), removing loopback transit, server executor scheduling lag, and millisecond truncation. - Warm up the single gRPC channel and operation code path with a non-retryable FAILED_PRECONDITION call before starting timed assertions, and replace Mockito.mock(ServerCall.Listener.class) with a lightweight no-op listener. - Allow either ABORTED or DEADLINE_EXCEEDED as the terminal status in testRpcWillRetryOnAbort, since a final retry scheduled near OPERATION_TIMEOUT can legitimately time out on its clamped deadline (or CallOptions deadline) before the server's ABORTED response arrives. - Assert timeout bounds on every recorded attempt (replacing Truth's existential .contains(...) checks) with realistic scheduling/GC tolerances, and restrict the unclamped check in testRpcWillRetryOnAbort to the first 7 attempts where cumulative max backoff (315ms) guarantees no clamping. - Use per-test CopyOnWriteArrayList snapshots and await server termination in teardown to avoid ConcurrentModificationException and call-count races.
1 parent f65aa05 commit ca3d306

1 file changed

Lines changed: 124 additions & 85 deletions

File tree

  • bigtable-hbase-1.x-parent/bigtable-hbase-1.x/src/test/java/com/google/cloud/bigtable/hbase

‎bigtable-hbase-1.x-parent/bigtable-hbase-1.x/src/test/java/com/google/cloud/bigtable/hbase/TestRetryBehavior.java‎

Lines changed: 124 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -16,32 +16,30 @@
1616
package com.google.cloud.bigtable.hbase;
1717

1818
import static com.google.common.truth.Truth.assertThat;
19+
import static com.google.common.truth.Truth.assertWithMessage;
1920

2021
import com.google.bigtable.v2.BigtableGrpc;
2122
import com.google.cloud.bigtable.test.helper.TestServerBuilder;
2223
import com.google.common.base.Stopwatch;
2324
import com.google.common.collect.Iterables;
2425
import com.google.common.collect.Lists;
25-
import com.google.common.truth.Correspondence;
26-
import io.grpc.Context;
2726
import io.grpc.Metadata;
2827
import io.grpc.Server;
2928
import io.grpc.ServerCall;
3029
import io.grpc.ServerCallHandler;
3130
import io.grpc.ServerInterceptor;
3231
import io.grpc.Status;
32+
import io.grpc.internal.GrpcUtil;
3333
import java.io.IOException;
3434
import java.time.Duration;
3535
import java.util.ArrayList;
3636
import java.util.Arrays;
37-
import java.util.Collections;
3837
import java.util.List;
3938
import java.util.Objects;
40-
import java.util.Optional;
39+
import java.util.concurrent.CopyOnWriteArrayList;
4140
import java.util.concurrent.TimeUnit;
42-
import java.util.concurrent.atomic.AtomicInteger;
4341
import java.util.concurrent.atomic.AtomicReference;
44-
import java.util.function.Consumer;
42+
import java.util.function.BiConsumer;
4543
import javax.annotation.Nullable;
4644
import org.apache.hadoop.conf.Configuration;
4745
import org.apache.hadoop.hbase.TableName;
@@ -58,29 +56,27 @@
5856
import org.junit.Test;
5957
import org.junit.runner.RunWith;
6058
import org.junit.runners.Parameterized;
61-
import org.mockito.Mockito;
6259

6360
@RunWith(Parameterized.class)
6461
public class TestRetryBehavior {
6562

6663
private static final Duration DELAY = Duration.ofMillis(5);
6764
private static final Duration ATTEMPT_TIMEOUT = Duration.ofMillis(450);
6865
private static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(2);
66+
// Tolerance for client-side scheduling/GC pauses between creating the gRPC Deadline and writing
67+
// the grpc-timeout header. Large enough to absorb CI jitter while still clearly distinguishing
68+
// ATTEMPT_TIMEOUT (450ms) from DELAY (5ms) and OPERATION_TIMEOUT (2s).
69+
private static final Duration DEADLINE_TOLERANCE = Duration.ofMillis(100);
70+
private static final Duration OPERATION_TIMEOUT_TOLERANCE = Duration.ofSeconds(1);
71+
6972
private final TestOp testOp;
7073

7174
private Server fakeServer;
7275

73-
private final List<Duration> remainingDurations = Collections.synchronizedList(new ArrayList<>());
74-
private final AtomicInteger callCount = new AtomicInteger();
75-
76-
private final AtomicReference<Consumer<ServerCall<?, ?>>> rpcRunnable =
76+
private final AtomicReference<BiConsumer<ServerCall<?, ?>, Metadata>> rpcHandler =
7777
new AtomicReference<>(
78-
(ServerCall<?, ?> call) -> call.close(Status.UNIMPLEMENTED, new Metadata()));
79-
80-
private static final Correspondence<Duration, Duration> MIN_DURATION_CORRESPONDENCE =
81-
Correspondence.from((actual, expected) -> actual.compareTo(expected) >= 0, ">=");
82-
private static final Correspondence<Duration, Duration> MAX_DURATION_CORRESPONDENCE =
83-
Correspondence.from((actual, expected) -> actual.compareTo(expected) <= 0, "<=");
78+
(ServerCall<?, ?> call, Metadata headers) ->
79+
call.close(Status.UNIMPLEMENTED, new Metadata()));
8480

8581
interface TableRunnable {
8682
void run(Table table) throws IOException;
@@ -127,33 +123,41 @@ public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
127123
ServerCall<ReqT, RespT> serverCall,
128124
Metadata metadata,
129125
ServerCallHandler<ReqT, RespT> serverCallHandler) {
130-
callCount.incrementAndGet();
131-
132-
// record the deadline
133-
@Nullable
134-
Duration duration =
135-
Optional.ofNullable(Context.current().getDeadline())
136-
.map(d -> Duration.ofMillis(d.timeRemaining(TimeUnit.MILLISECONDS)))
137-
.orElse(null);
138-
remainingDurations.add(duration);
139-
140126
// execute test specific callback
141-
rpcRunnable.get().accept(serverCall);
127+
rpcHandler.get().accept(serverCall, metadata);
142128

143129
// Don't really care about client requests, just blackhole them
144130
// this will prevent any invocations of the stub
145-
@SuppressWarnings("unchecked")
146-
ServerCall.Listener<ReqT> blackhole = Mockito.mock(ServerCall.Listener.class);
147-
return blackhole;
131+
return new ServerCall.Listener<ReqT>() {};
148132
}
149133
})
150134
.addService(new BigtableGrpc.BigtableImplBase() {})
151135
.buildAndStart();
152136
}
153137

154138
@After
155-
public void teardown() {
139+
public void teardown() throws InterruptedException {
156140
fakeServer.shutdownNow();
141+
fakeServer.awaitTermination(5, TimeUnit.SECONDS);
142+
}
143+
144+
private void warmUp(Table table) {
145+
// Prime the channel, TCP/HTTP2 connection, and operation code path with a fast non-retryable
146+
// error so connection setup and cold-start JIT don't skew attempt timing or deadlines.
147+
rpcHandler.set((call, headers) -> call.close(Status.FAILED_PRECONDITION, new Metadata()));
148+
Exception e = Assert.assertThrows(Exception.class, () -> testOp.runnable.run(table));
149+
assertThat(extractStatus(e).getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION);
150+
}
151+
152+
/**
153+
* Reads the wire {@code grpc-timeout} header directly rather than calling {@code
154+
* Context.current().getDeadline().timeRemaining(MILLISECONDS)}, avoiding loopback transit delay,
155+
* server executor scheduling jitter, and millisecond truncation.
156+
*/
157+
@Nullable
158+
private static Duration extractTimeout(Metadata metadata) {
159+
Long timeoutNanos = metadata.get(GrpcUtil.TIMEOUT_KEY);
160+
return timeoutNanos != null ? Duration.ofNanos(timeoutNanos) : null;
157161
}
158162

159163
private Configuration createBaseConfig() {
@@ -191,106 +195,141 @@ private static void setAttemptTimeout(Configuration config, Duration timeout) {
191195

192196
@Test
193197
public void testRpcWillRetryOnAbort() throws Exception {
194-
rpcRunnable.set((call) -> call.close(Status.ABORTED, new Metadata()));
195-
196198
try (Connection connection = ConnectionFactory.createConnection(createBaseConfig());
197199
Table table = connection.getTable(TableName.valueOf("fake-table"))) {
200+
warmUp(table);
201+
202+
List<Duration> attemptTimeouts = new CopyOnWriteArrayList<>();
203+
rpcHandler.set(
204+
(call, headers) -> {
205+
attemptTimeouts.add(extractTimeout(headers));
206+
call.close(Status.ABORTED, new Metadata());
207+
});
198208

199209
Stopwatch stopwatch = Stopwatch.createStarted();
200210
// TODO: this should be an IOException, but scanner.next isnt wrapping exceptions properly
201211
Exception e = Assert.assertThrows(Exception.class, () -> testOp.runnable.run(table));
202212

203213
Duration elapsed = stopwatch.elapsed();
214+
List<Duration> observedTimeouts = new ArrayList<>(attemptTimeouts);
204215

205216
Status status = extractStatus(e);
206-
assertThat(status.getCode()).isEqualTo(Status.Code.ABORTED);
207-
208-
// Server immediately errors out, so exponential backoff will be the bottleneck for retries
209-
// Maximum delays will be: 5, 10, 20, 40, 80, 160, 320, 640, 1m, 1m, ...
210-
// With 2s operation deadline, minimum number of attempts will be 9
211-
// Since exponential delay uses full jitter (which will decrease delay by 50% on average),
212-
// there will most likely be more attempts. However to avoid flakiness, we can only make
213-
// assertions about attempts that are guaranteed to happen. For example with 400ms remaining
214-
// in the operation timeout, the 10th delay can be 100ms, causing the attempt timeout to be
215-
// 300ms and the 11th delay could be 50ms causing the next attempt to have an attempt timeout
216-
// of 250ms.
217-
assertThat(callCount.get()).isAtLeast(9);
218-
// Ignoring the first attempt, because it will be unstable due to connection setup
219-
assertThat(remainingDurations.subList(1, 9))
220-
.comparingElementsUsing(MIN_DURATION_CORRESPONDENCE)
221-
.contains(ATTEMPT_TIMEOUT.minus(Duration.ofMillis(5)));
222-
223-
// but should still be limited by the operation timeout with some jitter
224-
assertThat(elapsed).isAtMost(OPERATION_TIMEOUT.plus(ATTEMPT_TIMEOUT.dividedBy(2)));
217+
// Retrying ABORTED runs until OPERATION_TIMEOUT (or maxAttempts for scans). When a final
218+
// retry is scheduled near OPERATION_TIMEOUT, its clamped attempt deadline (or the overall
219+
// CallOptions gRPC deadline on read/scan paths) can expire before the server's ABORTED
220+
// returns, legitimately surfacing DEADLINE_EXCEEDED instead of ABORTED.
221+
assertThat(status.getCode()).isAnyOf(Status.Code.ABORTED, Status.Code.DEADLINE_EXCEEDED);
222+
223+
// Server immediately errors out, so exponential backoff is the bottleneck for retries.
224+
// Maximum delays are: 5, 10, 20, 40, 80, 160, 320, 640, 1280, ... (with full jitter).
225+
// The first 8 attempts have cumulative max delay of 635ms (leaving >1.3s before the 2s
226+
// operation timeout). Even if attempts hung for ATTEMPT_TIMEOUT (450ms), at most 5 could fit
227+
// in 2s, so >= 8 attempts confirms ABORTED was retried.
228+
assertThat(observedTimeouts.size()).isAtLeast(8);
229+
230+
for (Duration timeout : observedTimeouts) {
231+
assertWithMessage("all attempts in %s", observedTimeouts).that(timeout).isNotNull();
232+
assertWithMessage("all attempts in %s", observedTimeouts)
233+
.that(timeout)
234+
.isAtMost(ATTEMPT_TIMEOUT);
235+
}
236+
237+
// The first 7 attempts have cumulative max delay of 315ms, leaving >1.2s of headroom before
238+
// remaining operation time drops below ATTEMPT_TIMEOUT (1550ms), so none should be clamped.
239+
List<Duration> unclampedTimeouts = observedTimeouts.subList(0, 7);
240+
for (Duration timeout : unclampedTimeouts) {
241+
assertWithMessage("unclamped attempts in %s", observedTimeouts)
242+
.that(timeout)
243+
.isAtLeast(ATTEMPT_TIMEOUT.minus(DEADLINE_TOLERANCE));
244+
}
245+
246+
// Should still be limited by the operation timeout.
247+
assertThat(elapsed).isAtMost(OPERATION_TIMEOUT.plus(OPERATION_TIMEOUT_TOLERANCE));
225248
}
226249
}
227250

228251
@Test
229252
public void testRpcWillRespectAttemptTimeout() throws IOException {
230-
rpcRunnable.set(
231-
(call) -> {
232-
/* hang indefinitely */
233-
});
234-
235253
try (Connection connection = ConnectionFactory.createConnection(createBaseConfig());
236254
Table table = connection.getTable(TableName.valueOf("fake-table"))) {
255+
warmUp(table);
256+
257+
List<Duration> attemptTimeouts = new CopyOnWriteArrayList<>();
258+
rpcHandler.set(
259+
(call, headers) -> {
260+
attemptTimeouts.add(extractTimeout(headers));
261+
/* hang indefinitely */
262+
});
237263

238264
Stopwatch stopwatch = Stopwatch.createStarted();
239265
// TODO: this should be an IOException, but scan doesnt properly wrap it
240266
Exception e = Assert.assertThrows(Exception.class, () -> testOp.runnable.run(table));
241267

242268
Duration elapsed = stopwatch.elapsed();
269+
List<Duration> observedTimeouts = new ArrayList<>(attemptTimeouts);
243270

244271
Status status = extractStatus(e);
245272
assertThat(status.getCode()).isEqualTo(Status.Code.DEADLINE_EXCEEDED);
246273

247-
// Server will hang for the attempt timeout and the client should retry the attempt
248-
// 5 * 450ms attempt timeouts > 2s operation timeout
249-
// 450 + 5 + 450 + 10 + 450 + 20 + 450 + 40 + 125
250-
assertThat(callCount.get()).isAtMost(5);
251-
// 3 * 450ms attempt timeouts + jitter < 2s operation timeout
252-
assertThat(callCount.get()).isAtLeast(3);
253-
assertThat(remainingDurations)
254-
.comparingElementsUsing(MAX_DURATION_CORRESPONDENCE)
255-
.contains(ATTEMPT_TIMEOUT);
256-
257-
// Ignoring the first and last attempt, all attempts should be just under attempt timeout
258-
assertThat(remainingDurations.subList(1, remainingDurations.size() - 1))
259-
.comparingElementsUsing(MIN_DURATION_CORRESPONDENCE)
260-
.contains(ATTEMPT_TIMEOUT.minus(Duration.ofMillis(10)));
261-
262-
// Altogether should still be limited by the operation timeout with some jitter
263-
assertThat(elapsed).isAtMost(OPERATION_TIMEOUT.plus(ATTEMPT_TIMEOUT));
274+
// Server hangs for the attempt timeout and the client should retry the attempt.
275+
// 4 * 450ms attempt timeouts + backoff (5+10+20+40 <= 75ms) leaves ~125ms for a 5th
276+
// (clamped) attempt, so at most 5 attempts can occur within the 2s operation timeout.
277+
assertThat(observedTimeouts.size()).isAtMost(5);
278+
// 3 * 450ms attempt timeouts < 2s operation timeout with >600ms of slack.
279+
assertThat(observedTimeouts.size()).isAtLeast(3);
280+
281+
for (Duration timeout : observedTimeouts) {
282+
assertWithMessage("all attempts in %s", observedTimeouts).that(timeout).isNotNull();
283+
assertWithMessage("all attempts in %s", observedTimeouts)
284+
.that(timeout)
285+
.isAtMost(ATTEMPT_TIMEOUT);
286+
}
287+
288+
// Every attempt except possibly the last (which may be clamped to the remaining operation
289+
// timeout) should receive a full ATTEMPT_TIMEOUT.
290+
List<Duration> fullAttempts = observedTimeouts.subList(0, observedTimeouts.size() - 1);
291+
for (Duration timeout : fullAttempts) {
292+
assertWithMessage("non-last attempts in %s", observedTimeouts)
293+
.that(timeout)
294+
.isAtLeast(ATTEMPT_TIMEOUT.minus(DEADLINE_TOLERANCE));
295+
}
296+
297+
// Altogether should still be limited by the operation timeout.
298+
assertThat(elapsed).isAtMost(OPERATION_TIMEOUT.plus(OPERATION_TIMEOUT_TOLERANCE));
264299
}
265300
}
266301

267302
@Test
268303
public void testRpcWillNotRetryOnHangWithoutAttemptTimeout() throws IOException {
269-
rpcRunnable.set(
270-
(call) -> {
271-
/* hang indefinitely */
272-
});
273-
274304
Configuration configuration = createBaseConfig();
275305
setAttemptTimeout(configuration, OPERATION_TIMEOUT);
276306

277307
try (Connection connection = ConnectionFactory.createConnection(configuration);
278308
Table table = connection.getTable(TableName.valueOf("fake-table"))) {
309+
warmUp(table);
310+
311+
List<Duration> attemptTimeouts = new CopyOnWriteArrayList<>();
312+
rpcHandler.set(
313+
(call, headers) -> {
314+
attemptTimeouts.add(extractTimeout(headers));
315+
/* hang indefinitely */
316+
});
279317

280318
Stopwatch stopwatch = Stopwatch.createStarted();
281319
// TODO: this should be an IOException, but scans dont wrap it properly
282320
Exception e = Assert.assertThrows(Exception.class, () -> testOp.runnable.run(table));
283321

284322
Duration elapsed = stopwatch.elapsed();
323+
List<Duration> observedTimeouts = new ArrayList<>(attemptTimeouts);
285324

286325
Status status = extractStatus(e);
287326
assertThat(status.getCode()).isEqualTo(Status.Code.DEADLINE_EXCEEDED);
288327

289-
// Server will hang for the attempt timeout and the client should retry the attempt
290-
assertThat(callCount.get()).isEqualTo(1);
291-
assertThat(elapsed).isAtMost(OPERATION_TIMEOUT.plus(ATTEMPT_TIMEOUT.dividedBy(2)));
292-
assertThat(remainingDurations.get(0)).isGreaterThan(ATTEMPT_TIMEOUT);
293-
assertThat(remainingDurations.get(0)).isAtMost(OPERATION_TIMEOUT);
328+
// Server hangs for the full operation timeout and the client should not retry.
329+
assertThat(observedTimeouts).hasSize(1);
330+
assertThat(elapsed).isAtMost(OPERATION_TIMEOUT.plus(OPERATION_TIMEOUT_TOLERANCE));
331+
assertThat(observedTimeouts.get(0)).isAtLeast(OPERATION_TIMEOUT.minus(DEADLINE_TOLERANCE));
332+
assertThat(observedTimeouts.get(0)).isAtMost(OPERATION_TIMEOUT);
294333
}
295334
}
296335

0 commit comments

Comments
 (0)