diff --git a/CHANGELOG.md b/CHANGELOG.md index e82e985ea..ec8345ebf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ * Core: added opt-in PRIMARY/PROMOTED Bridge pile preference with synchronized-pile fallback * Core: added Meter histograms with explicit bucket boundaries, OpenTelemetryMeter uses OpenTelemetry database latency boundaries by default +* Query: added `ydb.client.retry.duration` and `ydb.client.retry.attempts` metrics and operation name to SessionRetryContext +* Table: added `ydb.client.retry.duration` and `ydb.client.retry.attempts` metrics and operation name to SessionRetryContext ## 2.5.0 ## * Core: upgraded to grpc-java v1.82.4 diff --git a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java index 0e2010d84..e90f052f7 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -21,6 +21,7 @@ import tech.ydb.core.Status; import tech.ydb.core.StatusCode; import tech.ydb.core.UnexpectedResultException; +import tech.ydb.core.metrics.Meter; import tech.ydb.core.tracing.Scope; import tech.ydb.core.tracing.Span; import tech.ydb.core.tracing.SpanKind; @@ -28,6 +29,7 @@ import tech.ydb.core.utils.FutureTools; import tech.ydb.query.QueryClient; import tech.ydb.query.QuerySession; +import tech.ydb.table.impl.RetryMetrics; /** @@ -49,6 +51,7 @@ public class SessionRetryContext { private final int fastBackoffCeiling; private final boolean retryNotFound; private final boolean idempotent; + private final RetryMetrics metrics; private SessionRetryContext(Builder b) { this.queryClient = b.queryClient; @@ -61,6 +64,7 @@ private SessionRetryContext(Builder b) { this.fastBackoffCeiling = b.fastBackoffCeiling; this.retryNotFound = b.retryNotFound; this.idempotent = b.idempotent; + this.metrics = new RetryMetrics(b.meter); } public static Builder create(QueryClient sessionSupplier) { @@ -68,13 +72,41 @@ public static Builder create(QueryClient sessionSupplier) { } public CompletableFuture> supplyResult(Function>> fn) { - RetryableResultTask task = new RetryableResultTask<>(fn); - task.requestSession(); - return task.getFuture(); + return execute(new RetryableResultTask<>(null, fn)); + } + + /** + * Executes the function with retries as one logical operation. + * + * @param operationName name of the logical operation, used as the retry span name and reported as the + * {@code operation.name} attribute of {@code ydb.client.retry.*} metrics + * @param fn function to execute + * @param type of the result value + * @return future with the result of the last attempt + */ + public CompletableFuture> supplyResult(String operationName, + Function>> fn) { + return execute(new RetryableResultTask<>(Objects.requireNonNull(operationName, "operationName is null"), fn)); } public CompletableFuture supplyStatus(Function> fn) { - RetryableStatusTask task = new RetryableStatusTask(fn); + return execute(new RetryableStatusTask(null, fn)); + } + + /** + * Executes the function with retries as one logical operation. + * + * @param operationName name of the logical operation, used as the retry span name and reported as the + * {@code operation.name} attribute of {@code ydb.client.retry.*} metrics + * @param fn function to execute + * @return future with the status of the last attempt + */ + public CompletableFuture supplyStatus(String operationName, + Function> fn) { + return execute(new RetryableStatusTask(Objects.requireNonNull(operationName, "operationName is null"), fn)); + } + + private static CompletableFuture execute(BaseRetryableTask task) { task.requestSession(); return task.getFuture(); } @@ -145,14 +177,17 @@ private abstract class BaseRetryableTask implements Runnable { private final CompletableFuture promise = new CompletableFuture<>(); private final AtomicInteger retryNumber = new AtomicInteger(); private final Function> fn; + private final RetryMetrics.Operation metricsOperation; private final Tracer tracer; private final Span executeSpan; private Span trySpan; - BaseRetryableTask(Function> fn) { + BaseRetryableTask(@Nullable String operationName, Function> fn) { this.fn = fn; + this.metricsOperation = metrics.startOperation(operationName); this.tracer = queryClient.getTracer(); - this.executeSpan = tracer.startSpan(EXECUTE_SPAN_NAME, SpanKind.INTERNAL); + this.executeSpan = tracer.startSpan(operationName != null ? operationName : EXECUTE_SPAN_NAME, + SpanKind.INTERNAL); try (@SuppressWarnings("unused") Scope ignored = executeSpan.makeCurrent()) { this.trySpan = tracer.startSpan(EXECUTE_WITH_RETRY_SPAN_NAME, SpanKind.INTERNAL); @@ -178,6 +213,7 @@ public void run() { } public void requestSession() { + metricsOperation.onAttempt(); CompletableFuture> sessionFuture = createSessionWithRetrySpanParent(); if (sessionFuture.isDone() && !sessionFuture.isCompletedExceptionally()) { // faster than subscribing on future @@ -216,7 +252,7 @@ private void acceptSession(@Nonnull Result sessionResult) { Status status = toStatus(fnResult); if (status.isSuccess()) { if (promise.complete(fnResult)) { - finishSpans(status, null); + finishObservability(status, null); } else { finishOnCancel(); } @@ -225,7 +261,7 @@ private void acceptSession(@Nonnull Result sessionResult) { } } } catch (Throwable unexpected) { - finishSpans(null, unexpected); + finishObservability(null, unexpected); promise.completeExceptionally(unexpected); } }); @@ -245,13 +281,13 @@ private void scheduleNext(long delayMillis) { } private void finishOnCancel() { - finishSpans(null, new CancellationException("RunWithRetry was cancelled")); + finishObservability(null, new CancellationException("RunWithRetry was cancelled")); } private void handleError(@Nonnull Status status, R result) { // Check retrayable status if (!canRetry(status.getCode())) { - finishSpans(status, null); + finishObservability(status, null); promise.complete(result); return; } @@ -263,7 +299,7 @@ private void handleError(@Nonnull Status status, R result) { startNextRetrySpan(next); scheduleNext(next); } else { - finishSpans(status, null); + finishObservability(status, null); promise.complete(result); } } @@ -271,7 +307,7 @@ private void handleError(@Nonnull Status status, R result) { private void handleException(@Nonnull Throwable ex) { // Check retrayable execption if (!canRetry(ex)) { - finishSpans(null, ex); + finishObservability(null, ex); promise.completeExceptionally(ex); return; } @@ -283,7 +319,7 @@ private void handleException(@Nonnull Throwable ex) { startNextRetrySpan(next); scheduleNext(next); } else { - finishSpans(null, ex); + finishObservability(null, ex); promise.completeExceptionally(ex); } } @@ -307,11 +343,12 @@ private void finishTrySpan(Status status, Throwable throwable) { trySpan = Span.NOOP; } - private void finishSpans(@Nullable Status status, Throwable throwable) { + private void finishObservability(@Nullable Status status, Throwable throwable) { Throwable unwrapped = FutureTools.unwrapCompletionException(throwable); finishTrySpan(status, throwable); executeSpan.setStatus(status, unwrapped); executeSpan.end(); + metricsOperation.finish(); } } @@ -319,8 +356,8 @@ private void finishSpans(@Nullable Status status, Throwable throwable) { * RETRYABLE RESULT TASK */ private final class RetryableResultTask extends BaseRetryableTask> { - RetryableResultTask(Function>> fn) { - super(fn); + RetryableResultTask(@Nullable String operationName, Function>> fn) { + super(operationName, fn); } @Override @@ -338,8 +375,8 @@ Result toFailedResult(Result sessionResult) { * RETRYABLE STATUS TASK */ private final class RetryableStatusTask extends BaseRetryableTask { - RetryableStatusTask(Function> fn) { - super(fn); + RetryableStatusTask(@Nullable String operationName, Function> fn) { + super(operationName, fn); } @Override @@ -368,6 +405,7 @@ public static final class Builder { private int fastBackoffCeiling = 10; private boolean retryNotFound = true; private boolean idempotent = false; + private Meter meter = Meter.NOOP; public Builder(QueryClient queryClient) { this.queryClient = queryClient; @@ -420,6 +458,11 @@ public Builder idempotent(boolean idempotent) { return this; } + public Builder withMeter(Meter meter) { + this.meter = Objects.requireNonNull(meter); + return this; + } + public SessionRetryContext build() { return new SessionRetryContext(this); } diff --git a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java new file mode 100644 index 000000000..5f36b86e5 --- /dev/null +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -0,0 +1,120 @@ +package tech.ydb.query.tools; + +import java.util.Arrays; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatcher; + +import tech.ydb.core.Result; +import tech.ydb.core.Status; +import tech.ydb.core.StatusCode; +import tech.ydb.core.metrics.Attr; +import tech.ydb.core.metrics.DoubleHistogram; +import tech.ydb.core.metrics.Meter; +import tech.ydb.core.tracing.Span; +import tech.ydb.core.tracing.SpanKind; +import tech.ydb.core.tracing.Tracer; +import tech.ydb.query.QueryClient; +import tech.ydb.query.QuerySession; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +public class SessionRetryContextMetricsTest { + private final QueryClient queryClient = mock(QueryClient.class); + private final ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class); + private final Tracer tracer = mock(Tracer.class); + private final Meter meter = mock(Meter.class); + private final DoubleHistogram duration = mock(DoubleHistogram.class); + private final DoubleHistogram attempts = mock(DoubleHistogram.class); + + private final ArgumentMatcher myOp = a -> "operation.name".equals(a.getKey()) && "MyOp".equals(a.getValue()); + + @Before + public void setup() { + when(queryClient.getTracer()).thenReturn(tracer); + when(queryClient.getScheduler()).thenReturn(scheduler); + when(queryClient.createSession(any())) + .thenReturn(CompletableFuture.completedFuture(Result.success(mock(QuerySession.class)))); + when(tracer.startSpan(anyString(), any())).thenReturn(Span.NOOP); + when(scheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(inv -> { + inv.getArgument(0).run(); + return null; + }); + + when(meter.createHistogram(eq("ydb.client.retry.duration"), eq("s"), anyString(), + eq(Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 2d, 5d, 10d, 30d)))).thenReturn(duration); + when(meter.createHistogram(eq("ydb.client.retry.attempts"), eq("{attempt}"), anyString(), + eq(Arrays.asList(1d, 2d, 3d, 4d, 5d, 7d, 10d, 20d)))).thenReturn(attempts); + } + + private SessionRetryContext retryContext() { + return SessionRetryContext.create(queryClient).maxRetries(2).withMeter(meter).build(); + } + + @Test + public void namedOperationSucceededOnFirstAttempt() { + Result result = retryContext().supplyResult("MyOp", + session -> CompletableFuture.completedFuture(Result.success(42))).join(); + + Assert.assertEquals(Integer.valueOf(42), result.getValue()); + verify(tracer).startSpan("MyOp", SpanKind.INTERNAL); + verify(tracer, never()).startSpan("ydb.RunWithRetry", SpanKind.INTERNAL); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } + + @Test + public void retriedOperationWithoutNameHasNoAttributes() { + AtomicInteger calls = new AtomicInteger(); + Status status = retryContext().supplyStatus(session -> CompletableFuture.completedFuture( + calls.getAndIncrement() == 0 ? Status.of(StatusCode.OVERLOADED) : Status.SUCCESS)).join(); + + status.expectSuccess(); + verify(tracer).startSpan("ydb.RunWithRetry", SpanKind.INTERNAL); + verify(attempts).record(2d); + verify(duration).record(anyDouble()); + verifyNoMoreInteractions(attempts, duration); + } + + @Test + public void nonRetryableFailureIsSingleAttempt() { + Status status = retryContext().supplyStatus("MyOp", + session -> CompletableFuture.completedFuture(Status.of(StatusCode.SCHEME_ERROR))).join(); + + Assert.assertEquals(StatusCode.SCHEME_ERROR, status.getCode()); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } + + @Test + public void exhaustedSessionRetriesCountEveryAttempt() { + when(queryClient.createSession(any())) + .thenReturn(CompletableFuture.completedFuture(Result.fail(Status.of(StatusCode.OVERLOADED)))); + + Status status = retryContext().supplyStatus("MyOp", session -> { + throw new AssertionError("session must not be acquired"); + }).join(); + + Assert.assertEquals(StatusCode.OVERLOADED, status.getCode()); + verify(attempts).record(eq(3d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } +} diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index 9593c77fc..926e7d8d3 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -22,11 +22,13 @@ import tech.ydb.core.Status; import tech.ydb.core.StatusCode; import tech.ydb.core.UnexpectedResultException; +import tech.ydb.core.metrics.Meter; import tech.ydb.core.tracing.Scope; import tech.ydb.core.tracing.Span; import tech.ydb.core.tracing.SpanKind; import tech.ydb.core.tracing.Tracer; import tech.ydb.core.utils.FutureTools; +import tech.ydb.table.impl.RetryMetrics; /** @@ -48,6 +50,7 @@ public class SessionRetryContext { private final int fastBackoffCeiling; private final boolean retryNotFound; private final boolean idempotent; + private final RetryMetrics metrics; private SessionRetryContext(Builder b) { this.sessionSupplier = b.sessionSupplier; @@ -60,6 +63,7 @@ private SessionRetryContext(Builder b) { this.fastBackoffCeiling = b.fastBackoffCeiling; this.retryNotFound = b.retryNotFound; this.idempotent = b.idempotent; + this.metrics = new RetryMetrics(b.meter); } public static Builder create(SessionSupplier sessionSupplier) { @@ -76,14 +80,54 @@ public CompletableFuture supplyStatus(Function CompletableFuture> supplyResult(SessionRetryHandler h, Function>> fn) { - RetryableResultTask task = new RetryableResultTask<>(h, fn); - task.requestSession(); - return task.getFuture(); + return execute(new RetryableResultTask<>(null, h, fn)); } public CompletableFuture supplyStatus(SessionRetryHandler h, Function> fn) { - RetryableStatusTask task = new RetryableStatusTask(h, fn); + return execute(new RetryableStatusTask(null, h, fn)); + } + + /** + * Executes the function with retries as one logical operation. + * + * @param operationName name of the logical operation, used as the retry span name and reported as the + * {@code operation.name} attribute of {@code ydb.client.retry.*} metrics + * @param fn function to execute + * @param type of the result value + * @return future with the result of the last attempt + */ + public CompletableFuture> supplyResult(String operationName, + Function>> fn) { + return supplyResult(operationName, SessionRetryHandler.DEFAULT, fn); + } + + /** + * Executes the function with retries as one logical operation. + * + * @param operationName name of the logical operation, used as the retry span name and reported as the + * {@code operation.name} attribute of {@code ydb.client.retry.*} metrics + * @param fn function to execute + * @return future with the status of the last attempt + */ + public CompletableFuture supplyStatus(String operationName, + Function> fn) { + return supplyStatus(operationName, SessionRetryHandler.DEFAULT, fn); + } + + public CompletableFuture> supplyResult(String operationName, SessionRetryHandler h, + Function>> fn) { + Objects.requireNonNull(operationName, "operationName is null"); + return execute(new RetryableResultTask<>(operationName, h, fn)); + } + + public CompletableFuture supplyStatus(String operationName, SessionRetryHandler h, + Function> fn) { + Objects.requireNonNull(operationName, "operationName is null"); + return execute(new RetryableStatusTask(operationName, h, fn)); + } + + private static CompletableFuture execute(BaseRetryableTask task) { task.requestSession(); return task.getFuture(); } @@ -156,15 +200,19 @@ private abstract class BaseRetryableTask implements Runnable { private final Function> fn; private final long createTimestamp = Instant.now().toEpochMilli(); private final SessionRetryHandler handler; + private final RetryMetrics.Operation metricsOperation; private final Tracer tracer; private final Span executeSpan; private Span trySpan; - BaseRetryableTask(SessionRetryHandler h, Function> fn) { + BaseRetryableTask(@Nullable String operationName, SessionRetryHandler h, + Function> fn) { this.fn = fn; this.handler = h; + this.metricsOperation = metrics.startOperation(operationName); this.tracer = sessionSupplier.getTracer(); - this.executeSpan = tracer.startSpan(EXECUTE_SPAN_NAME, SpanKind.INTERNAL); + this.executeSpan = tracer.startSpan(operationName != null ? operationName : EXECUTE_SPAN_NAME, + SpanKind.INTERNAL); try (@SuppressWarnings("unused") Scope ignored = executeSpan.makeCurrent()) { this.trySpan = tracer.startSpan(EXECUTE_WITH_RETRY_SPAN_NAME, SpanKind.INTERNAL); @@ -195,6 +243,7 @@ public void run() { } public void requestSession() { + metricsOperation.onAttempt(); CompletableFuture> sessionFuture = createSessionWithRetrySpanParent(); if (sessionFuture.isDone() && !sessionFuture.isCompletedExceptionally()) { // faster than subscribing on future @@ -234,7 +283,7 @@ private void acceptSession(@Nonnull Result sessionResult) { if (status.isSuccess()) { if (promise.complete(fnResult)) { handler.onSuccess(SessionRetryContext.this, retryNumber.get(), ms()); - finishSpans(status, null); + finishObservability(status, null); } else { handler.onCancel(SessionRetryContext.this, retryNumber.get(), ms()); finishOnCancel(); @@ -245,7 +294,7 @@ private void acceptSession(@Nonnull Result sessionResult) { } } catch (Throwable unexpected) { handler.onError(SessionRetryContext.this, unexpected, retryNumber.get(), ms()); - finishSpans(null, unexpected); + finishObservability(null, unexpected); promise.completeExceptionally(unexpected); } }); @@ -265,14 +314,14 @@ private void scheduleNext(long delayMillis) { } private void finishOnCancel() { - finishSpans(null, new CancellationException("RunWithRetry was cancelled")); + finishObservability(null, new CancellationException("RunWithRetry was cancelled")); } private void handleError(@Nonnull Status status, R result) { StatusCode code = status.getCode(); if (!canRetry(code)) { handler.onError(SessionRetryContext.this, code, retryNumber.get(), ms()); - finishSpans(status, null); + finishObservability(status, null); promise.complete(result); return; } @@ -286,7 +335,7 @@ private void handleError(@Nonnull Status status, R result) { scheduleNext(next); } else { handler.onLimit(SessionRetryContext.this, code, maxRetries, ms()); - finishSpans(status, null); + finishObservability(status, null); promise.complete(result); } } @@ -295,7 +344,7 @@ private void handleException(@Nonnull Throwable ex) { // Check retrayable execption if (!canRetry(ex)) { handler.onError(SessionRetryContext.this, ex, retryNumber.get(), ms()); - finishSpans(null, ex); + finishObservability(null, ex); promise.completeExceptionally(ex); return; } @@ -309,7 +358,7 @@ private void handleException(@Nonnull Throwable ex) { scheduleNext(next); } else { handler.onLimit(SessionRetryContext.this, ex, maxRetries, ms()); - finishSpans(null, ex); + finishObservability(null, ex); promise.completeExceptionally(ex); } } @@ -333,11 +382,12 @@ private void finishTrySpan(Status status, Throwable throwable) { trySpan = Span.NOOP; } - private void finishSpans(@Nullable Status status, Throwable throwable) { + private void finishObservability(@Nullable Status status, Throwable throwable) { Throwable unwrapped = FutureTools.unwrapCompletionException(throwable); finishTrySpan(status, throwable); executeSpan.setStatus(status, unwrapped); executeSpan.end(); + metricsOperation.finish(); } } @@ -345,8 +395,9 @@ private void finishSpans(@Nullable Status status, Throwable throwable) { * RETRYABLE RESULT TASK */ private final class RetryableResultTask extends BaseRetryableTask> { - RetryableResultTask(SessionRetryHandler h, Function>> fn) { - super(h, fn); + RetryableResultTask(@Nullable String operationName, SessionRetryHandler h, + Function>> fn) { + super(operationName, h, fn); } @Override @@ -364,8 +415,9 @@ Result toFailedResult(Result sessionResult) { * RETRYABLE STATUS TASK */ private final class RetryableStatusTask extends BaseRetryableTask { - RetryableStatusTask(SessionRetryHandler h, Function> fn) { - super(h, fn); + RetryableStatusTask(@Nullable String operationName, SessionRetryHandler h, + Function> fn) { + super(operationName, h, fn); } @Override @@ -394,6 +446,7 @@ public static final class Builder { private int fastBackoffCeiling = 10; private boolean retryNotFound = true; private boolean idempotent = false; + private Meter meter = Meter.NOOP; public Builder(SessionSupplier sessionSupplier) { this.sessionSupplier = sessionSupplier; @@ -446,6 +499,11 @@ public Builder idempotent(boolean idempotent) { return this; } + public Builder withMeter(Meter meter) { + this.meter = Objects.requireNonNull(meter); + return this; + } + public SessionRetryContext build() { return new SessionRetryContext(this); } diff --git a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java new file mode 100644 index 000000000..f782bd73e --- /dev/null +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -0,0 +1,60 @@ +package tech.ydb.table.impl; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.Nullable; + +import tech.ydb.core.impl.Observability; +import tech.ydb.core.metrics.Attr; +import tech.ydb.core.metrics.DoubleHistogram; +import tech.ydb.core.metrics.Meter; + +public final class RetryMetrics { + private static final String OPERATION_NAME_ATTR = "operation.name"; + private static final Attr[] NO_ATTRS = new Attr[0]; + private static final double NANOS_IN_SECOND = 1_000_000_000.0; + private static final List DURATION_BUCKETS = Arrays.asList( + 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 2d, 5d, 10d, 30d); + private static final List ATTEMPTS_BUCKETS = Arrays.asList(1d, 2d, 3d, 4d, 5d, 7d, 10d, 20d); + + private final DoubleHistogram duration; + private final DoubleHistogram attempts; + + public RetryMetrics(Meter meter) { + Observability.reportMetricsUsage(meter); + this.duration = meter.createHistogram("ydb.client.retry.duration", "s", + "Total user-visible duration of a logical operation executed through the retry policy, " + + "including all attempts and back-off delays.", + DURATION_BUCKETS); + this.attempts = meter.createHistogram("ydb.client.retry.attempts", "{attempt}", + "Total number of attempts performed by the retry policy for one logical operation. " + + "A value of 1 means the operation succeeded on the first try.", + ATTEMPTS_BUCKETS); + } + + public Operation startOperation(@Nullable String operationName) { + return new Operation(operationName); + } + + public final class Operation { + private final long startNanos = System.nanoTime(); + private int attemptCount; + private final Attr[] attrs; + + private Operation(@Nullable String operationName) { + this.attrs = operationName != null + ? new Attr[]{Attr.of(OPERATION_NAME_ATTR, operationName)} + : NO_ATTRS; + } + + public void onAttempt() { + attemptCount++; + } + + public void finish() { + duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); + attempts.record(attemptCount, attrs); + } + } +} diff --git a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java new file mode 100644 index 000000000..5d0e76352 --- /dev/null +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -0,0 +1,118 @@ +package tech.ydb.table; + +import java.util.Arrays; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatcher; + +import tech.ydb.core.Result; +import tech.ydb.core.Status; +import tech.ydb.core.StatusCode; +import tech.ydb.core.metrics.Attr; +import tech.ydb.core.metrics.DoubleHistogram; +import tech.ydb.core.metrics.Meter; +import tech.ydb.core.tracing.Span; +import tech.ydb.core.tracing.SpanKind; +import tech.ydb.core.tracing.Tracer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +public class SessionRetryContextMetricsTest { + private final SessionSupplier sessionSupplier = mock(SessionSupplier.class); + private final ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class); + private final Tracer tracer = mock(Tracer.class); + private final Meter meter = mock(Meter.class); + private final DoubleHistogram duration = mock(DoubleHistogram.class); + private final DoubleHistogram attempts = mock(DoubleHistogram.class); + + private final ArgumentMatcher myOp = a -> "operation.name".equals(a.getKey()) && "MyOp".equals(a.getValue()); + + @Before + public void setup() { + when(sessionSupplier.getTracer()).thenReturn(tracer); + when(sessionSupplier.getScheduler()).thenReturn(scheduler); + when(sessionSupplier.createSession(any())) + .thenReturn(CompletableFuture.completedFuture(Result.success(mock(Session.class)))); + when(tracer.startSpan(anyString(), any())).thenReturn(Span.NOOP); + when(scheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(inv -> { + inv.getArgument(0).run(); + return null; + }); + + when(meter.createHistogram(eq("ydb.client.retry.duration"), eq("s"), anyString(), + eq(Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 2d, 5d, 10d, 30d)))).thenReturn(duration); + when(meter.createHistogram(eq("ydb.client.retry.attempts"), eq("{attempt}"), anyString(), + eq(Arrays.asList(1d, 2d, 3d, 4d, 5d, 7d, 10d, 20d)))).thenReturn(attempts); + } + + private SessionRetryContext retryContext() { + return SessionRetryContext.create(sessionSupplier).maxRetries(2).withMeter(meter).build(); + } + + @Test + public void namedOperationSucceededOnFirstAttempt() { + Result result = retryContext().supplyResult("MyOp", + session -> CompletableFuture.completedFuture(Result.success(42))).join(); + + Assert.assertEquals(Integer.valueOf(42), result.getValue()); + verify(tracer).startSpan("MyOp", SpanKind.INTERNAL); + verify(tracer, never()).startSpan("ydb.RunWithRetry", SpanKind.INTERNAL); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } + + @Test + public void retriedOperationWithoutNameHasNoAttributes() { + AtomicInteger calls = new AtomicInteger(); + Status status = retryContext().supplyStatus(session -> CompletableFuture.completedFuture( + calls.getAndIncrement() == 0 ? Status.of(StatusCode.OVERLOADED) : Status.SUCCESS)).join(); + + status.expectSuccess(); + verify(tracer).startSpan("ydb.RunWithRetry", SpanKind.INTERNAL); + verify(attempts).record(2d); + verify(duration).record(anyDouble()); + verifyNoMoreInteractions(attempts, duration); + } + + @Test + public void nonRetryableFailureIsSingleAttempt() { + Status status = retryContext().supplyStatus("MyOp", SessionRetryHandler.DEFAULT, + session -> CompletableFuture.completedFuture(Status.of(StatusCode.SCHEME_ERROR))).join(); + + Assert.assertEquals(StatusCode.SCHEME_ERROR, status.getCode()); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } + + @Test + public void exhaustedSessionRetriesCountEveryAttempt() { + when(sessionSupplier.createSession(any())) + .thenReturn(CompletableFuture.completedFuture(Result.fail(Status.of(StatusCode.OVERLOADED)))); + + Status status = retryContext().supplyStatus("MyOp", session -> { + throw new AssertionError("session must not be acquired"); + }).join(); + + Assert.assertEquals(StatusCode.OVERLOADED, status.getCode()); + verify(attempts).record(eq(3d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } +}