From 1115771e96b96bf65bc7912d40af358ad692fe77 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Fri, 27 Nov 2026 12:03:39 +0300 Subject: [PATCH 01/13] Add retry metrics and operation name to query SessionRetryContext Co-authored-by: sisyphus-dev-ai --- CHANGELOG.md | 1 + .../main/java/tech/ydb/query/QueryClient.java | 4 + .../tech/ydb/query/impl/QueryClientImpl.java | 7 + .../ydb/query/tools/SessionRetryContext.java | 83 ++++++++++-- .../tools/SessionRetryContextMetricsTest.java | 121 ++++++++++++++++++ 5 files changed, 206 insertions(+), 10 deletions(-) create mode 100644 query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index e82e985ea..a020bc1db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ * 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 ## 2.5.0 ## * Core: upgraded to grpc-java v1.82.4 diff --git a/query/src/main/java/tech/ydb/query/QueryClient.java b/query/src/main/java/tech/ydb/query/QueryClient.java index f9625624b..0811cd80d 100644 --- a/query/src/main/java/tech/ydb/query/QueryClient.java +++ b/query/src/main/java/tech/ydb/query/QueryClient.java @@ -44,6 +44,10 @@ default Tracer getTracer() { return NoopTracer.getInstance(); } + default Meter getMeter() { + return Meter.NOOP; + } + SessionPoolStats getSessionPoolStats(); @Override diff --git a/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java b/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java index 0994f07cd..ddf7f6b04 100644 --- a/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java +++ b/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java @@ -23,6 +23,7 @@ public class QueryClientImpl implements QueryClient { private final SessionPool pool; private final ScheduledExecutorService scheduler; private final Tracer tracer; + private final Meter meter; public QueryClientImpl(Builder builder) { String poolName = builder.sessionPoolName != null ? builder.sessionPoolName : builder.transport.getDatabase(); @@ -38,6 +39,7 @@ public QueryClientImpl(Builder builder) { ); this.scheduler = builder.transport.getScheduler(); this.tracer = builder.transport.getTracer(); + this.meter = builder.meter; } @Override @@ -55,6 +57,11 @@ public Tracer getTracer() { return tracer; } + @Override + public Meter getMeter() { + return meter; + } + public void updatePoolMaxSize(int maxSize) { pool.updateMaxSize(maxSize); } 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..3186345cd 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -1,6 +1,8 @@ package tech.ydb.query.tools; import java.time.Duration; +import java.util.Arrays; +import java.util.List; import java.util.Objects; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -21,6 +23,9 @@ import tech.ydb.core.Status; import tech.ydb.core.StatusCode; import tech.ydb.core.UnexpectedResultException; +import tech.ydb.core.metrics.Attr; +import tech.ydb.core.metrics.DoubleHistogram; +import tech.ydb.core.metrics.Meter; import tech.ydb.core.tracing.Scope; import tech.ydb.core.tracing.Span; import tech.ydb.core.tracing.SpanKind; @@ -39,6 +44,13 @@ public class SessionRetryContext { private static final String EXECUTE_WITH_RETRY_SPAN_NAME = "ydb.Try"; private static final String RETRY_BACKOFF_MS_ATTR = "ydb.retry.backoff_ms"; + 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 RETRY_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 RETRY_ATTEMPTS_BUCKETS = Arrays.asList(1d, 2d, 3d, 4d, 5d, 7d, 10d, 20d); + private final QueryClient queryClient; private final Executor executor; private final Duration sessionCreationTimeout; @@ -49,6 +61,8 @@ public class SessionRetryContext { private final int fastBackoffCeiling; private final boolean retryNotFound; private final boolean idempotent; + private final DoubleHistogram retryDuration; + private final DoubleHistogram retryAttempts; private SessionRetryContext(Builder b) { this.queryClient = b.queryClient; @@ -61,6 +75,16 @@ private SessionRetryContext(Builder b) { this.fastBackoffCeiling = b.fastBackoffCeiling; this.retryNotFound = b.retryNotFound; this.idempotent = b.idempotent; + + Meter meter = b.queryClient.getMeter(); + this.retryDuration = 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.", + RETRY_DURATION_BUCKETS); + this.retryAttempts = 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.", + RETRY_ATTEMPTS_BUCKETS); } public static Builder create(QueryClient sessionSupplier) { @@ -68,13 +92,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(); } @@ -144,15 +196,22 @@ private long backoffTimeMillis(Throwable t, int retryNumber) { private abstract class BaseRetryableTask implements Runnable { private final CompletableFuture promise = new CompletableFuture<>(); private final AtomicInteger retryNumber = new AtomicInteger(); + private final AtomicInteger attempts = new AtomicInteger(); + private final long startNanos = System.nanoTime(); private final Function> fn; + private final Attr[] metricAttrs; private final Tracer tracer; private final Span executeSpan; private Span trySpan; - BaseRetryableTask(Function> fn) { + BaseRetryableTask(@Nullable String operationName, Function> fn) { this.fn = fn; + this.metricAttrs = operationName != null + ? new Attr[]{Attr.of(OPERATION_NAME_ATTR, operationName)} + : NO_ATTRS; 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 +237,7 @@ public void run() { } public void requestSession() { + attempts.incrementAndGet(); CompletableFuture> sessionFuture = createSessionWithRetrySpanParent(); if (sessionFuture.isDone() && !sessionFuture.isCompletedExceptionally()) { // faster than subscribing on future @@ -312,6 +372,9 @@ private void finishSpans(@Nullable Status status, Throwable throwable) { finishTrySpan(status, throwable); executeSpan.setStatus(status, unwrapped); executeSpan.end(); + + retryDuration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, metricAttrs); + retryAttempts.record(attempts.get(), metricAttrs); } } @@ -319,8 +382,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 +401,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 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..82b0d8499 --- /dev/null +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -0,0 +1,121 @@ +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.getMeter()).thenReturn(meter); + 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).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); + } +} From eb73bc3ac3638586be34282b4cf9c1a300a491f2 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Fri, 27 Nov 2026 13:44:27 +0300 Subject: [PATCH 02/13] Add retry metrics and operation name to table SessionRetryContext Co-authored-by: sisyphus-dev-ai --- CHANGELOG.md | 1 + .../tech/ydb/query/impl/TableClientImpl.java | 5 + .../ydb/query/tools/SessionRetryContext.java | 41 ++---- .../tech/ydb/table/SessionRetryContext.java | 71 +++++++++-- .../java/tech/ydb/table/SessionSupplier.java | 5 + .../ydb/table/impl/PooledTableClient.java | 7 ++ .../tech/ydb/table/impl/RetryMetrics.java | 59 +++++++++ .../table/SessionRetryContextMetricsTest.java | 119 ++++++++++++++++++ 8 files changed, 264 insertions(+), 44 deletions(-) create mode 100644 table/src/main/java/tech/ydb/table/impl/RetryMetrics.java create mode 100644 table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index a020bc1db..ec8345ebf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +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/impl/TableClientImpl.java b/query/src/main/java/tech/ydb/query/impl/TableClientImpl.java index 3241565cb..70fcc73e7 100644 --- a/query/src/main/java/tech/ydb/query/impl/TableClientImpl.java +++ b/query/src/main/java/tech/ydb/query/impl/TableClientImpl.java @@ -67,6 +67,11 @@ public Tracer getTracer() { return proxy.getTracer(); } + @Override + public tech.ydb.core.metrics.Meter getMeter() { + return proxy.getMeter(); + } + @Override public SessionPoolStats sessionPoolStats() { return proxy.getSessionPoolStats(); 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 3186345cd..a8c94be3b 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -1,8 +1,6 @@ package tech.ydb.query.tools; import java.time.Duration; -import java.util.Arrays; -import java.util.List; import java.util.Objects; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -23,9 +21,6 @@ import tech.ydb.core.Status; import tech.ydb.core.StatusCode; import tech.ydb.core.UnexpectedResultException; -import tech.ydb.core.metrics.Attr; -import tech.ydb.core.metrics.DoubleHistogram; -import tech.ydb.core.metrics.Meter; import tech.ydb.core.tracing.Scope; import tech.ydb.core.tracing.Span; import tech.ydb.core.tracing.SpanKind; @@ -33,6 +28,7 @@ import tech.ydb.core.utils.FutureTools; import tech.ydb.query.QueryClient; import tech.ydb.query.QuerySession; +import tech.ydb.table.impl.RetryMetrics; /** @@ -44,13 +40,6 @@ public class SessionRetryContext { private static final String EXECUTE_WITH_RETRY_SPAN_NAME = "ydb.Try"; private static final String RETRY_BACKOFF_MS_ATTR = "ydb.retry.backoff_ms"; - 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 RETRY_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 RETRY_ATTEMPTS_BUCKETS = Arrays.asList(1d, 2d, 3d, 4d, 5d, 7d, 10d, 20d); - private final QueryClient queryClient; private final Executor executor; private final Duration sessionCreationTimeout; @@ -61,8 +50,7 @@ public class SessionRetryContext { private final int fastBackoffCeiling; private final boolean retryNotFound; private final boolean idempotent; - private final DoubleHistogram retryDuration; - private final DoubleHistogram retryAttempts; + private final RetryMetrics metrics; private SessionRetryContext(Builder b) { this.queryClient = b.queryClient; @@ -75,16 +63,7 @@ private SessionRetryContext(Builder b) { this.fastBackoffCeiling = b.fastBackoffCeiling; this.retryNotFound = b.retryNotFound; this.idempotent = b.idempotent; - - Meter meter = b.queryClient.getMeter(); - this.retryDuration = 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.", - RETRY_DURATION_BUCKETS); - this.retryAttempts = 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.", - RETRY_ATTEMPTS_BUCKETS); + this.metrics = new RetryMetrics(b.queryClient.getMeter()); } public static Builder create(QueryClient sessionSupplier) { @@ -196,19 +175,15 @@ private long backoffTimeMillis(Throwable t, int retryNumber) { private abstract class BaseRetryableTask implements Runnable { private final CompletableFuture promise = new CompletableFuture<>(); private final AtomicInteger retryNumber = new AtomicInteger(); - private final AtomicInteger attempts = new AtomicInteger(); - private final long startNanos = System.nanoTime(); private final Function> fn; - private final Attr[] metricAttrs; + private final RetryMetrics.Operation metricsOperation; private final Tracer tracer; private final Span executeSpan; private Span trySpan; BaseRetryableTask(@Nullable String operationName, Function> fn) { this.fn = fn; - this.metricAttrs = operationName != null - ? new Attr[]{Attr.of(OPERATION_NAME_ATTR, operationName)} - : NO_ATTRS; + this.metricsOperation = metrics.startOperation(operationName); this.tracer = queryClient.getTracer(); this.executeSpan = tracer.startSpan(operationName != null ? operationName : EXECUTE_SPAN_NAME, SpanKind.INTERNAL); @@ -237,7 +212,7 @@ public void run() { } public void requestSession() { - attempts.incrementAndGet(); + metricsOperation.onAttempt(); CompletableFuture> sessionFuture = createSessionWithRetrySpanParent(); if (sessionFuture.isDone() && !sessionFuture.isCompletedExceptionally()) { // faster than subscribing on future @@ -372,9 +347,7 @@ private void finishSpans(@Nullable Status status, Throwable throwable) { finishTrySpan(status, throwable); executeSpan.setStatus(status, unwrapped); executeSpan.end(); - - retryDuration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, metricAttrs); - retryAttempts.record(attempts.get(), metricAttrs); + metricsOperation.finish(); } } diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index 9593c77fc..355bfdc3b 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -27,6 +27,7 @@ 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 +49,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 +62,7 @@ private SessionRetryContext(Builder b) { this.fastBackoffCeiling = b.fastBackoffCeiling; this.retryNotFound = b.retryNotFound; this.idempotent = b.idempotent; + this.metrics = new RetryMetrics(b.sessionSupplier.getMeter()); } public static Builder create(SessionSupplier sessionSupplier) { @@ -76,14 +79,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 +199,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 +242,7 @@ public void run() { } public void requestSession() { + metricsOperation.onAttempt(); CompletableFuture> sessionFuture = createSessionWithRetrySpanParent(); if (sessionFuture.isDone() && !sessionFuture.isCompletedExceptionally()) { // faster than subscribing on future @@ -338,6 +386,7 @@ private void finishSpans(@Nullable Status status, Throwable throwable) { finishTrySpan(status, throwable); executeSpan.setStatus(status, unwrapped); executeSpan.end(); + metricsOperation.finish(); } } @@ -345,8 +394,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 +414,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 diff --git a/table/src/main/java/tech/ydb/table/SessionSupplier.java b/table/src/main/java/tech/ydb/table/SessionSupplier.java index dbec11281..3d21a90a2 100644 --- a/table/src/main/java/tech/ydb/table/SessionSupplier.java +++ b/table/src/main/java/tech/ydb/table/SessionSupplier.java @@ -5,6 +5,7 @@ import java.util.concurrent.ScheduledExecutorService; import tech.ydb.core.Result; +import tech.ydb.core.metrics.Meter; import tech.ydb.core.tracing.NoopTracer; import tech.ydb.core.tracing.Tracer; @@ -31,4 +32,8 @@ public interface SessionSupplier { default Tracer getTracer() { return NoopTracer.getInstance(); } + + default Meter getMeter() { + return Meter.NOOP; + } } diff --git a/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java b/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java index 38834344b..1b1460bf0 100644 --- a/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java +++ b/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java @@ -22,9 +22,11 @@ public class PooledTableClient implements TableClient { private final TableRpc tableRpc; private final SessionPool pool; + private final Meter meter; protected PooledTableClient(Builder builder) { this.tableRpc = builder.tableRpc; + this.meter = builder.meter; this.pool = new SessionPool( Clock.systemUTC(), builder.tableRpc, @@ -45,6 +47,11 @@ public ScheduledExecutorService getScheduler() { return tableRpc.getScheduler(); } + @Override + public Meter getMeter() { + return meter; + } + @Override public void close() { pool.close(); 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..878b52c05 --- /dev/null +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -0,0 +1,59 @@ +package tech.ydb.table.impl; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.annotation.Nullable; + +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) { + 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 final AtomicInteger attemptCount = new AtomicInteger(); + 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.incrementAndGet(); + } + + public void finish() { + duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); + attempts.record(attemptCount.get(), 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..e5479bc3c --- /dev/null +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -0,0 +1,119 @@ +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.getMeter()).thenReturn(meter); + 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).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); + } +} From 91300df7ead8c83f6036d7e2bf5df560b6be2a9a Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Fri, 27 Nov 2026 13:53:02 +0300 Subject: [PATCH 03/13] Pass Meter to SessionRetryContext through its builder Co-authored-by: sisyphus-dev-ai --- query/src/main/java/tech/ydb/query/QueryClient.java | 4 ---- .../main/java/tech/ydb/query/impl/QueryClientImpl.java | 7 ------- .../main/java/tech/ydb/query/impl/TableClientImpl.java | 5 ----- .../java/tech/ydb/query/tools/SessionRetryContext.java | 9 ++++++++- .../ydb/query/tools/SessionRetryContextMetricsTest.java | 3 +-- .../main/java/tech/ydb/table/SessionRetryContext.java | 9 ++++++++- table/src/main/java/tech/ydb/table/SessionSupplier.java | 5 ----- .../main/java/tech/ydb/table/impl/PooledTableClient.java | 7 ------- .../tech/ydb/table/SessionRetryContextMetricsTest.java | 3 +-- 9 files changed, 18 insertions(+), 34 deletions(-) diff --git a/query/src/main/java/tech/ydb/query/QueryClient.java b/query/src/main/java/tech/ydb/query/QueryClient.java index 0811cd80d..f9625624b 100644 --- a/query/src/main/java/tech/ydb/query/QueryClient.java +++ b/query/src/main/java/tech/ydb/query/QueryClient.java @@ -44,10 +44,6 @@ default Tracer getTracer() { return NoopTracer.getInstance(); } - default Meter getMeter() { - return Meter.NOOP; - } - SessionPoolStats getSessionPoolStats(); @Override diff --git a/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java b/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java index ddf7f6b04..0994f07cd 100644 --- a/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java +++ b/query/src/main/java/tech/ydb/query/impl/QueryClientImpl.java @@ -23,7 +23,6 @@ public class QueryClientImpl implements QueryClient { private final SessionPool pool; private final ScheduledExecutorService scheduler; private final Tracer tracer; - private final Meter meter; public QueryClientImpl(Builder builder) { String poolName = builder.sessionPoolName != null ? builder.sessionPoolName : builder.transport.getDatabase(); @@ -39,7 +38,6 @@ public QueryClientImpl(Builder builder) { ); this.scheduler = builder.transport.getScheduler(); this.tracer = builder.transport.getTracer(); - this.meter = builder.meter; } @Override @@ -57,11 +55,6 @@ public Tracer getTracer() { return tracer; } - @Override - public Meter getMeter() { - return meter; - } - public void updatePoolMaxSize(int maxSize) { pool.updateMaxSize(maxSize); } diff --git a/query/src/main/java/tech/ydb/query/impl/TableClientImpl.java b/query/src/main/java/tech/ydb/query/impl/TableClientImpl.java index 70fcc73e7..3241565cb 100644 --- a/query/src/main/java/tech/ydb/query/impl/TableClientImpl.java +++ b/query/src/main/java/tech/ydb/query/impl/TableClientImpl.java @@ -67,11 +67,6 @@ public Tracer getTracer() { return proxy.getTracer(); } - @Override - public tech.ydb.core.metrics.Meter getMeter() { - return proxy.getMeter(); - } - @Override public SessionPoolStats sessionPoolStats() { return proxy.getSessionPoolStats(); 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 a8c94be3b..749fc1a13 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; @@ -63,7 +64,7 @@ private SessionRetryContext(Builder b) { this.fastBackoffCeiling = b.fastBackoffCeiling; this.retryNotFound = b.retryNotFound; this.idempotent = b.idempotent; - this.metrics = new RetryMetrics(b.queryClient.getMeter()); + this.metrics = new RetryMetrics(b.meter); } public static Builder create(QueryClient sessionSupplier) { @@ -404,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; @@ -456,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 index 82b0d8499..5f36b86e5 100644 --- a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -46,7 +46,6 @@ public class SessionRetryContextMetricsTest { @Before public void setup() { - when(queryClient.getMeter()).thenReturn(meter); when(queryClient.getTracer()).thenReturn(tracer); when(queryClient.getScheduler()).thenReturn(scheduler); when(queryClient.createSession(any())) @@ -64,7 +63,7 @@ public void setup() { } private SessionRetryContext retryContext() { - return SessionRetryContext.create(queryClient).maxRetries(2).build(); + return SessionRetryContext.create(queryClient).maxRetries(2).withMeter(meter).build(); } @Test diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index 355bfdc3b..cf5643314 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -22,6 +22,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; @@ -62,7 +63,7 @@ private SessionRetryContext(Builder b) { this.fastBackoffCeiling = b.fastBackoffCeiling; this.retryNotFound = b.retryNotFound; this.idempotent = b.idempotent; - this.metrics = new RetryMetrics(b.sessionSupplier.getMeter()); + this.metrics = new RetryMetrics(b.meter); } public static Builder create(SessionSupplier sessionSupplier) { @@ -445,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; @@ -497,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/SessionSupplier.java b/table/src/main/java/tech/ydb/table/SessionSupplier.java index 3d21a90a2..dbec11281 100644 --- a/table/src/main/java/tech/ydb/table/SessionSupplier.java +++ b/table/src/main/java/tech/ydb/table/SessionSupplier.java @@ -5,7 +5,6 @@ import java.util.concurrent.ScheduledExecutorService; import tech.ydb.core.Result; -import tech.ydb.core.metrics.Meter; import tech.ydb.core.tracing.NoopTracer; import tech.ydb.core.tracing.Tracer; @@ -32,8 +31,4 @@ public interface SessionSupplier { default Tracer getTracer() { return NoopTracer.getInstance(); } - - default Meter getMeter() { - return Meter.NOOP; - } } diff --git a/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java b/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java index 1b1460bf0..38834344b 100644 --- a/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java +++ b/table/src/main/java/tech/ydb/table/impl/PooledTableClient.java @@ -22,11 +22,9 @@ public class PooledTableClient implements TableClient { private final TableRpc tableRpc; private final SessionPool pool; - private final Meter meter; protected PooledTableClient(Builder builder) { this.tableRpc = builder.tableRpc; - this.meter = builder.meter; this.pool = new SessionPool( Clock.systemUTC(), builder.tableRpc, @@ -47,11 +45,6 @@ public ScheduledExecutorService getScheduler() { return tableRpc.getScheduler(); } - @Override - public Meter getMeter() { - return meter; - } - @Override public void close() { pool.close(); diff --git a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java index e5479bc3c..5d0e76352 100644 --- a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -44,7 +44,6 @@ public class SessionRetryContextMetricsTest { @Before public void setup() { - when(sessionSupplier.getMeter()).thenReturn(meter); when(sessionSupplier.getTracer()).thenReturn(tracer); when(sessionSupplier.getScheduler()).thenReturn(scheduler); when(sessionSupplier.createSession(any())) @@ -62,7 +61,7 @@ public void setup() { } private SessionRetryContext retryContext() { - return SessionRetryContext.create(sessionSupplier).maxRetries(2).build(); + return SessionRetryContext.create(sessionSupplier).maxRetries(2).withMeter(meter).build(); } @Test From 54fbbb03ee497b08c2d73108a505cbc8783254ad Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Mon, 30 Nov 2026 17:00:49 +0300 Subject: [PATCH 04/13] Record retry metrics before completing the operation future Co-authored-by: sisyphus-dev-ai --- .../ydb/query/tools/SessionRetryContext.java | 1 + .../tools/SessionRetryContextMetricsTest.java | 16 ++++++++++++++++ .../java/tech/ydb/table/SessionRetryContext.java | 1 + .../java/tech/ydb/table/impl/RetryMetrics.java | 5 +++++ .../table/SessionRetryContextMetricsTest.java | 16 ++++++++++++++++ 5 files changed, 39 insertions(+) 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 749fc1a13..079629dda 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -251,6 +251,7 @@ private void acceptSession(@Nonnull Result sessionResult) { Status status = toStatus(fnResult); if (status.isSuccess()) { + metricsOperation.finish(); if (promise.complete(fnResult)) { finishSpans(status, null); } else { diff --git a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java index 5f36b86e5..2be88fe98 100644 --- a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -29,6 +29,7 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockingDetails; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -103,6 +104,21 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } + @Test + public void metricsAreRecordedBeforeUserCallbacks() { + CompletableFuture response = new CompletableFuture<>(); + AtomicInteger recordedBeforeCallback = new AtomicInteger(-1); + retryContext().supplyStatus("MyOp", session -> response) + .thenRun(() -> recordedBeforeCallback.set(mockingDetails(duration).getInvocations().size())); + + response.complete(Status.SUCCESS); + + Assert.assertEquals(1, recordedBeforeCallback.get()); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } + @Test public void exhaustedSessionRetriesCountEveryAttempt() { when(queryClient.createSession(any())) diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index cf5643314..91b951d24 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -281,6 +281,7 @@ private void acceptSession(@Nonnull Result sessionResult) { Status status = toStatus(fnResult); if (status.isSuccess()) { + metricsOperation.finish(); if (promise.complete(fnResult)) { handler.onSuccess(SessionRetryContext.this, retryNumber.get(), ms()); finishSpans(status, null); diff --git a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java index 878b52c05..96989dc2a 100644 --- a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -2,6 +2,7 @@ import java.util.Arrays; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; @@ -39,6 +40,7 @@ public Operation startOperation(@Nullable String operationName) { public final class Operation { private final long startNanos = System.nanoTime(); private final AtomicInteger attemptCount = new AtomicInteger(); + private final AtomicBoolean finished = new AtomicBoolean(); private final Attr[] attrs; private Operation(@Nullable String operationName) { @@ -52,6 +54,9 @@ public void onAttempt() { } public void finish() { + if (!finished.compareAndSet(false, true)) { + return; + } duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); attempts.record(attemptCount.get(), attrs); } diff --git a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java index 5d0e76352..0151fbd63 100644 --- a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -27,6 +27,7 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockingDetails; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -101,6 +102,21 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } + @Test + public void metricsAreRecordedBeforeUserCallbacks() { + CompletableFuture response = new CompletableFuture<>(); + AtomicInteger recordedBeforeCallback = new AtomicInteger(-1); + retryContext().supplyStatus("MyOp", session -> response) + .thenRun(() -> recordedBeforeCallback.set(mockingDetails(duration).getInvocations().size())); + + response.complete(Status.SUCCESS); + + Assert.assertEquals(1, recordedBeforeCallback.get()); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + verifyNoMoreInteractions(attempts, duration); + } + @Test public void exhaustedSessionRetriesCountEveryAttempt() { when(sessionSupplier.createSession(any())) From 403f5113d8e779db5e54dff19e77c0a8a94a788b Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Mon, 30 Nov 2026 17:00:49 +0300 Subject: [PATCH 05/13] Report metrics usage from SessionRetryContext meter Co-authored-by: sisyphus-dev-ai --- table/src/main/java/tech/ydb/table/impl/RetryMetrics.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java index 96989dc2a..9ae465a9d 100644 --- a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -7,6 +7,7 @@ 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; @@ -23,6 +24,7 @@ public final class RetryMetrics { 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.", From 1263e426ea53a66b08d08aaf53f53911dfcf1027 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 11:28:05 +0300 Subject: [PATCH 06/13] Ignore Meter failures when recording retry metrics Co-authored-by: sisyphus-dev-ai --- .../tools/SessionRetryContextMetricsTest.java | 31 +++++++++++++++++++ .../tech/ydb/table/impl/RetryMetrics.java | 12 +++++-- .../table/SessionRetryContextMetricsTest.java | 31 +++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java index 2be88fe98..3e42ffa06 100644 --- a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -104,6 +104,37 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } + @Test + public void brokenHistogramDoesNotChangeSuccessfulResult() { + breakDurationHistogram(); + Status status = retryContext().supplyStatus("MyOp", + session -> CompletableFuture.completedFuture(Status.SUCCESS)).join(); + + status.expectSuccess(); + } + + @Test + public void brokenHistogramDoesNotHangSessionFailure() { + breakDurationHistogram(); + CompletableFuture> session = new CompletableFuture<>(); + when(queryClient.createSession(any())).thenReturn(session); + CompletableFuture result = retryContext().supplyStatus("MyOp", s -> { + throw new AssertionError("session must not be acquired"); + }); + + session.complete(Result.fail(Status.of(StatusCode.SCHEME_ERROR))); + + Assert.assertTrue(result.isDone()); + Assert.assertEquals(StatusCode.SCHEME_ERROR, result.join().getCode()); + } + + private void breakDurationHistogram() { + when(meter.createHistogram(eq("ydb.client.retry.duration"), any(), any(), any())) + .thenReturn((value, attrs) -> { + throw new IllegalStateException("broken meter"); + }); + } + @Test public void metricsAreRecordedBeforeUserCallbacks() { CompletableFuture response = new CompletableFuture<>(); diff --git a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java index 9ae465a9d..2be856e88 100644 --- a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -7,12 +7,16 @@ import javax.annotation.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + 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 Logger logger = LoggerFactory.getLogger(RetryMetrics.class); 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; @@ -59,8 +63,12 @@ public void finish() { if (!finished.compareAndSet(false, true)) { return; } - duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); - attempts.record(attemptCount.get(), attrs); + try { + duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); + attempts.record(attemptCount.get(), attrs); + } catch (RuntimeException ex) { + logger.warn("Failed to record retry metrics", ex); + } } } } diff --git a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java index 0151fbd63..f1610ada9 100644 --- a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -102,6 +102,37 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } + @Test + public void brokenHistogramDoesNotChangeSuccessfulResult() { + breakDurationHistogram(); + Status status = retryContext().supplyStatus("MyOp", + session -> CompletableFuture.completedFuture(Status.SUCCESS)).join(); + + status.expectSuccess(); + } + + @Test + public void brokenHistogramDoesNotHangSessionFailure() { + breakDurationHistogram(); + CompletableFuture> session = new CompletableFuture<>(); + when(sessionSupplier.createSession(any())).thenReturn(session); + CompletableFuture result = retryContext().supplyStatus("MyOp", s -> { + throw new AssertionError("session must not be acquired"); + }); + + session.complete(Result.fail(Status.of(StatusCode.SCHEME_ERROR))); + + Assert.assertTrue(result.isDone()); + Assert.assertEquals(StatusCode.SCHEME_ERROR, result.join().getCode()); + } + + private void breakDurationHistogram() { + when(meter.createHistogram(eq("ydb.client.retry.duration"), any(), any(), any())) + .thenReturn((value, attrs) -> { + throw new IllegalStateException("broken meter"); + }); + } + @Test public void metricsAreRecordedBeforeUserCallbacks() { CompletableFuture response = new CompletableFuture<>(); From 819d347aed40c70d9325066117eb523d47560681 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 11:29:09 +0300 Subject: [PATCH 07/13] Record retry metrics when the operation is cancelled Co-authored-by: sisyphus-dev-ai --- .../tech/ydb/query/tools/SessionRetryContext.java | 5 +++++ .../query/tools/SessionRetryContextMetricsTest.java | 13 +++++++++++++ .../java/tech/ydb/table/SessionRetryContext.java | 5 +++++ .../ydb/table/SessionRetryContextMetricsTest.java | 13 +++++++++++++ 4 files changed, 36 insertions(+) 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 079629dda..616211c8f 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -185,6 +185,11 @@ private abstract class BaseRetryableTask implements Runnable { BaseRetryableTask(@Nullable String operationName, Function> fn) { this.fn = fn; this.metricsOperation = metrics.startOperation(operationName); + promise.whenComplete((result, error) -> { + if (promise.isCancelled()) { + metricsOperation.finish(); + } + }); this.tracer = queryClient.getTracer(); this.executeSpan = tracer.startSpan(operationName != null ? operationName : EXECUTE_SPAN_NAME, SpanKind.INTERNAL); diff --git a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java index 3e42ffa06..8b154b8d4 100644 --- a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -104,6 +104,19 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } + @Test + public void cancelledOperationIsRecordedOnCancel() { + CompletableFuture response = new CompletableFuture<>(); + CompletableFuture result = retryContext().supplyStatus("MyOp", session -> response); + + result.cancel(false); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + + response.complete(Status.SUCCESS); + verifyNoMoreInteractions(attempts, duration); + } + @Test public void brokenHistogramDoesNotChangeSuccessfulResult() { breakDurationHistogram(); diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index 91b951d24..0fbb5cb0e 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -210,6 +210,11 @@ private abstract class BaseRetryableTask implements Runnable { this.fn = fn; this.handler = h; this.metricsOperation = metrics.startOperation(operationName); + promise.whenComplete((result, error) -> { + if (promise.isCancelled()) { + metricsOperation.finish(); + } + }); this.tracer = sessionSupplier.getTracer(); this.executeSpan = tracer.startSpan(operationName != null ? operationName : EXECUTE_SPAN_NAME, SpanKind.INTERNAL); diff --git a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java index f1610ada9..53c3d0d5f 100644 --- a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -102,6 +102,19 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } + @Test + public void cancelledOperationIsRecordedOnCancel() { + CompletableFuture response = new CompletableFuture<>(); + CompletableFuture result = retryContext().supplyStatus("MyOp", session -> response); + + result.cancel(false); + verify(attempts).record(eq(1d), argThat(myOp)); + verify(duration).record(anyDouble(), argThat(myOp)); + + response.complete(Status.SUCCESS); + verifyNoMoreInteractions(attempts, duration); + } + @Test public void brokenHistogramDoesNotChangeSuccessfulResult() { breakDurationHistogram(); From b93dddba587cc7f16aa7fefee973ec09e149bba0 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 11:40:09 +0300 Subject: [PATCH 08/13] Revert "Record retry metrics when the operation is cancelled" This reverts commit 819d347aed40c70d9325066117eb523d47560681. --- .../tech/ydb/query/tools/SessionRetryContext.java | 5 ----- .../query/tools/SessionRetryContextMetricsTest.java | 13 ------------- .../java/tech/ydb/table/SessionRetryContext.java | 5 ----- .../ydb/table/SessionRetryContextMetricsTest.java | 13 ------------- 4 files changed, 36 deletions(-) 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 616211c8f..079629dda 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -185,11 +185,6 @@ private abstract class BaseRetryableTask implements Runnable { BaseRetryableTask(@Nullable String operationName, Function> fn) { this.fn = fn; this.metricsOperation = metrics.startOperation(operationName); - promise.whenComplete((result, error) -> { - if (promise.isCancelled()) { - metricsOperation.finish(); - } - }); this.tracer = queryClient.getTracer(); this.executeSpan = tracer.startSpan(operationName != null ? operationName : EXECUTE_SPAN_NAME, SpanKind.INTERNAL); diff --git a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java index 8b154b8d4..3e42ffa06 100644 --- a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -104,19 +104,6 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } - @Test - public void cancelledOperationIsRecordedOnCancel() { - CompletableFuture response = new CompletableFuture<>(); - CompletableFuture result = retryContext().supplyStatus("MyOp", session -> response); - - result.cancel(false); - verify(attempts).record(eq(1d), argThat(myOp)); - verify(duration).record(anyDouble(), argThat(myOp)); - - response.complete(Status.SUCCESS); - verifyNoMoreInteractions(attempts, duration); - } - @Test public void brokenHistogramDoesNotChangeSuccessfulResult() { breakDurationHistogram(); diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index 0fbb5cb0e..91b951d24 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -210,11 +210,6 @@ private abstract class BaseRetryableTask implements Runnable { this.fn = fn; this.handler = h; this.metricsOperation = metrics.startOperation(operationName); - promise.whenComplete((result, error) -> { - if (promise.isCancelled()) { - metricsOperation.finish(); - } - }); this.tracer = sessionSupplier.getTracer(); this.executeSpan = tracer.startSpan(operationName != null ? operationName : EXECUTE_SPAN_NAME, SpanKind.INTERNAL); diff --git a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java index 53c3d0d5f..f1610ada9 100644 --- a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -102,19 +102,6 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } - @Test - public void cancelledOperationIsRecordedOnCancel() { - CompletableFuture response = new CompletableFuture<>(); - CompletableFuture result = retryContext().supplyStatus("MyOp", session -> response); - - result.cancel(false); - verify(attempts).record(eq(1d), argThat(myOp)); - verify(duration).record(anyDouble(), argThat(myOp)); - - response.complete(Status.SUCCESS); - verifyNoMoreInteractions(attempts, duration); - } - @Test public void brokenHistogramDoesNotChangeSuccessfulResult() { breakDurationHistogram(); From 7df9209bfda3c8ed01bc349763c048e60d44375d Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 12:09:57 +0300 Subject: [PATCH 09/13] Use plain fields in RetryMetrics.Operation Co-authored-by: sisyphus-dev-ai --- .../main/java/tech/ydb/table/impl/RetryMetrics.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java index 2be856e88..62b4589a6 100644 --- a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -2,8 +2,6 @@ import java.util.Arrays; import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; @@ -45,8 +43,8 @@ public Operation startOperation(@Nullable String operationName) { public final class Operation { private final long startNanos = System.nanoTime(); - private final AtomicInteger attemptCount = new AtomicInteger(); - private final AtomicBoolean finished = new AtomicBoolean(); + private int attemptCount; + private boolean finished; private final Attr[] attrs; private Operation(@Nullable String operationName) { @@ -56,16 +54,17 @@ private Operation(@Nullable String operationName) { } public void onAttempt() { - attemptCount.incrementAndGet(); + attemptCount++; } public void finish() { - if (!finished.compareAndSet(false, true)) { + if (finished) { return; } + finished = true; try { duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); - attempts.record(attemptCount.get(), attrs); + attempts.record(attemptCount, attrs); } catch (RuntimeException ex) { logger.warn("Failed to record retry metrics", ex); } From 0330ece37933bd10a54c1e0afa30524f5e7df53c Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 12:41:04 +0300 Subject: [PATCH 10/13] Do not catch Meter exceptions in RetryMetrics Co-authored-by: sisyphus-dev-ai --- .../tools/SessionRetryContextMetricsTest.java | 31 ------------------- .../tech/ydb/table/impl/RetryMetrics.java | 12 ++----- .../table/SessionRetryContextMetricsTest.java | 31 ------------------- 3 files changed, 2 insertions(+), 72 deletions(-) diff --git a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java index 3e42ffa06..2be88fe98 100644 --- a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -104,37 +104,6 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } - @Test - public void brokenHistogramDoesNotChangeSuccessfulResult() { - breakDurationHistogram(); - Status status = retryContext().supplyStatus("MyOp", - session -> CompletableFuture.completedFuture(Status.SUCCESS)).join(); - - status.expectSuccess(); - } - - @Test - public void brokenHistogramDoesNotHangSessionFailure() { - breakDurationHistogram(); - CompletableFuture> session = new CompletableFuture<>(); - when(queryClient.createSession(any())).thenReturn(session); - CompletableFuture result = retryContext().supplyStatus("MyOp", s -> { - throw new AssertionError("session must not be acquired"); - }); - - session.complete(Result.fail(Status.of(StatusCode.SCHEME_ERROR))); - - Assert.assertTrue(result.isDone()); - Assert.assertEquals(StatusCode.SCHEME_ERROR, result.join().getCode()); - } - - private void breakDurationHistogram() { - when(meter.createHistogram(eq("ydb.client.retry.duration"), any(), any(), any())) - .thenReturn((value, attrs) -> { - throw new IllegalStateException("broken meter"); - }); - } - @Test public void metricsAreRecordedBeforeUserCallbacks() { CompletableFuture response = new CompletableFuture<>(); diff --git a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java index 62b4589a6..658a7867d 100644 --- a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -5,16 +5,12 @@ import javax.annotation.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 Logger logger = LoggerFactory.getLogger(RetryMetrics.class); 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; @@ -62,12 +58,8 @@ public void finish() { return; } finished = true; - try { - duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); - attempts.record(attemptCount, attrs); - } catch (RuntimeException ex) { - logger.warn("Failed to record retry metrics", ex); - } + 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 index f1610ada9..0151fbd63 100644 --- a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -102,37 +102,6 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } - @Test - public void brokenHistogramDoesNotChangeSuccessfulResult() { - breakDurationHistogram(); - Status status = retryContext().supplyStatus("MyOp", - session -> CompletableFuture.completedFuture(Status.SUCCESS)).join(); - - status.expectSuccess(); - } - - @Test - public void brokenHistogramDoesNotHangSessionFailure() { - breakDurationHistogram(); - CompletableFuture> session = new CompletableFuture<>(); - when(sessionSupplier.createSession(any())).thenReturn(session); - CompletableFuture result = retryContext().supplyStatus("MyOp", s -> { - throw new AssertionError("session must not be acquired"); - }); - - session.complete(Result.fail(Status.of(StatusCode.SCHEME_ERROR))); - - Assert.assertTrue(result.isDone()); - Assert.assertEquals(StatusCode.SCHEME_ERROR, result.join().getCode()); - } - - private void breakDurationHistogram() { - when(meter.createHistogram(eq("ydb.client.retry.duration"), any(), any(), any())) - .thenReturn((value, attrs) -> { - throw new IllegalStateException("broken meter"); - }); - } - @Test public void metricsAreRecordedBeforeUserCallbacks() { CompletableFuture response = new CompletableFuture<>(); From b93123bc1036846791ead1fd961587e9b97389c7 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 15:31:06 +0300 Subject: [PATCH 11/13] Record retry metrics only when finishing spans Co-authored-by: sisyphus-dev-ai --- .../ydb/query/tools/SessionRetryContext.java | 1 - .../tools/SessionRetryContextMetricsTest.java | 16 ---------------- .../java/tech/ydb/table/SessionRetryContext.java | 1 - .../table/SessionRetryContextMetricsTest.java | 16 ---------------- 4 files changed, 34 deletions(-) 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 079629dda..749fc1a13 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -251,7 +251,6 @@ private void acceptSession(@Nonnull Result sessionResult) { Status status = toStatus(fnResult); if (status.isSuccess()) { - metricsOperation.finish(); if (promise.complete(fnResult)) { finishSpans(status, null); } else { diff --git a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java index 2be88fe98..5f36b86e5 100644 --- a/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/tools/SessionRetryContextMetricsTest.java @@ -29,7 +29,6 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockingDetails; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -104,21 +103,6 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } - @Test - public void metricsAreRecordedBeforeUserCallbacks() { - CompletableFuture response = new CompletableFuture<>(); - AtomicInteger recordedBeforeCallback = new AtomicInteger(-1); - retryContext().supplyStatus("MyOp", session -> response) - .thenRun(() -> recordedBeforeCallback.set(mockingDetails(duration).getInvocations().size())); - - response.complete(Status.SUCCESS); - - Assert.assertEquals(1, recordedBeforeCallback.get()); - verify(attempts).record(eq(1d), argThat(myOp)); - verify(duration).record(anyDouble(), argThat(myOp)); - verifyNoMoreInteractions(attempts, duration); - } - @Test public void exhaustedSessionRetriesCountEveryAttempt() { when(queryClient.createSession(any())) diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index 91b951d24..cf5643314 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -281,7 +281,6 @@ private void acceptSession(@Nonnull Result sessionResult) { Status status = toStatus(fnResult); if (status.isSuccess()) { - metricsOperation.finish(); if (promise.complete(fnResult)) { handler.onSuccess(SessionRetryContext.this, retryNumber.get(), ms()); finishSpans(status, null); diff --git a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java index 0151fbd63..5d0e76352 100644 --- a/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/SessionRetryContextMetricsTest.java @@ -27,7 +27,6 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockingDetails; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -102,21 +101,6 @@ public void nonRetryableFailureIsSingleAttempt() { verifyNoMoreInteractions(attempts, duration); } - @Test - public void metricsAreRecordedBeforeUserCallbacks() { - CompletableFuture response = new CompletableFuture<>(); - AtomicInteger recordedBeforeCallback = new AtomicInteger(-1); - retryContext().supplyStatus("MyOp", session -> response) - .thenRun(() -> recordedBeforeCallback.set(mockingDetails(duration).getInvocations().size())); - - response.complete(Status.SUCCESS); - - Assert.assertEquals(1, recordedBeforeCallback.get()); - verify(attempts).record(eq(1d), argThat(myOp)); - verify(duration).record(anyDouble(), argThat(myOp)); - verifyNoMoreInteractions(attempts, duration); - } - @Test public void exhaustedSessionRetriesCountEveryAttempt() { when(sessionSupplier.createSession(any())) From a797c8b8d86340ebab802612b34a08b9af4fcf81 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 15:32:01 +0300 Subject: [PATCH 12/13] Remove finished flag from RetryMetrics.Operation Co-authored-by: sisyphus-dev-ai --- table/src/main/java/tech/ydb/table/impl/RetryMetrics.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java index 658a7867d..f782bd73e 100644 --- a/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/RetryMetrics.java @@ -40,7 +40,6 @@ public Operation startOperation(@Nullable String operationName) { public final class Operation { private final long startNanos = System.nanoTime(); private int attemptCount; - private boolean finished; private final Attr[] attrs; private Operation(@Nullable String operationName) { @@ -54,10 +53,6 @@ public void onAttempt() { } public void finish() { - if (finished) { - return; - } - finished = true; duration.record((System.nanoTime() - startNanos) / NANOS_IN_SECOND, attrs); attempts.record(attemptCount, attrs); } From 0a99e19e05d5e032b73be70af336e888da0de487 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Tue, 1 Dec 2026 15:41:49 +0300 Subject: [PATCH 13/13] Rename finishSpans to finishObservability Co-authored-by: sisyphus-dev-ai --- .../ydb/query/tools/SessionRetryContext.java | 16 ++++++++-------- .../java/tech/ydb/table/SessionRetryContext.java | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) 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 749fc1a13..e90f052f7 100644 --- a/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java +++ b/query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java @@ -252,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(); } @@ -261,7 +261,7 @@ private void acceptSession(@Nonnull Result sessionResult) { } } } catch (Throwable unexpected) { - finishSpans(null, unexpected); + finishObservability(null, unexpected); promise.completeExceptionally(unexpected); } }); @@ -281,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; } @@ -299,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); } } @@ -307,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; } @@ -319,7 +319,7 @@ private void handleException(@Nonnull Throwable ex) { startNextRetrySpan(next); scheduleNext(next); } else { - finishSpans(null, ex); + finishObservability(null, ex); promise.completeExceptionally(ex); } } @@ -343,7 +343,7 @@ 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); diff --git a/table/src/main/java/tech/ydb/table/SessionRetryContext.java b/table/src/main/java/tech/ydb/table/SessionRetryContext.java index cf5643314..926e7d8d3 100644 --- a/table/src/main/java/tech/ydb/table/SessionRetryContext.java +++ b/table/src/main/java/tech/ydb/table/SessionRetryContext.java @@ -283,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(); @@ -294,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); } }); @@ -314,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; } @@ -335,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); } } @@ -344,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; } @@ -358,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); } } @@ -382,7 +382,7 @@ 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);