Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
79 changes: 61 additions & 18 deletions query/src/main/java/tech/ydb/query/tools/SessionRetryContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@
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.query.QueryClient;
import tech.ydb.query.QuerySession;
import tech.ydb.table.impl.RetryMetrics;


/**
Expand All @@ -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;
Expand All @@ -61,20 +64,49 @@ 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) {
return new Builder(Objects.requireNonNull(sessionSupplier));
}

public <T> CompletableFuture<Result<T>> supplyResult(Function<QuerySession, CompletableFuture<Result<T>>> fn) {
RetryableResultTask<T> 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 <T> type of the result value
* @return future with the result of the last attempt
*/
public <T> CompletableFuture<Result<T>> supplyResult(String operationName,
Function<QuerySession, CompletableFuture<Result<T>>> fn) {
return execute(new RetryableResultTask<>(Objects.requireNonNull(operationName, "operationName is null"), fn));
}

public CompletableFuture<Status> supplyStatus(Function<QuerySession, CompletableFuture<Status>> 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<Status> supplyStatus(String operationName,
Function<QuerySession, CompletableFuture<Status>> fn) {
return execute(new RetryableStatusTask(Objects.requireNonNull(operationName, "operationName is null"), fn));
}

private static <R> CompletableFuture<R> execute(BaseRetryableTask<R> task) {
task.requestSession();
return task.getFuture();
}
Expand Down Expand Up @@ -145,14 +177,17 @@ private abstract class BaseRetryableTask<R> implements Runnable {
private final CompletableFuture<R> promise = new CompletableFuture<>();
private final AtomicInteger retryNumber = new AtomicInteger();
private final Function<QuerySession, CompletableFuture<R>> fn;
private final RetryMetrics.Operation metricsOperation;
private final Tracer tracer;
private final Span executeSpan;
private Span trySpan;

BaseRetryableTask(Function<QuerySession, CompletableFuture<R>> fn) {
BaseRetryableTask(@Nullable String operationName, Function<QuerySession, CompletableFuture<R>> 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);
Expand All @@ -178,6 +213,7 @@ public void run() {
}

public void requestSession() {
metricsOperation.onAttempt();
CompletableFuture<Result<QuerySession>> sessionFuture = createSessionWithRetrySpanParent();
if (sessionFuture.isDone() && !sessionFuture.isCompletedExceptionally()) {
// faster than subscribing on future
Expand Down Expand Up @@ -216,7 +252,7 @@ private void acceptSession(@Nonnull Result<QuerySession> sessionResult) {
Status status = toStatus(fnResult);
if (status.isSuccess()) {
if (promise.complete(fnResult)) {
finishSpans(status, null);
finishObservability(status, null);
} else {
finishOnCancel();
}
Expand All @@ -225,7 +261,7 @@ private void acceptSession(@Nonnull Result<QuerySession> sessionResult) {
}
}
} catch (Throwable unexpected) {
finishSpans(null, unexpected);
finishObservability(null, unexpected);
promise.completeExceptionally(unexpected);
}
});
Expand All @@ -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;
}
Expand All @@ -263,15 +299,15 @@ private void handleError(@Nonnull Status status, R result) {
startNextRetrySpan(next);
scheduleNext(next);
} else {
finishSpans(status, null);
finishObservability(status, null);
promise.complete(result);
}
}

private void handleException(@Nonnull Throwable ex) {
// Check retrayable execption
if (!canRetry(ex)) {
finishSpans(null, ex);
finishObservability(null, ex);
promise.completeExceptionally(ex);
return;
}
Expand All @@ -283,7 +319,7 @@ private void handleException(@Nonnull Throwable ex) {
startNextRetrySpan(next);
scheduleNext(next);
} else {
finishSpans(null, ex);
finishObservability(null, ex);
promise.completeExceptionally(ex);
}
}
Expand All @@ -307,20 +343,21 @@ 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();
Comment thread
pnv1 marked this conversation as resolved.
Resolved
}
}

/**
* RETRYABLE RESULT TASK
*/
private final class RetryableResultTask<T> extends BaseRetryableTask<Result<T>> {
RetryableResultTask(Function<QuerySession, CompletableFuture<Result<T>>> fn) {
super(fn);
RetryableResultTask(@Nullable String operationName, Function<QuerySession, CompletableFuture<Result<T>>> fn) {
super(operationName, fn);
}

@Override
Expand All @@ -338,8 +375,8 @@ Result<T> toFailedResult(Result<QuerySession> sessionResult) {
* RETRYABLE STATUS TASK
*/
private final class RetryableStatusTask extends BaseRetryableTask<Status> {
RetryableStatusTask(Function<QuerySession, CompletableFuture<Status>> fn) {
super(fn);
RetryableStatusTask(@Nullable String operationName, Function<QuerySession, CompletableFuture<Status>> fn) {
super(operationName, fn);
}

@Override
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Attr> 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.<Runnable>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<Integer> 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);
}
}
Loading
Loading