|
16 | 16 | package com.google.cloud.bigtable.hbase; |
17 | 17 |
|
18 | 18 | import static com.google.common.truth.Truth.assertThat; |
| 19 | +import static com.google.common.truth.Truth.assertWithMessage; |
19 | 20 |
|
20 | 21 | import com.google.bigtable.v2.BigtableGrpc; |
21 | 22 | import com.google.cloud.bigtable.test.helper.TestServerBuilder; |
22 | 23 | import com.google.common.base.Stopwatch; |
23 | 24 | import com.google.common.collect.Iterables; |
24 | 25 | import com.google.common.collect.Lists; |
25 | | -import com.google.common.truth.Correspondence; |
26 | | -import io.grpc.Context; |
27 | 26 | import io.grpc.Metadata; |
28 | 27 | import io.grpc.Server; |
29 | 28 | import io.grpc.ServerCall; |
30 | 29 | import io.grpc.ServerCallHandler; |
31 | 30 | import io.grpc.ServerInterceptor; |
32 | 31 | import io.grpc.Status; |
| 32 | +import io.grpc.internal.GrpcUtil; |
33 | 33 | import java.io.IOException; |
34 | 34 | import java.time.Duration; |
35 | 35 | import java.util.ArrayList; |
36 | 36 | import java.util.Arrays; |
37 | | -import java.util.Collections; |
38 | 37 | import java.util.List; |
39 | 38 | import java.util.Objects; |
40 | | -import java.util.Optional; |
| 39 | +import java.util.concurrent.CopyOnWriteArrayList; |
41 | 40 | import java.util.concurrent.TimeUnit; |
42 | | -import java.util.concurrent.atomic.AtomicInteger; |
43 | 41 | import java.util.concurrent.atomic.AtomicReference; |
44 | | -import java.util.function.Consumer; |
| 42 | +import java.util.function.BiConsumer; |
45 | 43 | import javax.annotation.Nullable; |
46 | 44 | import org.apache.hadoop.conf.Configuration; |
47 | 45 | import org.apache.hadoop.hbase.TableName; |
|
58 | 56 | import org.junit.Test; |
59 | 57 | import org.junit.runner.RunWith; |
60 | 58 | import org.junit.runners.Parameterized; |
61 | | -import org.mockito.Mockito; |
62 | 59 |
|
63 | 60 | @RunWith(Parameterized.class) |
64 | 61 | public class TestRetryBehavior { |
65 | 62 |
|
66 | 63 | private static final Duration DELAY = Duration.ofMillis(5); |
67 | 64 | private static final Duration ATTEMPT_TIMEOUT = Duration.ofMillis(450); |
68 | 65 | 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 | + |
69 | 72 | private final TestOp testOp; |
70 | 73 |
|
71 | 74 | private Server fakeServer; |
72 | 75 |
|
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 = |
77 | 77 | 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())); |
84 | 80 |
|
85 | 81 | interface TableRunnable { |
86 | 82 | void run(Table table) throws IOException; |
@@ -127,33 +123,41 @@ public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( |
127 | 123 | ServerCall<ReqT, RespT> serverCall, |
128 | 124 | Metadata metadata, |
129 | 125 | 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 | | - |
140 | 126 | // execute test specific callback |
141 | | - rpcRunnable.get().accept(serverCall); |
| 127 | + rpcHandler.get().accept(serverCall, metadata); |
142 | 128 |
|
143 | 129 | // Don't really care about client requests, just blackhole them |
144 | 130 | // 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>() {}; |
148 | 132 | } |
149 | 133 | }) |
150 | 134 | .addService(new BigtableGrpc.BigtableImplBase() {}) |
151 | 135 | .buildAndStart(); |
152 | 136 | } |
153 | 137 |
|
154 | 138 | @After |
155 | | - public void teardown() { |
| 139 | + public void teardown() throws InterruptedException { |
156 | 140 | 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; |
157 | 161 | } |
158 | 162 |
|
159 | 163 | private Configuration createBaseConfig() { |
@@ -191,106 +195,141 @@ private static void setAttemptTimeout(Configuration config, Duration timeout) { |
191 | 195 |
|
192 | 196 | @Test |
193 | 197 | public void testRpcWillRetryOnAbort() throws Exception { |
194 | | - rpcRunnable.set((call) -> call.close(Status.ABORTED, new Metadata())); |
195 | | - |
196 | 198 | try (Connection connection = ConnectionFactory.createConnection(createBaseConfig()); |
197 | 199 | 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 | + }); |
198 | 208 |
|
199 | 209 | Stopwatch stopwatch = Stopwatch.createStarted(); |
200 | 210 | // TODO: this should be an IOException, but scanner.next isnt wrapping exceptions properly |
201 | 211 | Exception e = Assert.assertThrows(Exception.class, () -> testOp.runnable.run(table)); |
202 | 212 |
|
203 | 213 | Duration elapsed = stopwatch.elapsed(); |
| 214 | + List<Duration> observedTimeouts = new ArrayList<>(attemptTimeouts); |
204 | 215 |
|
205 | 216 | 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)); |
225 | 248 | } |
226 | 249 | } |
227 | 250 |
|
228 | 251 | @Test |
229 | 252 | public void testRpcWillRespectAttemptTimeout() throws IOException { |
230 | | - rpcRunnable.set( |
231 | | - (call) -> { |
232 | | - /* hang indefinitely */ |
233 | | - }); |
234 | | - |
235 | 253 | try (Connection connection = ConnectionFactory.createConnection(createBaseConfig()); |
236 | 254 | 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 | + }); |
237 | 263 |
|
238 | 264 | Stopwatch stopwatch = Stopwatch.createStarted(); |
239 | 265 | // TODO: this should be an IOException, but scan doesnt properly wrap it |
240 | 266 | Exception e = Assert.assertThrows(Exception.class, () -> testOp.runnable.run(table)); |
241 | 267 |
|
242 | 268 | Duration elapsed = stopwatch.elapsed(); |
| 269 | + List<Duration> observedTimeouts = new ArrayList<>(attemptTimeouts); |
243 | 270 |
|
244 | 271 | Status status = extractStatus(e); |
245 | 272 | assertThat(status.getCode()).isEqualTo(Status.Code.DEADLINE_EXCEEDED); |
246 | 273 |
|
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)); |
264 | 299 | } |
265 | 300 | } |
266 | 301 |
|
267 | 302 | @Test |
268 | 303 | public void testRpcWillNotRetryOnHangWithoutAttemptTimeout() throws IOException { |
269 | | - rpcRunnable.set( |
270 | | - (call) -> { |
271 | | - /* hang indefinitely */ |
272 | | - }); |
273 | | - |
274 | 304 | Configuration configuration = createBaseConfig(); |
275 | 305 | setAttemptTimeout(configuration, OPERATION_TIMEOUT); |
276 | 306 |
|
277 | 307 | try (Connection connection = ConnectionFactory.createConnection(configuration); |
278 | 308 | 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 | + }); |
279 | 317 |
|
280 | 318 | Stopwatch stopwatch = Stopwatch.createStarted(); |
281 | 319 | // TODO: this should be an IOException, but scans dont wrap it properly |
282 | 320 | Exception e = Assert.assertThrows(Exception.class, () -> testOp.runnable.run(table)); |
283 | 321 |
|
284 | 322 | Duration elapsed = stopwatch.elapsed(); |
| 323 | + List<Duration> observedTimeouts = new ArrayList<>(attemptTimeouts); |
285 | 324 |
|
286 | 325 | Status status = extractStatus(e); |
287 | 326 | assertThat(status.getCode()).isEqualTo(Status.Code.DEADLINE_EXCEEDED); |
288 | 327 |
|
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); |
294 | 333 | } |
295 | 334 | } |
296 | 335 |
|
|
0 commit comments