From bdf3c78615f6c7481f4bd40732cdf373cd0fc315 Mon Sep 17 00:00:00 2001 From: lebmax Date: Tue, 24 Nov 2026 19:20:47 +0300 Subject: [PATCH 01/29] Fix canceled session pool waiters and add acquire metrics --- CHANGELOG.md | 2 + .../tech/ydb/core/impl/Observability.java | 2 +- .../tech/ydb/core/impl/ObservabilityTest.java | 6 +- .../java/tech/ydb/query/impl/SessionPool.java | 25 ++++++- .../tech/ydb/query/impl/PoolMetricsTest.java | 38 +++++++++- .../tech/ydb/table/impl/pool/PoolMetrics.java | 28 +++++++ .../tech/ydb/table/impl/pool/SessionPool.java | 27 +++++++ .../ydb/table/impl/pool/WaitingQueue.java | 28 +++++++ .../ydb/table/impl/pool/PoolMetricsTest.java | 44 ++++++++++- .../ydb/table/impl/pool/SessionPoolTest.java | 50 +++++++++++++ .../ydb/table/impl/pool/WaitingQueueTest.java | 73 ++++++++++++++++++- 11 files changed, 312 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fe577180..129c6ade1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,6 @@ * Core: added opt-in PRIMARY/PROMOTED Bridge pile preference with synchronized-pile fallback +* Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately +* Table/Query: added session-pool acquire duration and bounded failure-reason metrics ## 2.5.0 ## * Core: upgraded to grpc-java v1.82.4 diff --git a/core/src/main/java/tech/ydb/core/impl/Observability.java b/core/src/main/java/tech/ydb/core/impl/Observability.java index 3eba77589..ea94778c7 100644 --- a/core/src/main/java/tech/ydb/core/impl/Observability.java +++ b/core/src/main/java/tech/ydb/core/impl/Observability.java @@ -12,7 +12,7 @@ */ public final class Observability { public static final String TRACING_CHAIN = ";ydb-sdk-tracing/0.1.0"; - public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.3.0"; + public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.4.0"; private static volatile boolean isTracingEnabled = false; private static volatile boolean isMetricsEnabled = false; diff --git a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java index b6fc8dec4..9ce29f45b 100644 --- a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java +++ b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java @@ -31,18 +31,18 @@ public void baseTest() { Assert.assertEquals(BASE, Observability.getDiscoveryBuildInfo(BASE)); Observability.reportMetricsUsage(new Meter() { }); - Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE)); + Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE)); Observability.reportTracingUsage((String spanName, SpanKind spanKind) -> Span.NOOP); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE) ); Observability.reportMetricsUsage(Meter.NOOP); Observability.reportTracingUsage(NoopTracer.getInstance()); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE) ); } diff --git a/query/src/main/java/tech/ydb/query/impl/SessionPool.java b/query/src/main/java/tech/ydb/query/impl/SessionPool.java index 5b0cf272c..5d2cba7d2 100644 --- a/query/src/main/java/tech/ydb/query/impl/SessionPool.java +++ b/query/src/main/java/tech/ydb/query/impl/SessionPool.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -106,7 +107,9 @@ public void close() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire QuerySession with timeout {}", timeout); + long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); + future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -120,6 +123,26 @@ public CompletableFuture> acquire(Duration timeout) { return future; } + private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { + metrics.onAcquireTime(System.nanoTime() - startNanos); + if (error instanceof CancellationException) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (error != null || result == null) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } else if (!result.isSuccess()) { + StatusCode code = result.getStatus().getCode(); + if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); + } else if (code == StatusCode.CLIENT_CANCELLED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); + } else { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } + } + } + private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); @@ -128,10 +151,10 @@ private boolean pollNext(CompletableFuture> future) { return tryComplete(future, nextSession.join()); } + future.whenComplete((result, error) -> nextSession.cancel(false)); nextSession.whenComplete((session, th) -> { if (th != null) { if (future.isDone()) { - logger.warn("can't get QuerySession, future is already canceled", th); return; } diff --git a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java index 7fb29f879..5370c5443 100644 --- a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java @@ -64,6 +64,7 @@ public class PoolMetricsTest { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); + private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); private Runnable cleaner; @@ -85,7 +86,8 @@ public void setup() { when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); + when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> + PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -102,7 +104,9 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); + verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); + verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -131,6 +135,7 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); + verify(acquireTime).record(anyDouble(), argThat(poolName)); session.close(); verify(counter("released")).add(eq(1L), argThat(poolName)); @@ -139,6 +144,23 @@ public void sessionLifecycleRecordsCounters() { verify(counter("failed"), never()).add(anyLong(), any()); } + @Test + public void cancelledAcquireRemovesPendingRequestAndRecordsFailure() { + try (SessionPool pool = createPool(0, 1)) { + QuerySession occupied = acquireReady(pool); + CompletableFuture> cancelled = pool.acquire(TIMEOUT); + + Assert.assertTrue(cancelled.cancel(false)); + Assert.assertTrue(cancelled.isCancelled()); + assertPendingRequests(pool, 0L); + verifyAcquireFailure("cancelled"); + + occupied.close(); + assertPendingRequests(pool, 0L); + verify(counter("acquired")).add(eq(1L), argThat(poolName)); + } + } + @Test public void failedCreateRecordsFailedCounter() { rpc.overloaded = true; @@ -429,6 +451,20 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } + private void assertPendingRequests(SessionPool pool, long expected) { + LongMeasurement pending = mock(LongMeasurement.class); + gauges.get(PREFIX + "pending_requests").accept(pending); + verify(pending).record(eq(expected), argThat(poolName)); + } + + private void verifyAcquireFailure(String reason) { + verify(counter("acquire_failures")).add( + eq(1L), + argThat(poolName), + argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) + ); + } + private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java index daefe70af..722cc2c20 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java @@ -11,6 +11,19 @@ import tech.ydb.core.metrics.MetricRegistration; public final class PoolMetrics implements AutoCloseable { + public enum AcquireFailureReason { + TIMEOUT("timeout"), + CANCELLED("cancelled"), + REJECTED("rejected"), + OTHER("other"); + + private final String code; + + AcquireFailureReason(String code) { + this.code = code; + } + } + public enum Reason { UNKNOWN("unknown"), @@ -69,6 +82,7 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final Attr[] idleAttrs; private final Attr[] inUseAttrs; private final String statusKey; + private final String acquireFailureReasonKey; private final LongCounter created; private final LongCounter acquired; @@ -76,7 +90,9 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final LongCounter requested; private final LongCounter failed; private final LongCounter closed; + private final LongCounter acquireFailures; private final DoubleHistogram createTime; + private final DoubleHistogram acquireTime; private final MetricRegistration maxGauge; private final MetricRegistration minGauge; private final MetricRegistration countGauge; @@ -85,6 +101,7 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue queue, int minSize) { String prefix = "ydb." + name + ".session."; this.statusKey = prefix + "status_code"; + this.acquireFailureReasonKey = prefix + "reason"; this.poolNameAttr = Attr.of(prefix + "pool.name", poolName); this.poolAttrs = new Attr[]{poolNameAttr}; @@ -97,7 +114,10 @@ public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue qu this.requested = meter.createCounter(prefix + "requested", UNIT, "Total CreateSession calls."); this.failed = meter.createCounter(prefix + "failed", UNIT, "Total failed session creations."); this.closed = meter.createCounter(prefix + "closed", UNIT, "Total closed sessions."); + this.acquireFailures = meter.createCounter(prefix + "acquire_failures", "{request}", + "Total failed session acquire attempts."); this.createTime = meter.createHistogram(prefix + "create_time", "s", "Session creation cost."); + this.acquireTime = meter.createHistogram(prefix + "acquire_time", "s", "Session acquire duration."); this.maxGauge = meter.registerLongGauge(prefix + "max", UNIT, "Configured MaxPoolSize", m -> m.record(queue.getTotalLimit(), poolAttrs)); @@ -130,6 +150,14 @@ public void onCreateTime(long createTimeNanos) { createTime.record(createTimeNanos / NANOS_IN_SECOND, poolAttrs); } + public void onAcquireTime(long acquireTimeNanos) { + acquireTime.record(acquireTimeNanos / NANOS_IN_SECOND, poolAttrs); + } + + public void onAcquireFailure(@Nonnull AcquireFailureReason reason) { + acquireFailures.add(1L, poolNameAttr, Attr.of(acquireFailureReasonKey, reason.code)); + } + public void onSessionCreated() { created.add(1L, poolAttrs); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java index 9a497d2a2..516c36079 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -98,7 +99,9 @@ public SessionPoolStats stats() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire session with timeout {}", timeout); + long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); + future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -112,6 +115,26 @@ public CompletableFuture> acquire(Duration timeout) { return future; } + private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { + metrics.onAcquireTime(System.nanoTime() - startNanos); + if (error instanceof CancellationException) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (error != null || result == null) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } else if (!result.isSuccess()) { + StatusCode code = result.getStatus().getCode(); + if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); + } else if (code == StatusCode.CLIENT_CANCELLED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); + } else { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } + } + } + private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); @@ -120,8 +143,12 @@ private boolean pollNext(CompletableFuture> future) { return validateSession(nextSession.join(), future); } + future.whenComplete((result, error) -> nextSession.cancel(false)); nextSession.whenComplete((session, th) -> { if (th != null) { + if (future.isDone()) { + return; + } Throwable ex = FutureTools.unwrapCompletionException(th); Result fail = (ex instanceof UnexpectedResultException) ? Result.fail((UnexpectedResultException) ex) diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index a82572118..6a4146306 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -248,6 +248,13 @@ private boolean tryToCreateNewWaiting(CompletableFuture acquire) { } waitingAcquires.offer(acquire); // ConcurrentLinkedQueue always return true + acquire.whenComplete((ignored, th) -> removeWaitingAcquire(acquire)); + // close() can run after the count is reserved but before this offer. + // In that case clear() cannot see the new entry, so clean it here. + if (stopped && waitingAcquires.remove(acquire)) { + waitingAcqueireCount.decrementAndGet(); + acquire.completeExceptionally(new CancellationException("Queue is already closed")); + } return true; } @@ -291,10 +298,30 @@ private void checkNextWaitingAcquire() { waitingAcqueireCount.decrementAndGet(); } else { waitingAcquires.offerFirst(next); + // The future might have completed while it was temporarily removed from the deque. + // Its completion handler cannot remove it in that interval. + if (next.isDone()) { + removeWaitingAcquire(next); + } + if (stopped && waitingAcquires.remove(next)) { + waitingAcqueireCount.decrementAndGet(); + next.completeExceptionally(new CancellationException("Queue is already closed")); + } } } } + /** + * Removes a waiting acquire if it is still enqueued and updates the count + * exactly once. Polling paths update the count themselves after taking an + * acquire out of the deque. + */ + private void removeWaitingAcquire(CompletableFuture acquire) { + if (waitingAcquires.remove(acquire)) { + waitingAcqueireCount.decrementAndGet(); + } + } + private void clear() { for (CompletableFuture key : pendingRequests.keySet()) { if (pendingRequests.remove(key, key)) { @@ -304,6 +331,7 @@ private void clear() { CompletableFuture waiting = waitingAcquires.poll(); while (waiting != null) { + waitingAcqueireCount.decrementAndGet(); waiting.completeExceptionally(new CancellationException("Queue is already closed")); waiting = waitingAcquires.poll(); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java index 152a86b10..488af1fa8 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java @@ -49,6 +49,7 @@ public class PoolMetricsTest extends FutureHelper { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); + private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); @@ -62,7 +63,8 @@ public void setup() { clock.reset(Instant.parse("2022-07-01T00:00:00.000Z")); when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); + when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> + PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -87,7 +89,9 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); + verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); + verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -108,6 +112,7 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); + verify(acquireTime).record(anyDouble(), argThat(poolName)); Session s1 = futureIsReady(f1).getValue(); s1.close(); @@ -120,6 +125,35 @@ public void sessionLifecycleRecordsCounters() { verify(counter("failed"), never()).add(anyLong(), any()); } + @Test + public void acquireMetricsUseSecondsAndBoundedFailureReasons() { + WaitingQueue queue = new WaitingQueue<>(new WaitingQueue.Handler() { + @Override + public CompletableFuture create() { + return new CompletableFuture<>(); + } + + @Override + public void destroy(Object object) { + } + }, 1); + PoolMetrics metrics = new PoolMetrics(meter, "table", POOL, queue, 0); + + metrics.onAcquireTime(500_000_000L); + for (PoolMetrics.AcquireFailureReason reason : PoolMetrics.AcquireFailureReason.values()) { + metrics.onAcquireFailure(reason); + } + + verify(acquireTime).record(eq(0.5d), argThat(poolName)); + verifyAcquireFailure("timeout"); + verifyAcquireFailure("cancelled"); + verifyAcquireFailure("rejected"); + verifyAcquireFailure("other"); + + metrics.close(); + queue.close(); + } + @Test public void gracefulShutdownRecordsClosedReason() { SessionPool pool = createPool(0, 2); @@ -247,6 +281,14 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } + private void verifyAcquireFailure(String reason) { + verify(counter("acquire_failures")).add( + eq(1L), + argThat(poolName), + argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) + ); + } + private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java index b47f14cda..d8730e621 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java @@ -445,6 +445,56 @@ public void canceledSessionsTest() { tableRpc.completeSessionDeleteRequests(); } + @Test + public void timedOutWaitingAcquireReleasesQueueSlot() { + SessionPool pool = new SessionPool(clock, tableRpc, true, + SessionPoolOptions.DEFAULT.withSize(0, 1)); + + CompletableFuture> first = pendingFuture(pool.acquire(TIMEOUT)); + tableRpc.nextCreateSession().completeSuccess(); + Session held = futureIsReady(first).getValue(); + + CompletableFuture> timedOut = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + scheduler.runTasksTo(clock.instant().plus(TIMEOUT)); + resultIsWrong(timedOut, StatusCode.CLIENT_DEADLINE_EXPIRED); + check(pool).pending(0); + + CompletableFuture> next = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + held.close(); + Session acquired = futureIsReady(next).getValue(); + check(pool).pending(0).acquired(1); + + acquired.close(); + pool.close(); + tableRpc.completeSessionDeleteRequests(); + } + + @Test + public void cancelledWaitingAcquireReleasesQueueSlot() { + SessionPool pool = new SessionPool(clock, tableRpc, true, + SessionPoolOptions.DEFAULT.withSize(0, 1)); + + CompletableFuture> first = pendingFuture(pool.acquire(TIMEOUT)); + tableRpc.nextCreateSession().completeSuccess(); + Session held = futureIsReady(first).getValue(); + + CompletableFuture> cancelled = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + Assert.assertTrue(cancelled.cancel(true)); + check(pool).pending(0); + + CompletableFuture> next = pendingFuture(pool.acquire(TIMEOUT)); + held.close(); + Session acquired = futureIsReady(next).getValue(); + check(pool).pending(0).acquired(1); + + acquired.close(); + pool.close(); + tableRpc.completeSessionDeleteRequests(); + } + @Test public void sessionDataQueryErrorsTest() { SessionPool pool = new SessionPool(clock, tableRpc, true, diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 9616ebf2e..bf53e1dc1 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -562,11 +562,11 @@ public void canceledWaitingTest() { Resource r2 = pendingIsReady(w1); Assert.assertEquals("Next waiting got same resource ", r1, r2); - // Cancellation of waiting doesn't affect to queue - w2.cancel(true); - check(queue).queueSize(1).idleSize(0).waitingsCount(2); + // Cancellation immediately removes the waiter and frees a waiting slot. + Assert.assertTrue(w2.cancel(true)); + check(queue).queueSize(1).idleSize(0).waitingsCount(1); - // Canceled waiting must be deleted when queue process next released resource + // The next released resource goes directly to the remaining waiter. queue.release(r2); check(queue).queueSize(1).idleSize(0).waitingsCount(0); @@ -580,6 +580,71 @@ public void canceledWaitingTest() { check(rs).requestsCount(0).activeCount(0); } + @Test + public void completedWaitingIsRemovedImmediatelyTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + waiting.completeExceptionally(new RuntimeException("caller stopped waiting")); + check(queue).waitingsCount(0); + + rs.completeNext(); + Resource resource = pendingIsReady(first); + queue.release(resource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + } + + @Test + public void canceledWaitingAfterRequeueDoesNotConsumeReleasedResourceTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 2, 1); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture second = pendingFuture(acquire(queue)); + rs.completeNext().completeNext(); + Resource firstResource = pendingIsReady(first); + Resource secondResource = pendingIsReady(second); + + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + // Reducing the limit polls and requeues the waiter because both resources are in use. + queue.updateLimits(1, 1); + check(queue).waitingsCount(1); + + waiting.cancel(true); + check(queue).waitingsCount(0); + + queue.release(firstResource); + queue.release(secondResource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + } + + @Test + public void closeRemovesWaitingCountImmediatelyTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + queue.close(); + futureIsCanceled(waiting, QUEUE_IS_CLOSED); + check(queue).queueSize(0).waitingsCount(0); + + rs.completeNext(); + futureIsCanceled(first, QUEUE_IS_CLOSED); + } + @Test public void immediatellyCompletedWaitingsTest() { ResourceHandler rs = new ResourceHandler(); From 4ca7a9bbd1877af41839597b6a9db202b9b239bc Mon Sep 17 00:00:00 2001 From: lebmax Date: Wed, 25 Nov 2026 00:03:13 +0300 Subject: [PATCH 02/29] Test queue admission after waiter cancellation --- .../ydb/table/impl/pool/WaitingQueueTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index bf53e1dc1..07fa3c67c 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -580,6 +580,38 @@ public void canceledWaitingTest() { check(rs).requestsCount(0).activeCount(0); } + @Test + public void cancelledWaitingFreesFullQueueSlotTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + CompletableFuture cancelled = pendingFuture(acquire(queue)); + CompletableFuture remaining = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + + Assert.assertTrue(cancelled.cancel(true)); + check(queue).waitingsCount(1); + CompletableFuture replacement = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + + queue.release(resource); + Resource next = pendingIsReady(remaining); + Assert.assertSame(resource, next); + queue.release(next); + Resource last = pendingIsReady(replacement); + Assert.assertSame(resource, last); + + queue.delete(last); + queue.close(); + check(queue).queueSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + @Test public void completedWaitingIsRemovedImmediatelyTest() { ResourceHandler rs = new ResourceHandler(); From 823dcf3abc0c3172a3339a77889ba70659d98772 Mon Sep 17 00:00:00 2001 From: lebmax Date: Thu, 26 Nov 2026 11:24:27 +0300 Subject: [PATCH 03/29] Fix waiting acquire count field name --- .../ydb/table/impl/pool/WaitingQueue.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index 6a4146306..79f0208af 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -58,7 +58,7 @@ default void destroy(T object, PoolMetrics.Reason reason) { /** Queue of waiting acquire requests */ private final ConcurrentLinkedDeque> waitingAcquires = new ConcurrentLinkedDeque<>(); /** Size of waiting acquires queue */ - private final AtomicInteger waitingAcqueireCount = new AtomicInteger(); + private final AtomicInteger waitingAcquireCount = new AtomicInteger(); private final ThreadLocal localGuard = new ThreadLocal<>(); @@ -178,7 +178,7 @@ public int getPendingCount() { } public int getWaitingCount() { - return waitingAcqueireCount.get(); + return waitingAcquireCount.get(); } public int getTotalLimit() { @@ -240,10 +240,10 @@ private boolean tryToCreateNewPending(CompletableFuture acquire) { } private boolean tryToCreateNewWaiting(CompletableFuture acquire) { - int waitingsCount = waitingAcqueireCount.get(); + int waitingsCount = waitingAcquireCount.get(); while (waitingsCount < limits.waitingsLimit) { - if (!waitingAcqueireCount.compareAndSet(waitingsCount, waitingsCount + 1)) { - waitingsCount = waitingAcqueireCount.get(); + if (!waitingAcquireCount.compareAndSet(waitingsCount, waitingsCount + 1)) { + waitingsCount = waitingAcquireCount.get(); continue; } @@ -252,7 +252,7 @@ private boolean tryToCreateNewWaiting(CompletableFuture acquire) { // close() can run after the count is reserved but before this offer. // In that case clear() cannot see the new entry, so clean it here. if (stopped && waitingAcquires.remove(acquire)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); acquire.completeExceptionally(new CancellationException("Queue is already closed")); } return true; @@ -270,7 +270,7 @@ private boolean tryToCompleteWaiting(T object) { CompletableFuture next = waitingAcquires.poll(); while (next != null) { guard.init(); - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); if (safeAcquireObject(next, object) && !guard.isBroken()) { return true; } @@ -289,13 +289,13 @@ private void checkNextWaitingAcquire() { CompletableFuture next = waitingAcquires.poll(); while (next != null && next.isDone()) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); next = waitingAcquires.poll(); } if (next != null) { if (tryToCreateNewPending(next)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); } else { waitingAcquires.offerFirst(next); // The future might have completed while it was temporarily removed from the deque. @@ -304,7 +304,7 @@ private void checkNextWaitingAcquire() { removeWaitingAcquire(next); } if (stopped && waitingAcquires.remove(next)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); next.completeExceptionally(new CancellationException("Queue is already closed")); } } @@ -318,7 +318,7 @@ private void checkNextWaitingAcquire() { */ private void removeWaitingAcquire(CompletableFuture acquire) { if (waitingAcquires.remove(acquire)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); } } @@ -331,7 +331,7 @@ private void clear() { CompletableFuture waiting = waitingAcquires.poll(); while (waiting != null) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); waiting.completeExceptionally(new CancellationException("Queue is already closed")); waiting = waitingAcquires.poll(); } From f70f0987ea589871e92e3225eb8e953d858ef795 Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 27 Nov 2026 13:42:34 +0300 Subject: [PATCH 04/29] Fix canceled session acquires with constant-time waiter removal --- CHANGELOG.md | 1 - .../tech/ydb/core/impl/Observability.java | 2 +- .../tech/ydb/core/impl/ObservabilityTest.java | 6 +- .../java/tech/ydb/query/impl/SessionPool.java | 22 --- .../tech/ydb/query/impl/PoolMetricsTest.java | 24 +-- .../tech/ydb/table/impl/pool/PoolMetrics.java | 28 ---- .../tech/ydb/table/impl/pool/SessionPool.java | 23 --- .../ydb/table/impl/pool/WaitingAcquires.java | 113 +++++++++++++ .../ydb/table/impl/pool/WaitingQueue.java | 75 ++++----- .../ydb/table/impl/pool/PoolMetricsTest.java | 44 +---- .../ydb/table/impl/pool/SessionPoolTest.java | 4 +- .../ydb/table/impl/pool/WaitingQueueTest.java | 150 +++++++++++++++++- 12 files changed, 301 insertions(+), 191 deletions(-) create mode 100644 table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 129c6ade1..97d40180f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,5 @@ * Core: added opt-in PRIMARY/PROMOTED Bridge pile preference with synchronized-pile fallback * Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately -* Table/Query: added session-pool acquire duration and bounded failure-reason metrics ## 2.5.0 ## * Core: upgraded to grpc-java v1.82.4 diff --git a/core/src/main/java/tech/ydb/core/impl/Observability.java b/core/src/main/java/tech/ydb/core/impl/Observability.java index ea94778c7..3eba77589 100644 --- a/core/src/main/java/tech/ydb/core/impl/Observability.java +++ b/core/src/main/java/tech/ydb/core/impl/Observability.java @@ -12,7 +12,7 @@ */ public final class Observability { public static final String TRACING_CHAIN = ";ydb-sdk-tracing/0.1.0"; - public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.4.0"; + public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.3.0"; private static volatile boolean isTracingEnabled = false; private static volatile boolean isMetricsEnabled = false; diff --git a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java index 9ce29f45b..b6fc8dec4 100644 --- a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java +++ b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java @@ -31,18 +31,18 @@ public void baseTest() { Assert.assertEquals(BASE, Observability.getDiscoveryBuildInfo(BASE)); Observability.reportMetricsUsage(new Meter() { }); - Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE)); + Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE)); Observability.reportTracingUsage((String spanName, SpanKind spanKind) -> Span.NOOP); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE) ); Observability.reportMetricsUsage(Meter.NOOP); Observability.reportTracingUsage(NoopTracer.getInstance()); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE) ); } diff --git a/query/src/main/java/tech/ydb/query/impl/SessionPool.java b/query/src/main/java/tech/ydb/query/impl/SessionPool.java index 5d2cba7d2..a19fba94f 100644 --- a/query/src/main/java/tech/ydb/query/impl/SessionPool.java +++ b/query/src/main/java/tech/ydb/query/impl/SessionPool.java @@ -107,9 +107,7 @@ public void close() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire QuerySession with timeout {}", timeout); - long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); - future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -123,26 +121,6 @@ public CompletableFuture> acquire(Duration timeout) { return future; } - private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { - metrics.onAcquireTime(System.nanoTime() - startNanos); - if (error instanceof CancellationException) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (error != null || result == null) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } else if (!result.isSuccess()) { - StatusCode code = result.getStatus().getCode(); - if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); - } else if (code == StatusCode.CLIENT_CANCELLED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); - } else { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } - } - } - private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); diff --git a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java index 5370c5443..65d1a85d6 100644 --- a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java @@ -64,7 +64,6 @@ public class PoolMetricsTest { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); - private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); private Runnable cleaner; @@ -86,8 +85,7 @@ public void setup() { when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> - PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); + when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -104,9 +102,7 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); - verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); - verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -135,7 +131,6 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); - verify(acquireTime).record(anyDouble(), argThat(poolName)); session.close(); verify(counter("released")).add(eq(1L), argThat(poolName)); @@ -145,18 +140,17 @@ public void sessionLifecycleRecordsCounters() { } @Test - public void cancelledAcquireRemovesPendingRequestAndRecordsFailure() { + public void cancelledAcquireRemovesPendingRequest() { try (SessionPool pool = createPool(0, 1)) { QuerySession occupied = acquireReady(pool); CompletableFuture> cancelled = pool.acquire(TIMEOUT); Assert.assertTrue(cancelled.cancel(false)); Assert.assertTrue(cancelled.isCancelled()); - assertPendingRequests(pool, 0L); - verifyAcquireFailure("cancelled"); + assertPendingRequests(0L); occupied.close(); - assertPendingRequests(pool, 0L); + assertPendingRequests(0L); verify(counter("acquired")).add(eq(1L), argThat(poolName)); } } @@ -451,20 +445,12 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } - private void assertPendingRequests(SessionPool pool, long expected) { + private void assertPendingRequests(long expected) { LongMeasurement pending = mock(LongMeasurement.class); gauges.get(PREFIX + "pending_requests").accept(pending); verify(pending).record(eq(expected), argThat(poolName)); } - private void verifyAcquireFailure(String reason) { - verify(counter("acquire_failures")).add( - eq(1L), - argThat(poolName), - argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) - ); - } - private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java index 722cc2c20..daefe70af 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java @@ -11,19 +11,6 @@ import tech.ydb.core.metrics.MetricRegistration; public final class PoolMetrics implements AutoCloseable { - public enum AcquireFailureReason { - TIMEOUT("timeout"), - CANCELLED("cancelled"), - REJECTED("rejected"), - OTHER("other"); - - private final String code; - - AcquireFailureReason(String code) { - this.code = code; - } - } - public enum Reason { UNKNOWN("unknown"), @@ -82,7 +69,6 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final Attr[] idleAttrs; private final Attr[] inUseAttrs; private final String statusKey; - private final String acquireFailureReasonKey; private final LongCounter created; private final LongCounter acquired; @@ -90,9 +76,7 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final LongCounter requested; private final LongCounter failed; private final LongCounter closed; - private final LongCounter acquireFailures; private final DoubleHistogram createTime; - private final DoubleHistogram acquireTime; private final MetricRegistration maxGauge; private final MetricRegistration minGauge; private final MetricRegistration countGauge; @@ -101,7 +85,6 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue queue, int minSize) { String prefix = "ydb." + name + ".session."; this.statusKey = prefix + "status_code"; - this.acquireFailureReasonKey = prefix + "reason"; this.poolNameAttr = Attr.of(prefix + "pool.name", poolName); this.poolAttrs = new Attr[]{poolNameAttr}; @@ -114,10 +97,7 @@ public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue qu this.requested = meter.createCounter(prefix + "requested", UNIT, "Total CreateSession calls."); this.failed = meter.createCounter(prefix + "failed", UNIT, "Total failed session creations."); this.closed = meter.createCounter(prefix + "closed", UNIT, "Total closed sessions."); - this.acquireFailures = meter.createCounter(prefix + "acquire_failures", "{request}", - "Total failed session acquire attempts."); this.createTime = meter.createHistogram(prefix + "create_time", "s", "Session creation cost."); - this.acquireTime = meter.createHistogram(prefix + "acquire_time", "s", "Session acquire duration."); this.maxGauge = meter.registerLongGauge(prefix + "max", UNIT, "Configured MaxPoolSize", m -> m.record(queue.getTotalLimit(), poolAttrs)); @@ -150,14 +130,6 @@ public void onCreateTime(long createTimeNanos) { createTime.record(createTimeNanos / NANOS_IN_SECOND, poolAttrs); } - public void onAcquireTime(long acquireTimeNanos) { - acquireTime.record(acquireTimeNanos / NANOS_IN_SECOND, poolAttrs); - } - - public void onAcquireFailure(@Nonnull AcquireFailureReason reason) { - acquireFailures.add(1L, poolNameAttr, Attr.of(acquireFailureReasonKey, reason.code)); - } - public void onSessionCreated() { created.add(1L, poolAttrs); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java index 516c36079..72239b43f 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java @@ -4,7 +4,6 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; -import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -99,9 +98,7 @@ public SessionPoolStats stats() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire session with timeout {}", timeout); - long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); - future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -115,26 +112,6 @@ public CompletableFuture> acquire(Duration timeout) { return future; } - private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { - metrics.onAcquireTime(System.nanoTime() - startNanos); - if (error instanceof CancellationException) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (error != null || result == null) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } else if (!result.isSuccess()) { - StatusCode code = result.getStatus().getCode(); - if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); - } else if (code == StatusCode.CLIENT_CANCELLED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); - } else { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } - } - } - private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java new file mode 100644 index 000000000..74b9b9a6a --- /dev/null +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java @@ -0,0 +1,113 @@ +package tech.ydb.table.impl.pool; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; + +final class WaitingAcquires { + private final AtomicInteger count = new AtomicInteger(); + + private Waiter first; + private Waiter last; + + int count() { + return count.get(); + } + + boolean compareAndReserve(int expectedCount) { + return count.compareAndSet(expectedCount, expectedCount + 1); + } + + void releaseReservation() { + count.decrementAndGet(); + } + + Waiter newWaiter(CompletableFuture acquire) { + return new Waiter<>(this, acquire); + } + + synchronized void offerLast(Waiter waiter) { + if (waiter.linked) { + unlink(waiter); + } + waiter.previous = last; + waiter.next = null; + waiter.linked = true; + if (last == null) { + first = waiter; + } else { + last.next = waiter; + } + last = waiter; + } + + synchronized void offerFirst(Waiter waiter) { + if (waiter.linked) { + unlink(waiter); + } + waiter.previous = null; + waiter.next = first; + waiter.linked = true; + if (first == null) { + last = waiter; + } else { + first.previous = waiter; + } + first = waiter; + } + + synchronized Waiter pollFirst() { + if (first == null) { + return null; + } + Waiter waiter = first; + unlink(waiter); + // Polling only unlinks; callers decide when to release the reservation. + return waiter; + } + + synchronized boolean remove(Waiter waiter) { + if (!waiter.linked) { + return false; + } + unlink(waiter); + count.decrementAndGet(); + return true; + } + + private void unlink(Waiter waiter) { + Waiter previous = waiter.previous; + Waiter next = waiter.next; + if (previous == null) { + first = next; + } else { + previous.next = next; + } + if (next == null) { + last = previous; + } else { + next.previous = previous; + } + waiter.previous = null; + waiter.next = null; + waiter.linked = false; + } + + static final class Waiter implements BiConsumer { + private final WaitingAcquires owner; + final CompletableFuture acquire; + private Waiter previous; + private Waiter next; + private boolean linked; + + private Waiter(WaitingAcquires owner, CompletableFuture acquire) { + this.owner = owner; + this.acquire = acquire; + } + + @Override + public void accept(T object, Throwable error) { + owner.remove(this); + } + } +} diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index 79f0208af..8c09d3f7c 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -55,10 +55,7 @@ default void destroy(T object, PoolMetrics.Reason reason) { /** Summary size of queue = idle.size() + used.size() + pendingRequests.size() */ private final AtomicInteger queueSize = new AtomicInteger(); - /** Queue of waiting acquire requests */ - private final ConcurrentLinkedDeque> waitingAcquires = new ConcurrentLinkedDeque<>(); - /** Size of waiting acquires queue */ - private final AtomicInteger waitingAcquireCount = new AtomicInteger(); + private final WaitingAcquires waitingAcquires = new WaitingAcquires<>(); private final ThreadLocal localGuard = new ThreadLocal<>(); @@ -178,7 +175,7 @@ public int getPendingCount() { } public int getWaitingCount() { - return waitingAcquireCount.get(); + return waitingAcquires.count(); } public int getTotalLimit() { @@ -240,19 +237,19 @@ private boolean tryToCreateNewPending(CompletableFuture acquire) { } private boolean tryToCreateNewWaiting(CompletableFuture acquire) { - int waitingsCount = waitingAcquireCount.get(); + int waitingsCount = waitingAcquires.count(); while (waitingsCount < limits.waitingsLimit) { - if (!waitingAcquireCount.compareAndSet(waitingsCount, waitingsCount + 1)) { - waitingsCount = waitingAcquireCount.get(); + if (!waitingAcquires.compareAndReserve(waitingsCount)) { + waitingsCount = waitingAcquires.count(); continue; } - waitingAcquires.offer(acquire); // ConcurrentLinkedQueue always return true - acquire.whenComplete((ignored, th) -> removeWaitingAcquire(acquire)); + WaitingAcquires.Waiter waiter = waitingAcquires.newWaiter(acquire); + waitingAcquires.offerLast(waiter); + acquire.whenComplete(waiter); // close() can run after the count is reserved but before this offer. // In that case clear() cannot see the new entry, so clean it here. - if (stopped && waitingAcquires.remove(acquire)) { - waitingAcquireCount.decrementAndGet(); + if (stopped && waitingAcquires.remove(waiter)) { acquire.completeExceptionally(new CancellationException("Queue is already closed")); } return true; @@ -267,15 +264,15 @@ private boolean tryToCompleteWaiting(T object) { } try (WaitingGuard guard = new WaitingGuard(object)) { - CompletableFuture next = waitingAcquires.poll(); - while (next != null) { + WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); + while (waiter != null) { guard.init(); - waitingAcquireCount.decrementAndGet(); - if (safeAcquireObject(next, object) && !guard.isBroken()) { + waitingAcquires.releaseReservation(); + if (safeAcquireObject(waiter.acquire, object) && !guard.isBroken()) { return true; } - next = waitingAcquires.poll(); + waiter = waitingAcquires.pollFirst(); } return false; @@ -287,41 +284,29 @@ private void checkNextWaitingAcquire() { return; } - CompletableFuture next = waitingAcquires.poll(); - while (next != null && next.isDone()) { - waitingAcquireCount.decrementAndGet(); - next = waitingAcquires.poll(); + WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); + while (waiter != null && waiter.acquire.isDone()) { + waitingAcquires.releaseReservation(); + waiter = waitingAcquires.pollFirst(); } - if (next != null) { - if (tryToCreateNewPending(next)) { - waitingAcquireCount.decrementAndGet(); + if (waiter != null) { + if (tryToCreateNewPending(waiter.acquire)) { + waitingAcquires.releaseReservation(); } else { - waitingAcquires.offerFirst(next); + waitingAcquires.offerFirst(waiter); // The future might have completed while it was temporarily removed from the deque. // Its completion handler cannot remove it in that interval. - if (next.isDone()) { - removeWaitingAcquire(next); + if (waiter.acquire.isDone()) { + waitingAcquires.remove(waiter); } - if (stopped && waitingAcquires.remove(next)) { - waitingAcquireCount.decrementAndGet(); - next.completeExceptionally(new CancellationException("Queue is already closed")); + if (stopped && waitingAcquires.remove(waiter)) { + waiter.acquire.completeExceptionally(new CancellationException("Queue is already closed")); } } } } - /** - * Removes a waiting acquire if it is still enqueued and updates the count - * exactly once. Polling paths update the count themselves after taking an - * acquire out of the deque. - */ - private void removeWaitingAcquire(CompletableFuture acquire) { - if (waitingAcquires.remove(acquire)) { - waitingAcquireCount.decrementAndGet(); - } - } - private void clear() { for (CompletableFuture key : pendingRequests.keySet()) { if (pendingRequests.remove(key, key)) { @@ -329,11 +314,11 @@ private void clear() { } } - CompletableFuture waiting = waitingAcquires.poll(); + WaitingAcquires.Waiter waiting = waitingAcquires.pollFirst(); while (waiting != null) { - waitingAcquireCount.decrementAndGet(); - waiting.completeExceptionally(new CancellationException("Queue is already closed")); - waiting = waitingAcquires.poll(); + waitingAcquires.releaseReservation(); + waiting.acquire.completeExceptionally(new CancellationException("Queue is already closed")); + waiting = waitingAcquires.pollFirst(); } T nextIdle = idle.poll(); diff --git a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java index 488af1fa8..152a86b10 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java @@ -49,7 +49,6 @@ public class PoolMetricsTest extends FutureHelper { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); - private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); @@ -63,8 +62,7 @@ public void setup() { clock.reset(Instant.parse("2022-07-01T00:00:00.000Z")); when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> - PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); + when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -89,9 +87,7 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); - verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); - verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -112,7 +108,6 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); - verify(acquireTime).record(anyDouble(), argThat(poolName)); Session s1 = futureIsReady(f1).getValue(); s1.close(); @@ -125,35 +120,6 @@ public void sessionLifecycleRecordsCounters() { verify(counter("failed"), never()).add(anyLong(), any()); } - @Test - public void acquireMetricsUseSecondsAndBoundedFailureReasons() { - WaitingQueue queue = new WaitingQueue<>(new WaitingQueue.Handler() { - @Override - public CompletableFuture create() { - return new CompletableFuture<>(); - } - - @Override - public void destroy(Object object) { - } - }, 1); - PoolMetrics metrics = new PoolMetrics(meter, "table", POOL, queue, 0); - - metrics.onAcquireTime(500_000_000L); - for (PoolMetrics.AcquireFailureReason reason : PoolMetrics.AcquireFailureReason.values()) { - metrics.onAcquireFailure(reason); - } - - verify(acquireTime).record(eq(0.5d), argThat(poolName)); - verifyAcquireFailure("timeout"); - verifyAcquireFailure("cancelled"); - verifyAcquireFailure("rejected"); - verifyAcquireFailure("other"); - - metrics.close(); - queue.close(); - } - @Test public void gracefulShutdownRecordsClosedReason() { SessionPool pool = createPool(0, 2); @@ -281,14 +247,6 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } - private void verifyAcquireFailure(String reason) { - verify(counter("acquire_failures")).add( - eq(1L), - argThat(poolName), - argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) - ); - } - private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java index d8730e621..e38e72d28 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java @@ -104,7 +104,7 @@ public void increaseLimitsTest() { tableRpc.check().sessionRequests(1); check(pool).idle(0).acquired(0).pending(1).size(0, 1).totalClient(0, 0).totalServer(1, 0, 0, 0); - // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue + // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue for (int i = 0; i < wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } @@ -149,7 +149,7 @@ public void decreaseLimitsTest() { tableRpc.check().sessionRequests(2); check(pool).idle(0).acquired(0).pending(2).size(0, 2).totalClient(0, 0).totalServer(2, 0, 0, 0); - // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue + // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue for (int i = 0; i < 2 * wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 07fa3c67c..7e1e25391 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -1,14 +1,19 @@ package tech.ydb.table.impl.pool; import java.util.ArrayDeque; +import java.util.ArrayList; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.junit.Assert; @@ -527,6 +532,7 @@ public void simpleWaitingRequests() { // After release resource must be moved to next waiting future queue.release(next); CompletableFuture waiting = waitings.poll(); + Assert.assertNotNull(waiting); next = pendingIsReady(waiting); Assert.assertEquals("All waitings got single resource ", r1, next); @@ -612,6 +618,31 @@ public void cancelledWaitingFreesFullQueueSlotTest() { check(rs).requestsCount(0).activeCount(0); } + @Test + public void cancelDuplicatedWaitingAcquireRemovesBothReservationsTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + CompletableFuture duplicated = new CompletableFuture<>(); + queue.acquire(duplicated); + queue.acquire(duplicated); + check(queue).waitingsCount(2); + + Assert.assertTrue(duplicated.cancel(true)); + check(queue).queueSize(1).idleSize(0).waitingsCount(0); + + queue.release(resource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + @Test public void completedWaitingIsRemovedImmediatelyTest() { ResourceHandler rs = new ResourceHandler(); @@ -660,21 +691,132 @@ public void canceledWaitingAfterRequeueDoesNotConsumeReleasedResourceTest() { queue.close(); } + @Test + public void updateLimitsDequeuesOldestWaiterAtFrontTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 2, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture second = pendingFuture(acquire(queue)); + rs.completeNext().completeNext(); + Resource firstResource = pendingIsReady(first); + Resource secondResource = pendingIsReady(second); + + CompletableFuture oldestWaiting = pendingFuture(acquire(queue)); + CompletableFuture laterWaiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + + // With both resources in use, the oldest waiter cannot reserve a new resource. + // It must remain ahead of the later waiter when it is returned to the queue. + queue.updateLimits(1, 2); + check(queue).waitingsCount(2); + + queue.release(firstResource); + Assert.assertSame(firstResource, pendingIsReady(oldestWaiting)); + futureIsPending(laterWaiting); + + queue.release(secondResource); + Assert.assertSame(secondResource, pendingIsReady(laterWaiting)); + + queue.delete(firstResource); + queue.delete(secondResource); + queue.close(); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + @Test public void closeRemovesWaitingCountImmediatelyTest() { ResourceHandler rs = new ResourceHandler(); - WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 3); CompletableFuture first = pendingFuture(acquire(queue)); - CompletableFuture waiting = pendingFuture(acquire(queue)); - check(queue).waitingsCount(1); + CompletableFuture firstWaiting = pendingFuture(acquire(queue)); + CompletableFuture middleWaiting = pendingFuture(acquire(queue)); + CompletableFuture lastWaiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(3); queue.close(); - futureIsCanceled(waiting, QUEUE_IS_CLOSED); + futureIsCanceled(firstWaiting, QUEUE_IS_CLOSED); + futureIsCanceled(middleWaiting, QUEUE_IS_CLOSED); + futureIsCanceled(lastWaiting, QUEUE_IS_CLOSED); check(queue).queueSize(0).waitingsCount(0); rs.completeNext(); futureIsCanceled(first, QUEUE_IS_CLOSED); + check(rs).requestsCount(0).activeCount(0); + } + + @Test + public void concurrentCancelAndCloseRemovesAllWaitingAcquiresTest() throws InterruptedException { + final int waitingCount = 64; + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, waitingCount); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + List> waitings = new ArrayList<>(); + for (int idx = 0; idx < waitingCount; idx++) { + CompletableFuture waiting = new CompletableFuture<>(); + queue.acquire(waiting); + waitings.add(waiting); + } + check(queue).waitingsCount(waitingCount); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + AtomicReference workerFailure = new AtomicReference<>(); + + Thread cancellation = new Thread(() -> { + ready.countDown(); + try { + Assert.assertTrue("Cancellation worker did not start", start.await(5, TimeUnit.SECONDS)); + for (CompletableFuture waiting : waitings) { + waiting.cancel(true); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + workerFailure.compareAndSet(null, ex); + } catch (Throwable th) { + workerFailure.compareAndSet(null, th); + } + }, "waiting-queue-cancellation-test"); + Thread closing = new Thread(() -> { + ready.countDown(); + try { + Assert.assertTrue("Close worker did not start", start.await(5, TimeUnit.SECONDS)); + queue.close(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + workerFailure.compareAndSet(null, ex); + } catch (Throwable th) { + workerFailure.compareAndSet(null, th); + } + }, "waiting-queue-close-test"); + cancellation.setDaemon(true); + closing.setDaemon(true); + cancellation.start(); + closing.start(); + + boolean workersReady = ready.await(5, TimeUnit.SECONDS); + start.countDown(); + cancellation.join(5000); + closing.join(5000); + + Assert.assertTrue("Workers did not become ready", workersReady); + Assert.assertFalse("Cancellation worker did not finish", cancellation.isAlive()); + Assert.assertFalse("Close worker did not finish", closing.isAlive()); + Assert.assertNull("Concurrent worker failed", workerFailure.get()); + check(queue).queueSize(1).idleSize(0).waitingsCount(0); + for (CompletableFuture waiting : waitings) { + Assert.assertTrue("Waiting future is terminal", waiting.isDone()); + } + + queue.release(resource); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); } @Test From 4806946bbb272335b146469b3ca1d74b1d90ebf0 Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 27 Nov 2026 13:57:13 +0300 Subject: [PATCH 05/29] Remove unused cancellation import --- query/src/main/java/tech/ydb/query/impl/SessionPool.java | 1 - 1 file changed, 1 deletion(-) diff --git a/query/src/main/java/tech/ydb/query/impl/SessionPool.java b/query/src/main/java/tech/ydb/query/impl/SessionPool.java index a19fba94f..ef93223e1 100644 --- a/query/src/main/java/tech/ydb/query/impl/SessionPool.java +++ b/query/src/main/java/tech/ydb/query/impl/SessionPool.java @@ -4,7 +4,6 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; -import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; From 091e2fda977da74000087acc2be862118b9aaa44 Mon Sep 17 00:00:00 2001 From: Ivan Laptev Date: Thu, 26 Nov 2026 16:13:51 +0300 Subject: [PATCH 06/29] Expose topic partition key ranges (#799) --- .../ydb/topic/description/PartitionInfo.java | 50 ++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java index 0f7474210..ce2b8bd18 100644 --- a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java +++ b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java @@ -6,6 +6,7 @@ import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; import tech.ydb.proto.topic.YdbTopic; @@ -18,6 +19,11 @@ public class PartitionInfo { private final List childPartitionIds; private final List parentPartitionIds; private final PartitionStats partitionStats; + private final boolean keyRange; + @Nullable + private final ByteString fromBound; + @Nullable + private final ByteString toBound; public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.partitionId = info.getPartitionId(); @@ -25,6 +31,10 @@ public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.childPartitionIds = ImmutableList.copyOf(info.getChildPartitionIdsList()); this.parentPartitionIds = ImmutableList.copyOf(info.getParentPartitionIdsList()); this.partitionStats = info.hasPartitionStats() ? new PartitionStats(info.getPartitionStats()) : null; + this.keyRange = info.hasKeyRange(); + YdbTopic.PartitionKeyRange range = info.getKeyRange(); + this.fromBound = range.hasFromBound() ? range.getFromBound() : null; + this.toBound = range.hasToBound() ? range.getToBound() : null; } public long getPartitionId() { @@ -43,6 +53,38 @@ public List getParentPartitionIds() { return parentPartitionIds; } + /** + * Whether the server supplied a key range, including a range with both ends unbounded. + * @return true if key-range metadata is present + */ + public boolean hasKeyRange() { + return keyRange; + } + + public boolean hasFromBound() { + return fromBound != null; + } + + public boolean hasToBound() { + return toBound != null; + } + + /** + * Inclusive lower bound, compared as unsigned bytes. Empty means unbounded. + * @return a defensive copy of the bound + */ + public byte[] getFromBound() { + return fromBound == null ? new byte[0] : fromBound.toByteArray(); + } + + /** + * Exclusive upper bound, compared as unsigned bytes. Empty means unbounded. + * @return a defensive copy of the bound + */ + public byte[] getToBound() { + return toBound == null ? new byte[0] : toBound.toByteArray(); + } + @Nullable public PartitionStats getPartitionStats() { return partitionStats; @@ -61,11 +103,15 @@ public boolean equals(Object o) { active == that.active && Objects.equals(childPartitionIds, that.childPartitionIds) && Objects.equals(parentPartitionIds, that.parentPartitionIds) && - Objects.equals(partitionStats, that.partitionStats); + Objects.equals(partitionStats, that.partitionStats) && + keyRange == that.keyRange && + Objects.equals(fromBound, that.fromBound) && + Objects.equals(toBound, that.toBound); } @Override public int hashCode() { - return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats); + return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats, + keyRange, fromBound, toBound); } } From 980a7f9c9ddd7b2bb4df1e2d2a80aca8fff60703 Mon Sep 17 00:00:00 2001 From: Alexandr Gorshenin Date: Wed, 25 Nov 2026 08:33:37 +0000 Subject: [PATCH 07/29] Added option to set grpc channel shutdown timeout --- .../ydb/core/grpc/GrpcTransportBuilder.java | 12 ++++++++++++ .../core/impl/FixedCallOptionsTransport.java | 4 +++- .../ydb/core/impl/MultiChannelTransport.java | 2 +- .../ydb/core/impl/SingleChannelTransport.java | 2 +- .../tech/ydb/core/impl/YdbTransportImpl.java | 10 ++++++---- .../tech/ydb/core/impl/auth/GrpcAuthRpc.java | 2 ++ .../tech/ydb/core/impl/pool/GrpcChannel.java | 18 ++++++------------ .../ydb/core/impl/pool/GrpcChannelPool.java | 10 +++++++--- .../core/grpc/GrpcTransportBuilderTest.java | 19 +++++++++++++++++++ .../tech/ydb/core/impl/YdbDiscoveryTest.java | 3 ++- .../core/impl/pool/GrpcChannelPoolTest.java | 11 ++++++----- 11 files changed, 65 insertions(+), 28 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java index a014bf782..a877bbd00 100644 --- a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java +++ b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java @@ -86,6 +86,7 @@ public enum InitMode { private AuthRpcProvider authProvider = NopAuthProvider.INSTANCE; private long readTimeoutMillis = 0; private long discoveryTimeoutMillis = 60_000; + private Duration channelShutdownTimeout = Duration.ofSeconds(5); private boolean useDefaultGrpcResolver = false; private GrpcCompression compression = GrpcCompression.NO_COMPRESSION; private InitMode initMode = InitMode.SYNC; @@ -191,6 +192,10 @@ public long getDiscoveryTimeoutMillis() { return discoveryTimeoutMillis; } + public Duration getChannelShutdownTimeout() { + return channelShutdownTimeout; + } + public GrpcCompression getGrpcCompression() { return compression; } @@ -355,6 +360,13 @@ public GrpcTransportBuilder withDiscoveryTimeout(long timeout, TimeUnit unit) { return this; } + public GrpcTransportBuilder withChannelShutdownTimeout(Duration timeout) { + Preconditions.checkArgument(!timeout.isNegative() && !timeout.isZero(), + "withChannelShutdownTimeout must be greater than 0"); + this.channelShutdownTimeout = timeout; + return this; + } + public GrpcTransportBuilder withGrpcKeepAliveTime(Duration time) { if (time == null) { this.grpcKeepAliveTimeMillis = null; diff --git a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java index 4a0edfc48..b747b359b 100644 --- a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.concurrent.ScheduledExecutorService; import tech.ydb.core.grpc.GrpcRequestSettings; @@ -23,13 +24,14 @@ public FixedCallOptionsTransport( AuthCallOptions callOptions, String database, String buildInfo, + Duration channelShutdownTimeout, EndpointRecord endpoint, ManagedChannelFactory channelFactory) { super(endpoint, buildInfo); this.scheduler = scheduler; this.callOptions = callOptions; this.database = database; - this.channel = new GrpcChannel(endpoint, channelFactory); + this.channel = new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java index 7ea557569..b0585d087 100644 --- a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java @@ -51,7 +51,7 @@ public MultiChannelTransport(GrpcTransportBuilder builder, List hos .collect(Collectors.toList()); this.callOptions = new AuthCallOptions(scheduler, endpoints, channelFactory, builder); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler, builder.getChannelShutdownTimeout()); this.endpointPool = new EndpointPool(BalancingSettings.defaultInstance()); this.endpointPool.setNewState(null, Piles.EMPTY, endpoints); } diff --git a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java index b68177117..917553b95 100644 --- a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java @@ -31,7 +31,7 @@ public SingleChannelTransport(GrpcTransportBuilder builder) { logger.info("creating single channel transport with endpoint {}", serverEndpoint); this.database = Strings.nullToEmpty(builder.getDatabase()); - this.channel = new GrpcChannel(serverEndpoint, channelFactory); + this.channel = new GrpcChannel(serverEndpoint, channelFactory, builder.getChannelShutdownTimeout()); this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions( scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder diff --git a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java index dd6410b6f..560ae2344 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java @@ -55,9 +55,9 @@ public YdbTransportImpl(GrpcTransportBuilder builder) { this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions(scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler, builder.getChannelShutdownTimeout()); this.endpointPool = new EndpointPool(balancingSettings); - DiscoveryHandler handler = new DiscoveryHandler(builder.getBuildInfo()); + DiscoveryHandler handler = new DiscoveryHandler(builder.getBuildInfo(), builder.getChannelShutdownTimeout()); this.discovery = new YdbDiscovery(handler, scheduler, database, discoveryTimeout); } @@ -131,9 +131,11 @@ protected void pessimizeEndpoint(EndpointRecord endpoint, String reason) { private class DiscoveryHandler implements YdbDiscovery.Handler { private final String baseBuildInfo; + private final Duration channelShutdownTimeout; - DiscoveryHandler(String buildInfo) { + DiscoveryHandler(String buildInfo, Duration channelShutdownTimeout) { this.baseBuildInfo = buildInfo; + this.channelShutdownTimeout = channelShutdownTimeout; } @Override @@ -156,7 +158,7 @@ public CompletableFuture handleEndpoints(List endpoints public GrpcTransport createDiscoveryTransport() { String buildInfo = Observability.getDiscoveryBuildInfo(baseBuildInfo); return new FixedCallOptionsTransport( - scheduler, callOptions, database, buildInfo, serverEndpoint, channelFactory + scheduler, callOptions, database, buildInfo, channelShutdownTimeout, serverEndpoint, channelFactory ); } } diff --git a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java index 8a7afcf5c..5335234ab 100644 --- a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java +++ b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.auth; +import java.time.Duration; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; @@ -64,6 +65,7 @@ public GrpcTransport createTransport() { new AuthCallOptions(), database, buildInfo, + Duration.ofSeconds(1), endpoints.get(endpointIdx.get()), channelFactory ); diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java index 2e9a1135d..1e6c662a4 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.pool; +import java.time.Duration; import java.util.concurrent.TimeUnit; import io.grpc.Channel; @@ -12,18 +13,17 @@ * @author Nikolay Perfilov */ public final class GrpcChannel implements Runnable { - - /* Channel shutdown waits for finish of active grpc calls, so there must be enough time to complete them all */ - static final long WAIT_FOR_CLOSING_MS = 5000; private static final Logger logger = LoggerFactory.getLogger(GrpcChannel.class); private final EndpointRecord endpoint; private final ManagedChannel channel; + private final Duration shutdownTimeout; - public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory) { + public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory, Duration shutdownTimeout) { try { logger.debug("Creating grpc channel with {}", endpoint); this.endpoint = endpoint; + this.shutdownTimeout = shutdownTimeout; this.channel = factory.newManagedChannel(endpoint.getHost(), endpoint.getPort(), endpoint.getAuthority()); checkState(); } catch (Throwable th) { @@ -49,8 +49,9 @@ public boolean shutdown() { } try { + long deadline = System.nanoTime() + shutdownTimeout.toNanos(); initShutdown(); - return awaitTermination(closingDeadline()); + return awaitTermination(deadline); } catch (InterruptedException e) { logger.warn("transport shutdown interrupted for channel {}: ", endpoint, e); Thread.currentThread().interrupt(); @@ -60,13 +61,6 @@ public boolean shutdown() { } } - /** - * @return the {@link System#nanoTime()} based deadline for the termination of channels shut down now - */ - static long closingDeadline() { - return System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_FOR_CLOSING_MS); - } - /** * Initiates an orderly shutdown: new calls are rejected, but the active ones are allowed to complete. */ diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java index f36a8b1b9..76ebf68c5 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.pool; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -25,10 +26,13 @@ public class GrpcChannelPool { private final Map channels = new ConcurrentHashMap<>(); private final ManagedChannelFactory channelFactory; private final ScheduledExecutorService executor; + private final Duration channelShutdownTimeout; - public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor) { + public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor, + Duration channelShutdownTimeout) { this.channelFactory = channelFactory; this.executor = executor; + this.channelShutdownTimeout = channelShutdownTimeout; } public Set getReadyEndpoints() { @@ -42,7 +46,7 @@ public GrpcChannel getChannel(EndpointRecord endpoint) { return result != null ? result : channels.computeIfAbsent(endpoint.getHostAndPort(), (key) -> { logger.debug("channel {} was not found in pool, creating one...", endpoint.getHostAndPort()); - return new GrpcChannel(endpoint, channelFactory); + return new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); }); } @@ -58,7 +62,7 @@ private CompletableFuture shutdownChannels(Collection chan // instead of waiting for each other channelsList.forEach(GrpcChannel::initShutdown); return CompletableFuture.supplyAsync(() -> { - long deadline = GrpcChannel.closingDeadline(); + long deadline = System.nanoTime() + channelShutdownTimeout.toNanos(); int closed = 0; try { diff --git a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java index 64880f96f..372fdd632 100644 --- a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java +++ b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java @@ -1,5 +1,7 @@ package tech.ydb.core.grpc; +import java.time.Duration; + import org.junit.Assert; import org.junit.Test; @@ -19,6 +21,7 @@ public void defaultValuesTest() { Assert.assertNull(builder.getCert()); Assert.assertEquals(GrpcTransportBuilder.InitMode.SYNC, builder.getInitMode()); Assert.assertNotNull(builder.getManagedChannelFactory()); + Assert.assertEquals(Duration.ofSeconds(5), builder.getChannelShutdownTimeout()); } @Test @@ -51,4 +54,20 @@ public void balancingSettingsTest() { Assert.assertEquals(BalancingSettings.Policy.USE_DETECT_LOCAL_DC, mixed.getPolicy()); Assert.assertNull(mixed.getPreferableLocation()); } + + @Test + public void channelShutdownTimeoutTest() { + GrpcTransportBuilder builder = GrpcTransport.forConnectionString(YDB); + + Exception ex1 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ZERO)); + Exception ex2 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(5).negated())); + + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0", ex1.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0", ex2.getMessage()); + + builder.withChannelShutdownTimeout(Duration.ofHours(1)); + Assert.assertEquals(Duration.ofSeconds(3600), builder.getChannelShutdownTimeout()); + } } diff --git a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java index 9414f5d84..1bc3b818e 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java @@ -299,7 +299,8 @@ public Instant instant() { public GrpcTransport createDiscoveryTransport() { EndpointRecord discovery = new EndpointRecord("unknown", 1234); AuthCallOptions options = new AuthCallOptions(); - return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", discovery, channelFactory); + return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", Duration.ofSeconds(1), + discovery, channelFactory); } @Override diff --git a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java index 42cc0495d..db6d0a4a5 100644 --- a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java +++ b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.pool; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -46,7 +47,7 @@ public void simpleTest() { EndpointRecord e1 = new EndpointRecord("host1", 1234, 10); EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); Assert.assertEquals(0, pool.getChannels().size()); GrpcChannel channel1 = pool.getChannel(e1); @@ -79,7 +80,7 @@ public void removeChannels() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -138,7 +139,7 @@ public void badShutdownTest() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -200,7 +201,7 @@ private GrpcChannelPool poolWithBusyChannels(ScheduledExecutorService executor, Mockito.when(factoryMock.newManagedChannel(Mockito.any(), Mockito.anyInt(), Mockito.isNull())) .thenReturn(c1, c2, c3); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor, Duration.ofSeconds(5)); pool.getChannel(new EndpointRecord("host1", 1234, 10)); pool.getChannel(new EndpointRecord("host1", 1235, 11)); pool.getChannel(new EndpointRecord("host1", 1236, 12)); @@ -226,7 +227,7 @@ public void channelsShutdownInParallelTest() throws InterruptedException { // and they share one deadline, so the last channel waits only for the rest of it Assert.assertEquals(3, awaitTimeouts.size()); - long fullTimeout = TimeUnit.MILLISECONDS.toNanos(GrpcChannel.WAIT_FOR_CLOSING_MS); + long fullTimeout = Duration.ofSeconds(5).toNanos(); long lastTimeout = awaitTimeouts.get(2); Assert.assertTrue("Unexpected timeout " + lastTimeout, lastTimeout <= fullTimeout - 2 * 300_000_000L); } From ccbb0aebb7efa984adb98eb63229eb23ec30fc73 Mon Sep 17 00:00:00 2001 From: Alexandr Gorshenin Date: Sun, 29 Nov 2026 12:29:28 +0000 Subject: [PATCH 08/29] Small fixes --- .../ydb/core/grpc/GrpcTransportBuilder.java | 4 ++-- .../ydb/core/impl/SingleChannelTransport.java | 7 +++++-- .../ydb/core/impl/YdbSchedulerFactory.java | 10 ++++++++-- .../tech/ydb/core/impl/YdbTransportImpl.java | 19 +++++++++++++------ .../tech/ydb/core/impl/auth/GrpcAuthRpc.java | 2 +- .../core/grpc/GrpcTransportBuilderTest.java | 14 ++++++++++---- .../ydb/core/impl/YdbTransportImplTest.java | 2 +- .../core/impl/pool/GrpcChannelPoolTest.java | 1 + 8 files changed, 41 insertions(+), 18 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java index a877bbd00..0e96f129d 100644 --- a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java +++ b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java @@ -361,8 +361,8 @@ public GrpcTransportBuilder withDiscoveryTimeout(long timeout, TimeUnit unit) { } public GrpcTransportBuilder withChannelShutdownTimeout(Duration timeout) { - Preconditions.checkArgument(!timeout.isNegative() && !timeout.isZero(), - "withChannelShutdownTimeout must be greater than 0"); + Preconditions.checkArgument(timeout.compareTo(Duration.ofHours(1)) < 1 && !timeout.isNegative() + && !timeout.isZero(), "withChannelShutdownTimeout must be greater than 0 and less than 1 hour"); this.channelShutdownTimeout = timeout; return this; } diff --git a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java index 917553b95..d50ca14d4 100644 --- a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.Collections; import java.util.concurrent.ScheduledExecutorService; @@ -22,6 +23,7 @@ public class SingleChannelTransport extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final GrpcChannel channel; private final String database; + private final Duration channleShutdownTimeout; private final ScheduledExecutorService scheduler; public SingleChannelTransport(GrpcTransportBuilder builder) { @@ -31,7 +33,8 @@ public SingleChannelTransport(GrpcTransportBuilder builder) { logger.info("creating single channel transport with endpoint {}", serverEndpoint); this.database = Strings.nullToEmpty(builder.getDatabase()); - this.channel = new GrpcChannel(serverEndpoint, channelFactory, builder.getChannelShutdownTimeout()); + this.channleShutdownTimeout = builder.getChannelShutdownTimeout(); + this.channel = new GrpcChannel(serverEndpoint, channelFactory, channleShutdownTimeout); this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions( scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder @@ -52,7 +55,7 @@ public String getDatabase() { protected void shutdown() { channel.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler); + YdbSchedulerFactory.shutdownScheduler(scheduler, channleShutdownTimeout.plusSeconds(5)); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java index 93b782559..830cf7e01 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -38,16 +39,21 @@ public static ScheduledExecutorService createScheduler() { return Executors.newScheduledThreadPool(threads, new YdbThreadFactory()); } + @Deprecated public static boolean shutdownScheduler(ScheduledExecutorService scheduler) { + return shutdownScheduler(scheduler, Duration.ofMillis(WAIT_FOR_SHUTDOWN_MS)); + } + + public static boolean shutdownScheduler(ScheduledExecutorService scheduler, Duration timeout) { try { scheduler.shutdown(); - boolean closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); + boolean closed = scheduler.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown timeout exceeded, terminate"); for (Runnable task: scheduler.shutdownNow()) { logger.warn(" task {} is terminated", task); } - closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); + closed = scheduler.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown problem"); } diff --git a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java index 560ae2344..f3f4fc0b9 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java @@ -37,6 +37,7 @@ public class YdbTransportImpl extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; + private final Duration channelShutdownTimeout; private final YdbDiscovery discovery; private final Tracer tracer; @@ -57,7 +58,9 @@ public YdbTransportImpl(GrpcTransportBuilder builder) { channelFactory, builder); this.channelPool = new GrpcChannelPool(channelFactory, scheduler, builder.getChannelShutdownTimeout()); this.endpointPool = new EndpointPool(balancingSettings); - DiscoveryHandler handler = new DiscoveryHandler(builder.getBuildInfo(), builder.getChannelShutdownTimeout()); + this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); + + DiscoveryHandler handler = new DiscoveryHandler(builder.getBuildInfo()); this.discovery = new YdbDiscovery(handler, scheduler, database, discoveryTimeout); } @@ -84,7 +87,7 @@ protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler); + YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); } @Override @@ -131,11 +134,9 @@ protected void pessimizeEndpoint(EndpointRecord endpoint, String reason) { private class DiscoveryHandler implements YdbDiscovery.Handler { private final String baseBuildInfo; - private final Duration channelShutdownTimeout; - DiscoveryHandler(String buildInfo, Duration channelShutdownTimeout) { + DiscoveryHandler(String buildInfo) { this.baseBuildInfo = buildInfo; - this.channelShutdownTimeout = channelShutdownTimeout; } @Override @@ -158,7 +159,13 @@ public CompletableFuture handleEndpoints(List endpoints public GrpcTransport createDiscoveryTransport() { String buildInfo = Observability.getDiscoveryBuildInfo(baseBuildInfo); return new FixedCallOptionsTransport( - scheduler, callOptions, database, buildInfo, channelShutdownTimeout, serverEndpoint, channelFactory + scheduler, + callOptions, + database, + buildInfo, + Duration.ofSeconds(1), // discovery transport must not use long-life calls + serverEndpoint, + channelFactory ); } } diff --git a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java index 5335234ab..820b66101 100644 --- a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java +++ b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java @@ -65,7 +65,7 @@ public GrpcTransport createTransport() { new AuthCallOptions(), database, buildInfo, - Duration.ofSeconds(1), + Duration.ofSeconds(1), // auth provider transport must not use long-life calls endpoints.get(endpointIdx.get()), channelFactory ); diff --git a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java index 372fdd632..0dd315cad 100644 --- a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java +++ b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java @@ -63,11 +63,17 @@ public void channelShutdownTimeoutTest() { () -> builder.withChannelShutdownTimeout(Duration.ZERO)); Exception ex2 = Assert.assertThrows(IllegalArgumentException.class, () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(5).negated())); + Exception ex3 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(3600).negated())); + Exception ex4 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(3601).negated())); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0", ex1.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0", ex2.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex1.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex2.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex3.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex4.getMessage()); - builder.withChannelShutdownTimeout(Duration.ofHours(1)); - Assert.assertEquals(Duration.ofSeconds(3600), builder.getChannelShutdownTimeout()); + builder.withChannelShutdownTimeout(Duration.ofMinutes(10)); + Assert.assertEquals(Duration.ofSeconds(600), builder.getChannelShutdownTimeout()); } } diff --git a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java index aef1d5259..83e7b7b6f 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java @@ -313,7 +313,7 @@ public void customSchedulerTest() { Assert.assertFalse(scheduler.isShutdown()); Assert.assertFalse(scheduler.isTerminated()); - YdbSchedulerFactory.shutdownScheduler(custom); + YdbSchedulerFactory.shutdownScheduler(custom, Duration.ofSeconds(1)); } @Test diff --git a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java index db6d0a4a5..a79423150 100644 --- a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java +++ b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java @@ -38,6 +38,7 @@ public void setUp() { } @After + @SuppressWarnings("deprecation") public void tearDown() { YdbSchedulerFactory.shutdownScheduler(scheduler); } From 1cf0652e8c1260accc660938fca2698d54b7d012 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Mon, 30 Nov 2026 14:27:05 +0300 Subject: [PATCH 09/29] Fixed channel shutdown timeout in MultiChannelTransport and boundary test --- .../tech/ydb/core/grpc/GrpcTransportBuilder.java | 2 +- .../tech/ydb/core/impl/MultiChannelTransport.java | 7 +++++-- .../ydb/core/impl/SingleChannelTransport.java | 8 ++++---- .../ydb/core/grpc/GrpcTransportBuilderTest.java | 15 +++++++++------ 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java index 0e96f129d..9de5023d2 100644 --- a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java +++ b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java @@ -362,7 +362,7 @@ public GrpcTransportBuilder withDiscoveryTimeout(long timeout, TimeUnit unit) { public GrpcTransportBuilder withChannelShutdownTimeout(Duration timeout) { Preconditions.checkArgument(timeout.compareTo(Duration.ofHours(1)) < 1 && !timeout.isNegative() - && !timeout.isZero(), "withChannelShutdownTimeout must be greater than 0 and less than 1 hour"); + && !timeout.isZero(), "withChannelShutdownTimeout must be greater than 0 and at most 1 hour"); this.channelShutdownTimeout = timeout; return this; } diff --git a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java index b0585d087..eea0984ca 100644 --- a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -35,6 +36,7 @@ public class MultiChannelTransport extends BaseGrpcTransport { private final List endpoints; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; + private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public MultiChannelTransport(GrpcTransportBuilder builder, List hosts) { @@ -51,7 +53,8 @@ public MultiChannelTransport(GrpcTransportBuilder builder, List hos .collect(Collectors.toList()); this.callOptions = new AuthCallOptions(scheduler, endpoints, channelFactory, builder); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler, builder.getChannelShutdownTimeout()); + this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler, channelShutdownTimeout); this.endpointPool = new EndpointPool(BalancingSettings.defaultInstance()); this.endpointPool.setNewState(null, Piles.EMPTY, endpoints); } @@ -70,7 +73,7 @@ public String getDatabase() { protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler); + YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java index d50ca14d4..132d35f37 100644 --- a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java @@ -23,7 +23,7 @@ public class SingleChannelTransport extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final GrpcChannel channel; private final String database; - private final Duration channleShutdownTimeout; + private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public SingleChannelTransport(GrpcTransportBuilder builder) { @@ -33,8 +33,8 @@ public SingleChannelTransport(GrpcTransportBuilder builder) { logger.info("creating single channel transport with endpoint {}", serverEndpoint); this.database = Strings.nullToEmpty(builder.getDatabase()); - this.channleShutdownTimeout = builder.getChannelShutdownTimeout(); - this.channel = new GrpcChannel(serverEndpoint, channelFactory, channleShutdownTimeout); + this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); + this.channel = new GrpcChannel(serverEndpoint, channelFactory, channelShutdownTimeout); this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions( scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder @@ -55,7 +55,7 @@ public String getDatabase() { protected void shutdown() { channel.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler, channleShutdownTimeout.plusSeconds(5)); + YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); } @Override diff --git a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java index 0dd315cad..e43dfff01 100644 --- a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java +++ b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java @@ -64,16 +64,19 @@ public void channelShutdownTimeoutTest() { Exception ex2 = Assert.assertThrows(IllegalArgumentException.class, () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(5).negated())); Exception ex3 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(3600).negated())); + () -> builder.withChannelShutdownTimeout(Duration.ofHours(1).plusNanos(1))); Exception ex4 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(3601).negated())); + () -> builder.withChannelShutdownTimeout(Duration.ofMillis(Long.MAX_VALUE))); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex1.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex2.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex3.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and less than 1 hour", ex4.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex1.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex2.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex3.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex4.getMessage()); builder.withChannelShutdownTimeout(Duration.ofMinutes(10)); Assert.assertEquals(Duration.ofSeconds(600), builder.getChannelShutdownTimeout()); + + builder.withChannelShutdownTimeout(Duration.ofHours(1)); + Assert.assertEquals(Duration.ofHours(1), builder.getChannelShutdownTimeout()); } } From 8b636d0d1f85382f13c68b7d26f24185fa72e211 Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Mon, 30 Nov 2026 15:02:36 +0300 Subject: [PATCH 10/29] Keep 10s as minimal scheduler shutdown wait --- .../main/java/tech/ydb/core/impl/YdbSchedulerFactory.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java index 830cf7e01..d9fd8ca09 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java @@ -26,7 +26,7 @@ * @author Aleksandr Gorshenin */ public class YdbSchedulerFactory { - /** Scheduler waits for closing of channels so this timeout must be greater that GrpcChannel.WAIT_FOR_CLOSING_MS */ + /** Minimal time to wait for scheduler tasks, including the ones closing grpc channels */ private static final long WAIT_FOR_SHUTDOWN_MS = 2 * 5000; private static final Logger logger = LoggerFactory.getLogger(YdbSchedulerFactory.class); @@ -45,15 +45,16 @@ public static boolean shutdownScheduler(ScheduledExecutorService scheduler) { } public static boolean shutdownScheduler(ScheduledExecutorService scheduler, Duration timeout) { + long waitMs = Math.max(timeout.toMillis(), WAIT_FOR_SHUTDOWN_MS); try { scheduler.shutdown(); - boolean closed = scheduler.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS); + boolean closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown timeout exceeded, terminate"); for (Runnable task: scheduler.shutdownNow()) { logger.warn(" task {} is terminated", task); } - closed = scheduler.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS); + closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown problem"); } From cfc3565ea7ed07d3228eb27cdee35d462c368a68 Mon Sep 17 00:00:00 2001 From: Kirill Kurdyukov Date: Mon, 30 Nov 2026 15:52:08 +0300 Subject: [PATCH 11/29] Merge pull request #803 from ydb-platform/histogram-buckets Set latency bucket boundaries for duration histograms --- CHANGELOG.md | 1 + .../java/tech/ydb/core/metrics/Meter.java | 12 ++++++++++++ .../ydb/core/metrics/OpenTelemetryMeter.java | 17 ++++++++++++++++- .../core/metrics/OpenTelemetryMeterTest.java | 19 +++++++++++++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97d40180f..90f512701 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ * 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 * Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately ## 2.5.0 ## diff --git a/core/src/main/java/tech/ydb/core/metrics/Meter.java b/core/src/main/java/tech/ydb/core/metrics/Meter.java index fde4c3fd1..e43d3b9e0 100644 --- a/core/src/main/java/tech/ydb/core/metrics/Meter.java +++ b/core/src/main/java/tech/ydb/core/metrics/Meter.java @@ -1,5 +1,6 @@ package tech.ydb.core.metrics; +import java.util.List; import java.util.function.Consumer; import io.grpc.ExperimentalApi; @@ -16,10 +17,21 @@ default LongCounter createCounter(String name, String unit, String description) return LongCounter.NOOP; } + /** + * Creates a histogram of durations in seconds. {@link OpenTelemetryMeter} uses the OpenTelemetry database + * semantic conventions latency bucket boundaries. + */ default DoubleHistogram createHistogram(String name, String unit, String description) { return DoubleHistogram.NOOP; } + /** + * Creates a histogram with recommended explicit bucket boundaries. + */ + default DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { + return DoubleHistogram.NOOP; + } + /** * Creates a gauge callback without a registration handle. * diff --git a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java index 6f817a769..5c840ddde 100644 --- a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java +++ b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java @@ -1,5 +1,7 @@ package tech.ydb.core.metrics; +import java.util.Arrays; +import java.util.List; import java.util.Objects; import java.util.function.Consumer; @@ -22,6 +24,14 @@ public final class OpenTelemetryMeter implements Meter { private static final String DEFAULT_SCOPE = "tech.ydb.sdk"; + /** + * Latency bucket boundaries in seconds recommended by the OpenTelemetry database semantic conventions for + * {@code db.client.operation.duration}: + * Semantic conventions for database + * client metrics. + */ + private static final List LATENCY_BUCKETS = Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d); + private final io.opentelemetry.api.metrics.Meter meter; private OpenTelemetryMeter(io.opentelemetry.api.metrics.Meter meter) { @@ -52,7 +62,12 @@ public LongCounter createCounter(String name, String unit, String description) { @Override public DoubleHistogram createHistogram(String name, String unit, String description) { - DoubleHistogramBuilder builder = meter.histogramBuilder(name); + return createHistogram(name, unit, description, LATENCY_BUCKETS); + } + + @Override + public DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { + DoubleHistogramBuilder builder = meter.histogramBuilder(name).setExplicitBucketBoundariesAdvice(buckets); if (unit != null) { builder.setUnit(unit); } diff --git a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java index 17287ecf8..58b1d05af 100644 --- a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java +++ b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java @@ -1,6 +1,7 @@ package tech.ydb.core.metrics; import java.io.IOException; +import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; @@ -74,6 +75,24 @@ public void histogramReportsValueAndAttributes() { Assert.assertEquals("my-pool", point.getAttributes().get(POOL)); } + @Test + public void histogramUsesLatencyBucketsByDefault() { + meter.createHistogram("ydb.test.latency", "s", "test latency").record(0.02d); + + HistogramPointData point = single("ydb.test.latency").getHistogramData().getPoints().iterator().next(); + Assert.assertEquals(Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d), point.getBoundaries()); + Assert.assertEquals(Arrays.asList(0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), point.getCounts()); + } + + @Test + public void histogramUsesExplicitBuckets() { + meter.createHistogram("ydb.test.buckets", "{attempt}", "test buckets", Arrays.asList(1d, 2d, 5d)).record(3d); + + HistogramPointData point = single("ydb.test.buckets").getHistogramData().getPoints().iterator().next(); + Assert.assertEquals(Arrays.asList(1d, 2d, 5d), point.getBoundaries()); + Assert.assertEquals(Arrays.asList(0L, 0L, 1L, 0L), point.getCounts()); + } + @Test public void gaugeInvokesCallbackOnCollect() { AtomicLong value = new AtomicLong(7L); From 08605c0cbf97fe0a905c335410b9dcf6f418664f Mon Sep 17 00:00:00 2001 From: Igor Melnichenko Date: Sun, 11 Oct 2026 01:29:21 +0300 Subject: [PATCH 12/29] Background token refresh has no backoff - After a failed refresh, the next getToken() starts another login immediately. - If the auth service is down, logins repeat back-to-back at the request rate. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed background token refresh now retries after 1 s, 2 s, 4 s… up to 1 min. An expired token still triggers a blocking login as before. --- .../ydb/core/auth/BackgroundIdentity.java | 39 ++++++++++++++++--- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java index 048c1ef35..1561c7937 100644 --- a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java +++ b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java @@ -1,6 +1,7 @@ package tech.ydb.core.auth; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.concurrent.CompletableFuture; @@ -19,6 +20,10 @@ public class BackgroundIdentity implements tech.ydb.auth.AuthIdentity { private static final Logger logger = LoggerFactory.getLogger(BackgroundIdentity.class); + // Delays before retrying a failed background update while the current token is still valid + private static final long RETRY_MIN_DELAY_MS = 1_000; + private static final long RETRY_MAX_DELAY_MS = 60_000; + public interface Rpc extends AutoCloseable { class Token { private final String token; @@ -85,6 +90,12 @@ public String getToken() { return state.get().validate(clock.instant()).token(); } + private static Instant nextRetry(Instant now, int failedUpdates) { + // 1s, 2s, 4s, ... up to 1 minute + long delayMs = RETRY_MIN_DELAY_MS << Math.min(failedUpdates - 1, 10); + return now.plus(Duration.ofMillis(Math.min(delayMs, RETRY_MAX_DELAY_MS))); + } + private T unwrap(CompletableFuture future) { try { return future.get(rpc.getTimeoutSeconds(), TimeUnit.SECONDS); @@ -143,10 +154,12 @@ public State validate(Instant now) { private class BackgroundLogin implements State { private final Rpc.Token token; + private final int failedUpdates; private final CompletableFuture future = new CompletableFuture<>(); - BackgroundLogin(Rpc.Token token) { + BackgroundLogin(Rpc.Token token, int failedUpdates) { this.token = token; + this.failedUpdates = failedUpdates; } @Override @@ -172,8 +185,10 @@ public State validate(Instant now) { // If token had already expired, switch to sync mode and wait for finishing return updateState(this, new SyncLogin()).validate(now); } - // else retry background login - return updateState(this, new BackgroundLogin(token)); + + // else retry background login after a delay, every getToken() would retry it immediately otherwise + int failed = failedUpdates + 1; + return updateState(this, new LoggedInState(token, nextRetry(now, failed), failed)); } if (future.isDone()) { @@ -186,13 +201,25 @@ public State validate(Instant now) { private class LoggedInState implements State { private final Rpc.Token token; + private final Instant updateAt; + private final int failedUpdates; LoggedInState(Rpc.Token token) { + this(token, token.updateAt(), 0); + } + + LoggedInState(Rpc.Token token, Instant updateAt, int failedUpdates) { this.token = token; + this.updateAt = updateAt; + this.failedUpdates = failedUpdates; } @Override - public void init() { } + public void init() { + if (failedUpdates > 0) { + logger.warn("background token update failed {} time(s), next attempt at {}", failedUpdates, updateAt); + } + } @Override public String token() { @@ -205,8 +232,8 @@ public State validate(Instant now) { // If token had already expired, switch to sync mode and wait for finishing return updateState(this, new SyncLogin()).validate(now); } - if (now.isAfter(token.updateAt())) { - return updateState(this, new BackgroundLogin(token)); + if (now.isAfter(updateAt)) { + return updateState(this, new BackgroundLogin(token, failedUpdates)); } return this; } From 18b9114ec9af4b10dc9645d628c0be60d4a8aa9b Mon Sep 17 00:00:00 2001 From: Alexandr Gorshenin Date: Wed, 21 Oct 2026 15:16:49 +0100 Subject: [PATCH 13/29] Added random delay to nextRetry --- .../ydb/core/auth/BackgroundIdentity.java | 26 +++++------ .../ydb/core/auth/BackgroundIdentityTest.java | 45 +++++++------------ .../auth/CredentialsAuthProviderTest.java | 37 +-------------- 3 files changed, 31 insertions(+), 77 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java index 1561c7937..02316859f 100644 --- a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java +++ b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java @@ -1,11 +1,11 @@ package tech.ydb.core.auth; import java.time.Clock; -import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; @@ -20,9 +20,9 @@ public class BackgroundIdentity implements tech.ydb.auth.AuthIdentity { private static final Logger logger = LoggerFactory.getLogger(BackgroundIdentity.class); - // Delays before retrying a failed background update while the current token is still valid - private static final long RETRY_MIN_DELAY_MS = 1_000; - private static final long RETRY_MAX_DELAY_MS = 60_000; + // Max backoff will be random delay from 28.8s to 57.6s + private static final long RETRY_BACKOFF_MS = 450; + private static final long RETRY_CEILING = 6; public interface Rpc extends AutoCloseable { class Token { @@ -90,10 +90,10 @@ public String getToken() { return state.get().validate(clock.instant()).token(); } - private static Instant nextRetry(Instant now, int failedUpdates) { - // 1s, 2s, 4s, ... up to 1 minute - long delayMs = RETRY_MIN_DELAY_MS << Math.min(failedUpdates - 1, 10); - return now.plus(Duration.ofMillis(Math.min(delayMs, RETRY_MAX_DELAY_MS))); + private static Instant nextRetry(Instant now, int retryNumber) { + int slots = 1 << Math.min(retryNumber, RETRY_CEILING); + long delay = RETRY_BACKOFF_MS * slots; + return now.plusMillis(delay + ThreadLocalRandom.current().nextLong(delay)); } private T unwrap(CompletableFuture future) { @@ -154,12 +154,12 @@ public State validate(Instant now) { private class BackgroundLogin implements State { private final Rpc.Token token; - private final int failedUpdates; + private final int retryNumber; private final CompletableFuture future = new CompletableFuture<>(); - BackgroundLogin(Rpc.Token token, int failedUpdates) { + BackgroundLogin(Rpc.Token token, int retryNumber) { this.token = token; - this.failedUpdates = failedUpdates; + this.retryNumber = retryNumber; } @Override @@ -187,8 +187,8 @@ public State validate(Instant now) { } // else retry background login after a delay, every getToken() would retry it immediately otherwise - int failed = failedUpdates + 1; - return updateState(this, new LoggedInState(token, nextRetry(now, failed), failed)); + Instant nextUpdateAt = nextRetry(now, retryNumber); + return updateState(this, new LoggedInState(token, nextUpdateAt, retryNumber + 1)); } if (future.isDone()) { diff --git a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java index 4a9ed0221..8c190d793 100644 --- a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java +++ b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java @@ -1,36 +1,33 @@ package tech.ydb.core.auth; import java.time.Clock; -import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; -public class BackgroundIdentityTest { - private final Instant now = Instant.EPOCH; - private final Clock clock = Clock.fixed(now, ZoneId.of("UTC")); - private static class MockedRpc implements BackgroundIdentity.Rpc { - private final CompletableFuture tokenFuture = new CompletableFuture<>(); +public class BackgroundIdentityTest { + private final Clock clock = Mockito.mock(Clock.class); + private final BackgroundIdentity.Rpc rpc = Mockito.mock(BackgroundIdentity.Rpc.class); - @Override - public CompletableFuture getTokenAsync() { - return tokenFuture; - } + // Wednesday, June 1, 2022 00:00:00 UTC + private final Instant now = Instant.ofEpochSecond(1654041600); - @Override - public int getTimeoutSeconds() { - return 60; - } + @Before + public void init() { + Mockito.when(clock.instant()).thenReturn(now); } - @Test(timeout = 30_000) + @Test public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { - MockedRpc rpc = new MockedRpc(); + CompletableFuture f1 = new CompletableFuture<>(); + Mockito.when(rpc.getTokenAsync()).thenReturn(f1); + BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); AtomicReference caught = new AtomicReference<>(); @@ -49,19 +46,11 @@ public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedExceptio reader.join(); Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); - Assert.assertFalse( - "interrupt must not surface as a NullPointerException", - caught.get() instanceof NullPointerException - ); + Assert.assertTrue(caught.get().getClass() == RuntimeException.class); + Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); // the identity must recover once the login completes - rpc.getTokenAsync().complete( - new BackgroundIdentity.Rpc.Token( - "token-value", - now.plus(Duration.ofHours(2)), - now.plus(Duration.ofHours(1)) - ) - ); + f1.complete(new BackgroundIdentity.Rpc.Token("token-value", now.plusSeconds(3600), now.plusSeconds(1800))); Assert.assertEquals("token-value", identity.getToken()); } diff --git a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java index 4ed8bf832..139004612 100644 --- a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java +++ b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java @@ -4,7 +4,6 @@ import java.time.Duration; import java.time.Instant; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicReference; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.Any; @@ -203,42 +202,8 @@ public void syncRefreshTokenTest() { identity.close(); } - @Test - public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { - Mockito.when(clock.instant()).thenReturn(now); - - CompletableFuture> result = new CompletableFuture<>(); - Mockito.when(transport.unaryCall(Mockito.eq(AuthServiceGrpc.getLoginMethod()), Mockito.any(), Mockito.any())) - .thenReturn(result); - - tech.ydb.auth.AuthIdentity identity = createAuth("user", "password"); - - AtomicReference caught = new AtomicReference<>(); - Thread reader = new Thread(() -> { - try { - identity.getToken(); - } catch (Throwable th) { - caught.set(th); - } - }); - - reader.start(); - reader.interrupt(); - reader.join(); - - Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); - Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); - - String token = JwtBuilder.create(now.plus(Duration.ofHours(2)), now); - result.complete(Result.success(responseOk(token))); - - // the identity must recover once the login completes - Assert.assertEquals(token, identity.getToken()); - } - private tech.ydb.auth.AuthIdentity createAuth(String login, String password) { - return new StaticCredentials(clock, login, password) - .createAuthIdentity(rpc); + return new StaticCredentials(clock, login, password).createAuthIdentity(rpc); } private static YdbAuth.LoginResponse responseOk(String token) { From 1cfdf93cf5fcd6e7fe21259e6002989c4eebde0b Mon Sep 17 00:00:00 2001 From: Alexandr Gorshenin Date: Sun, 29 Nov 2026 12:56:12 +0000 Subject: [PATCH 14/29] Added tests for retries --- .../ydb/core/auth/BackgroundIdentityTest.java | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java index 8c190d793..afdc8e6c8 100644 --- a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java +++ b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java @@ -17,10 +17,57 @@ public class BackgroundIdentityTest { // Wednesday, June 1, 2022 00:00:00 UTC private final Instant now = Instant.ofEpochSecond(1654041600); + private final AtomicReference currentTime = new AtomicReference<>(now); @Before public void init() { - Mockito.when(clock.instant()).thenReturn(now); + Mockito.when(clock.instant()).thenAnswer(invocation -> currentTime.get()); + Mockito.when(rpc.getTimeoutSeconds()).thenReturn(10); + } + + @Test + public void retryFailsTest() { + CompletableFuture req1 = new CompletableFuture<>(); + CompletableFuture req2 = new CompletableFuture<>(); + CompletableFuture req3 = new CompletableFuture<>(); + CompletableFuture req4 = new CompletableFuture<>(); + + Mockito.when(rpc.getTokenAsync()) + .thenReturn(req1) + .thenReturn(req2) + .thenReturn(req3) + .thenReturn(req4); + + BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); + req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); + Assert.assertEquals("token-1", identity.getToken()); + + currentTime.set(now.plusMillis(101)); + Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh + req2.completeExceptionally(new RuntimeException("first refresh failed")); + Assert.assertEquals("token-1", identity.getToken()); // schedules a retry 450–899 ms later + Assert.assertEquals("token-1", identity.getToken()); // repeated reads do not retry immediately + Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); + + currentTime.set(now.plusMillis(551)); // minimum delay is 450 ms; the deadline comparison is strict + Assert.assertEquals("token-1", identity.getToken()); + Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); + + currentTime.set(now.plusMillis(1001)); // 900 ms guarantees the first retry deadline has passed + Assert.assertEquals("token-1", identity.getToken()); // starts the second refresh + req3.completeExceptionally(new RuntimeException("second refresh failed")); + Assert.assertEquals("token-1", identity.getToken()); // schedules a 900–1799 ms backoff + Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + + currentTime.set(now.plusMillis(1900)); // 899 ms after failure is below the second backoff minimum + Assert.assertEquals("token-1", identity.getToken()); + Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + + currentTime.set(now.plusMillis(2801)); // 1800 ms guarantees the second retry deadline has passed + Assert.assertEquals("token-1", identity.getToken()); // starts the third refresh + req4.complete(new BackgroundIdentity.Rpc.Token("token-2", now.plusSeconds(7200), now.plusMillis(5000))); + Assert.assertEquals("token-2", identity.getToken()); + Mockito.verify(rpc, Mockito.times(4)).getTokenAsync(); } @Test From 38da2469126551fad29e96ff3578df662d3a2f9a Mon Sep 17 00:00:00 2001 From: KirillKurdyukov Date: Mon, 30 Nov 2026 14:38:53 +0300 Subject: [PATCH 15/29] Count retry backoff from the moment of background token update failure --- .../ydb/core/auth/BackgroundIdentity.java | 18 ++++---------- .../ydb/core/auth/BackgroundIdentityTest.java | 24 +++++++++++++++++++ 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java index 02316859f..02ddc9915 100644 --- a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java +++ b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java @@ -168,7 +168,10 @@ public void init() { if (nextToken != null) { future.complete(new LoggedInState(nextToken)); } else { - future.completeExceptionally(th); + // retry background login after a delay counted from the failure moment, + // every getToken() would retry it immediately otherwise + Instant nextUpdateAt = nextRetry(clock.instant(), retryNumber); + future.complete(new LoggedInState(token, nextUpdateAt, retryNumber + 1)); } }); } @@ -180,19 +183,8 @@ public String token() { @Override public State validate(Instant now) { - if (future.isCompletedExceptionally()) { - if (now.isAfter(token.expiredAt())) { - // If token had already expired, switch to sync mode and wait for finishing - return updateState(this, new SyncLogin()).validate(now); - } - - // else retry background login after a delay, every getToken() would retry it immediately otherwise - Instant nextUpdateAt = nextRetry(now, retryNumber); - return updateState(this, new LoggedInState(token, nextUpdateAt, retryNumber + 1)); - } - if (future.isDone()) { - return updateState(this, future.join()); + return updateState(this, future.join()).validate(now); } return this; diff --git a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java index afdc8e6c8..2b1c69831 100644 --- a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java +++ b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java @@ -71,6 +71,30 @@ public void retryFailsTest() { } @Test + public void retryDelayStartsFromFailureTest() { + CompletableFuture req1 = new CompletableFuture<>(); + CompletableFuture req2 = new CompletableFuture<>(); + CompletableFuture req3 = new CompletableFuture<>(); + + Mockito.when(rpc.getTokenAsync()) + .thenReturn(req1) + .thenReturn(req2) + .thenReturn(req3); + + BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); + req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); + Assert.assertEquals("token-1", identity.getToken()); + + currentTime.set(now.plusMillis(101)); + Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh + req2.completeExceptionally(new RuntimeException("first refresh failed")); + + currentTime.set(now.plusMillis(1101)); // the first retry delay (450-899 ms) has passed since the failure + Assert.assertEquals("token-1", identity.getToken()); // starts the retry immediately + Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + } + + @Test(timeout = 30_000) public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { CompletableFuture f1 = new CompletableFuture<>(); Mockito.when(rpc.getTokenAsync()).thenReturn(f1); From aaa8a8f80e89cb1cb13b24e06883f9e9b75b0a0d Mon Sep 17 00:00:00 2001 From: lebmax Date: Thu, 3 Dec 2026 01:00:36 +0300 Subject: [PATCH 16/29] Fix canceled session acquires with constant-time waiter removal --- .../QueryClientSessionPoolWaiterTest.java | 189 ++++++++++++++++++ .../ydb/table/impl/pool/WaitingQueueTest.java | 60 ++++++ 2 files changed, 249 insertions(+) create mode 100644 query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java diff --git a/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java b/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java new file mode 100644 index 000000000..f1a035349 --- /dev/null +++ b/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java @@ -0,0 +1,189 @@ +package tech.ydb.query.impl; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; +import org.junit.ClassRule; +import org.junit.Test; + +import tech.ydb.core.Result; +import tech.ydb.core.StatusCode; +import tech.ydb.query.QueryClient; +import tech.ydb.query.QuerySession; +import tech.ydb.table.SessionPoolStats; +import tech.ydb.test.junit4.GrpcTransportRule; + +public class QueryClientSessionPoolWaiterTest { + private static final Duration LONG_ACQUIRE_TIMEOUT = Duration.ofMinutes(1); + private static final Duration SHORT_ACQUIRE_TIMEOUT = Duration.ofSeconds(3); + private static final long ASYNC_ASSERTION_TIMEOUT_SECONDS = 10; + private static final int MAX_QUEUE_FILL_ATTEMPTS = 100; + + @ClassRule + public static final GrpcTransportRule YDB = new GrpcTransportRule(); + + @Test + public void cancelledPublicWaiterReleasesSaturatedQueueSlotAndPreservesFifo() throws Exception { + try (QueryClient client = newClient()) { + QuerySession held = awaitSession(client.createSession(LONG_ACQUIRE_TIMEOUT)); + List>> waiters = new ArrayList<>(); + fillWaitingQueue(client, waiters); + + int cancelledIndex = waiters.size() / 2; + CompletableFuture> cancelled = waiters.get(cancelledIndex); + Assert.assertTrue("The selected waiting acquire should be cancelable", cancelled.cancel(true)); + + CompletableFuture> replacement = + acquirePendingWhenQueueHasSlot(client, LONG_ACQUIRE_TIMEOUT); + List>> liveWaiters = without(waiters, cancelledIndex); + liveWaiters.add(replacement); + + assertOnlyHeldSession(client); + Assert.assertNotNull(replacement); + Assert.assertFalse("The replacement must wait while the only session is held", replacement.isDone()); + drainInFifoOrder(client, held, liveWaiters); + } + } + + @Test + public void timedOutPublicWaiterReleasesSaturatedQueueSlot() throws Exception { + try (QueryClient client = newClient()) { + List>> waiters = new ArrayList<>(); + CompletableFuture> replacement = null; + + try (QuerySession held = awaitSession(client.createSession(LONG_ACQUIRE_TIMEOUT))) { + try { + // Put the timeout acquire into the queue before filling the remaining slots. + waiters.add(client.createSession(LONG_ACQUIRE_TIMEOUT)); + CompletableFuture> timedOut = + client.createSession(SHORT_ACQUIRE_TIMEOUT); + waiters.add(timedOut); + + fillWaitingQueue(client, waiters); + Assert.assertFalse("The queue should be observed full before the timed acquire expires", timedOut.isDone()); + + Result timeoutResult = + timedOut.get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertEquals(StatusCode.CLIENT_DEADLINE_EXPIRED, timeoutResult.getStatus().getCode()); + + // The timeout completes the public future before its cancellation callback is + // necessarily observed by this thread. Retry only the expected full-queue rejection + // until the public API admits a new waiter. + replacement = acquirePendingWhenQueueHasSlot(client, LONG_ACQUIRE_TIMEOUT); + Assert.assertNotNull(replacement); + Assert.assertFalse("The replacement must wait while the only session is held", replacement.isDone()); + assertOnlyHeldSession(client); + } finally { + for (CompletableFuture> waiter : waiters) { + waiter.cancel(true); + } + if (replacement != null) { + replacement.cancel(true); + } + } + } + } + } + + private static QueryClient newClient() { + return QueryClient.newClient(YDB) + .sessionPoolMaxSize(1) + .build(); + } + + private static QuerySession awaitSession(CompletableFuture> future) throws Exception { + Result result = future.get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertTrue("Session creation should succeed: " + result.getStatus(), result.isSuccess()); + return result.getValue(); + } + + private static void fillWaitingQueue( + QueryClient client, List>> waiters) { + for (int attempt = 0; attempt < MAX_QUEUE_FILL_ATTEMPTS; attempt += 1) { + CompletableFuture> waiter = client.createSession(LONG_ACQUIRE_TIMEOUT); + if (!waiter.isDone()) { + waiters.add(waiter); + continue; + } + + Result overflow = waiter.join(); + Assert.assertEquals( + "The queue should reject the first acquire beyond its waiting limit", + StatusCode.CLIENT_RESOURCE_EXHAUSTED, + overflow.getStatus().getCode() + ); + Assert.assertFalse("The queue should admit at least one waiter", waiters.isEmpty()); + return; + } + + Assert.fail("The bounded session-pool waiting queue did not reject an overflow acquire"); + } + + private static CompletableFuture> acquirePendingWhenQueueHasSlot( + QueryClient client, Duration timeout) throws InterruptedException { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(ASYNC_ASSERTION_TIMEOUT_SECONDS); + while (System.nanoTime() < deadlineNanos) { + CompletableFuture> candidate = client.createSession(timeout); + if (!candidate.isDone()) { + return candidate; + } + + Result result = candidate.join(); + Assert.assertEquals( + "A saturated queue may reject only with CLIENT_RESOURCE_EXHAUSTED", + StatusCode.CLIENT_RESOURCE_EXHAUSTED, + result.getStatus().getCode() + ); + Thread.sleep(5); + } + + Assert.fail("No new acquire was admitted after a waiting acquire became terminal"); + return null; + } + + private static List>> without( + List>> futures, int excludedIndex) { + List>> result = new ArrayList<>(futures.size() - 1); + for (int i = 0; i < futures.size(); i += 1) { + if (i != excludedIndex) { + result.add(futures.get(i)); + } + } + return result; + } + + private static void assertOnlyHeldSession(QueryClient client) { + SessionPoolStats stats = client.getSessionPoolStats(); + Assert.assertEquals("The only session remains acquired", 1, stats.getAcquiredCount()); + Assert.assertEquals("No session should be idle while the held session is open", 0, stats.getIdleCount()); + } + + private static void drainInFifoOrder( + QueryClient client, + QuerySession held, + List>> waiters) throws Exception { + String heldId = held.getId(); + QuerySession current = held; + for (int i = 0; i < waiters.size(); i += 1) { + current.close(); + + Result result = waiters.get(i).get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertTrue("The next live waiter should receive the released session", result.isSuccess()); + QuerySession next = result.getValue(); + Assert.assertEquals("The pool should hand off the same session in FIFO order", heldId, next.getId()); + + for (int j = i + 1; j < waiters.size(); j += 1) { + Assert.assertFalse("A later waiter must remain pending", waiters.get(j).isDone()); + } + current = next; + } + + current.close(); + Assert.assertEquals(0, client.getSessionPoolStats().getAcquiredCount()); + Assert.assertEquals(1, client.getSessionPoolStats().getIdleCount()); + } +} diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 7e1e25391..922555f21 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -11,6 +11,9 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -819,6 +822,63 @@ public void concurrentCancelAndCloseRemovesAllWaitingAcquiresTest() throws Inter check(rs).requestsCount(0).activeCount(0); } + @Test + public void cancellationRacingWithReleasePreservesWaitingCapacity() throws Exception { + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + for (int attempt = 0; attempt < 32; attempt++) { + checkCancellationRacingWithRelease(workers); + } + } finally { + workers.shutdownNow(); + } + } + + private void checkCancellationRacingWithRelease(ExecutorService workers) throws Exception { + ResourceHandler handler = new ResourceHandler(); + try (WaitingQueue queue = new WaitingQueue<>(handler, 1, 2)) { + CompletableFuture first = pendingFuture(acquire(queue)); + handler.completeNext(); + Resource held = pendingIsReady(first); + CompletableFuture contested = pendingFuture(acquire(queue)); + CompletableFuture surviving = pendingFuture(acquire(queue)); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + Future cancelled = workers.submit(() -> { + ready.countDown(); + Assert.assertTrue(start.await(5, TimeUnit.SECONDS)); + return contested.cancel(false); + }); + Future released = workers.submit(() -> { + ready.countDown(); + Assert.assertTrue(start.await(5, TimeUnit.SECONDS)); + queue.release(held); + return null; + }); + boolean bothReady = ready.await(5, TimeUnit.SECONDS); + start.countDown(); + Assert.assertTrue("Both workers should be ready", bothReady); + released.get(5, TimeUnit.SECONDS); + if (cancelled.get(5, TimeUnit.SECONDS)) { + Assert.assertTrue(contested.isCancelled()); + } else { + Assert.assertSame(held, pendingIsReady(contested)); + queue.release(held); + } + Assert.assertSame(held, pendingIsReady(surviving)); + + CompletableFuture next = pendingFuture(acquire(queue)); + CompletableFuture last = pendingFuture(acquire(queue)); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + queue.release(held); + Assert.assertSame(held, pendingIsReady(next)); + queue.release(held); + Assert.assertSame(held, pendingIsReady(last)); + queue.release(held); + } + } + @Test public void immediatellyCompletedWaitingsTest() { ResourceHandler rs = new ResourceHandler(); From 1e266d696767ccd3e2f97fda76a22ba8e8c688bd Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 4 Dec 2026 13:16:58 +0300 Subject: [PATCH 17/29] Remove cancelled session waiters by key without a shared monitor Release each waiting slot once, including when resize has detached the waiter. Skip removal on normal handoff and cover both concurrent cases. --- .../ydb/table/impl/pool/WaitingAcquires.java | 112 ++++------ .../ydb/table/impl/pool/WaitingQueue.java | 17 +- .../pool/WaitingQueueParallelChurnTest.java | 204 ++++++++++++++++++ .../ydb/table/impl/pool/WaitingQueueTest.java | 57 +++++ 4 files changed, 314 insertions(+), 76 deletions(-) create mode 100644 table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java index 74b9b9a6a..7dffd44ed 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java @@ -1,15 +1,18 @@ package tech.ydb.table.impl.pool; +import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; final class WaitingAcquires { + private final ConcurrentSkipListMap, Waiter> queue = new ConcurrentSkipListMap<>(); + private final AtomicLong sequence = new AtomicLong(); private final AtomicInteger count = new AtomicInteger(); - private Waiter first; - private Waiter last; - int count() { return count.get(); } @@ -18,96 +21,67 @@ boolean compareAndReserve(int expectedCount) { return count.compareAndSet(expectedCount, expectedCount + 1); } - void releaseReservation() { - count.decrementAndGet(); + void releaseReservation(Waiter waiter) { + if (waiter.release()) { + count.decrementAndGet(); + } } Waiter newWaiter(CompletableFuture acquire) { - return new Waiter<>(this, acquire); + return new Waiter<>(this, acquire, sequence.getAndIncrement()); } - synchronized void offerLast(Waiter waiter) { - if (waiter.linked) { - unlink(waiter); - } - waiter.previous = last; - waiter.next = null; - waiter.linked = true; - if (last == null) { - first = waiter; - } else { - last.next = waiter; - } - last = waiter; + void offer(Waiter waiter) { + // The waiter is also the key, so enqueue does not need to box the sequence number. + queue.put(waiter, waiter); } - synchronized void offerFirst(Waiter waiter) { - if (waiter.linked) { - unlink(waiter); - } - waiter.previous = null; - waiter.next = first; - waiter.linked = true; - if (first == null) { - last = waiter; - } else { - first.previous = waiter; - } - first = waiter; - } - - synchronized Waiter pollFirst() { - if (first == null) { - return null; - } - Waiter waiter = first; - unlink(waiter); - // Polling only unlinks; callers decide when to release the reservation. - return waiter; + Waiter pollFirst() { + Map.Entry, Waiter> entry = queue.pollFirstEntry(); + return entry == null ? null : entry.getValue(); } - synchronized boolean remove(Waiter waiter) { - if (!waiter.linked) { + boolean remove(Waiter waiter) { + if (!queue.remove(waiter, waiter)) { return false; } - unlink(waiter); - count.decrementAndGet(); + releaseReservation(waiter); return true; } - private void unlink(Waiter waiter) { - Waiter previous = waiter.previous; - Waiter next = waiter.next; - if (previous == null) { - first = next; - } else { - previous.next = next; - } - if (next == null) { - last = previous; - } else { - next.previous = previous; - } - waiter.previous = null; - waiter.next = null; - waiter.linked = false; - } + static final class Waiter implements Comparable>, BiConsumer { + @SuppressWarnings("rawtypes") + private static final AtomicIntegerFieldUpdater RELEASED = + AtomicIntegerFieldUpdater.newUpdater(Waiter.class, "released"); - static final class Waiter implements BiConsumer { private final WaitingAcquires owner; final CompletableFuture acquire; - private Waiter previous; - private Waiter next; - private boolean linked; + private final long order; + private volatile int released; - private Waiter(WaitingAcquires owner, CompletableFuture acquire) { + private Waiter(WaitingAcquires owner, CompletableFuture acquire, long order) { this.owner = owner; this.acquire = acquire; + this.order = order; + } + + private boolean release() { + return released == 0 && RELEASED.compareAndSet(this, 0, 1); + } + + @Override + public int compareTo(Waiter other) { + return Long.compareUnsigned(order, other.order); } @Override public void accept(T object, Throwable error) { - owner.remove(this); + if (released == 0) { + // A resize can temporarily detach this waiter. Completion still frees its slot. + if (!owner.remove(this)) { + owner.releaseReservation(this); + } + } } } } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index 8c09d3f7c..76700b056 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -245,7 +245,7 @@ private boolean tryToCreateNewWaiting(CompletableFuture acquire) { } WaitingAcquires.Waiter waiter = waitingAcquires.newWaiter(acquire); - waitingAcquires.offerLast(waiter); + waitingAcquires.offer(waiter); acquire.whenComplete(waiter); // close() can run after the count is reserved but before this offer. // In that case clear() cannot see the new entry, so clean it here. @@ -267,7 +267,7 @@ private boolean tryToCompleteWaiting(T object) { WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); while (waiter != null) { guard.init(); - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiter); if (safeAcquireObject(waiter.acquire, object) && !guard.isBroken()) { return true; } @@ -286,16 +286,19 @@ private void checkNextWaitingAcquire() { WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); while (waiter != null && waiter.acquire.isDone()) { - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiter); waiter = waitingAcquires.pollFirst(); } if (waiter != null) { if (tryToCreateNewPending(waiter.acquire)) { - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiter); + } else if (waiter.acquire.isDone()) { + waitingAcquires.releaseReservation(waiter); } else { - waitingAcquires.offerFirst(waiter); - // The future might have completed while it was temporarily removed from the deque. + // Keep the original order when returning an older waiter after a resize. + waitingAcquires.offer(waiter); + // The future might have completed while it was temporarily removed. // Its completion handler cannot remove it in that interval. if (waiter.acquire.isDone()) { waitingAcquires.remove(waiter); @@ -316,7 +319,7 @@ private void clear() { WaitingAcquires.Waiter waiting = waitingAcquires.pollFirst(); while (waiting != null) { - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiting); waiting.acquire.completeExceptionally(new CancellationException("Queue is already closed")); waiting = waitingAcquires.pollFirst(); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java new file mode 100644 index 000000000..7f30412dc --- /dev/null +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java @@ -0,0 +1,204 @@ +package tech.ydb.table.impl.pool; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReferenceArray; + +import org.junit.Assert; +import org.junit.Test; + +public class WaitingQueueParallelChurnTest { + private static final int TIMEOUT_SECONDS = 10; + private static final int PREFIX_WAITERS = 3; + private static final int WORKER_COUNT = 8; + private static final int CHURN_ITERATIONS = 128; + private static final int WAITING_LIMIT = PREFIX_WAITERS + WORKER_COUNT; + + @Test + public void admitsParallelCancelAndReplaceChurnAndPreservesFifo() throws Exception { + CompletableFuture resourceCreation = new CompletableFuture<>(); + WaitingQueue.Handler handler = new WaitingQueue.Handler() { + @Override + public CompletableFuture create() { + return resourceCreation; + } + + @Override + public void destroy(Object object) { + // The queue owns one resource for this test. + } + }; + + WaitingQueue queue = new WaitingQueue<>(handler, 1, WAITING_LIMIT); + ExecutorService workers = Executors.newFixedThreadPool(WORKER_COUNT); + CountDownLatch workersReady = new CountDownLatch(WORKER_COUNT); + CountDownLatch startWorkers = new CountDownLatch(1); + AtomicReferenceArray> workerWaiters = + new AtomicReferenceArray<>(WORKER_COUNT); + AtomicInteger maximumObservedWaitingCount = new AtomicInteger(); + Future[] workerTasks = new Future[WORKER_COUNT]; + Object resource = new Object(); + + try { + CompletableFuture heldAcquire = new CompletableFuture<>(); + queue.acquire(heldAcquire); + Assert.assertTrue("Resource creation should complete", resourceCreation.complete(resource)); + Assert.assertSame("The only resource remains checked out", resource, + heldAcquire.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + List> prefix = new ArrayList<>(); + for (int i = 0; i < PREFIX_WAITERS; i++) { + CompletableFuture waiter = enqueue(queue); + assertWaiting(waiter, "Prefix waiter should be admitted"); + prefix.add(waiter); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + } + + for (int workerId = 0; workerId < WORKER_COUNT; workerId++) { + CompletableFuture initialWaiter = enqueue(queue); + assertWaiting(initialWaiter, "Worker's initial waiter should be admitted"); + workerWaiters.set(workerId, initialWaiter); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + + final int id = workerId; + workerTasks[workerId] = workers.submit(() -> { + workersReady.countDown(); + if (!startWorkers.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("Timed out waiting for the churn start latch"); + } + + CompletableFuture current = workerWaiters.get(id); + for (int i = 0; i < CHURN_ITERATIONS; i++) { + Assert.assertTrue("Canceling the worker's active waiter should succeed", + current.cancel(false)); + + CompletableFuture replacement = new CompletableFuture<>(); + queue.acquire(replacement); + assertWaiting(replacement, "Replacement waiter should be admitted"); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + + current = replacement; + workerWaiters.set(id, current); + } + return null; + }); + } + + Assert.assertEquals("The prefix and workers should fill all waiting slots", + WAITING_LIMIT, queue.getWaitingCount()); + Assert.assertTrue("Workers did not reach the start latch", + workersReady.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + startWorkers.countDown(); + awaitAll(workerTasks); + + Assert.assertEquals("Every worker should retain one final active waiter", + WAITING_LIMIT, queue.getWaitingCount()); + Assert.assertEquals("The observed waiting count should reach but not exceed the limit", + WAITING_LIMIT, maximumObservedWaitingCount.get()); + + List> replacements = new ArrayList<>(); + for (int i = 0; i < WORKER_COUNT; i++) { + CompletableFuture replacement = workerWaiters.get(i); + assertWaiting(replacement, "Final replacement should remain queued"); + replacements.add(replacement); + } + + Object currentResource = resource; + for (int i = 0; i < prefix.size(); i++) { + queue.release(currentResource); + currentResource = prefix.get(i).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertSame("Untouched prefix waiters should receive the resource FIFO", + resource, currentResource); + + for (int later = i + 1; later < prefix.size(); later++) { + Assert.assertFalse("Later prefix waiter must not overtake the current waiter", + prefix.get(later).isDone()); + } + for (CompletableFuture replacement : replacements) { + Assert.assertFalse("Worker replacements must remain behind the untouched prefix", + replacement.isDone()); + } + } + + boolean[] served = new boolean[replacements.size()]; + for (int count = 0; count < replacements.size(); count++) { + queue.release(currentResource); + + int newlyServed = -1; + for (int i = 0; i < replacements.size(); i++) { + if (!served[i] && replacements.get(i).isDone()) { + Assert.assertEquals("One release should serve one replacement", -1, newlyServed); + newlyServed = i; + } + } + + Assert.assertNotEquals("Each release should serve a worker replacement", -1, newlyServed); + currentResource = replacements.get(newlyServed).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertSame("Each replacement should receive the released resource", + resource, currentResource); + served[newlyServed] = true; + } + Assert.assertEquals("All worker replacements should have received the resource", + WORKER_COUNT, countServed(served)); + } finally { + startWorkers.countDown(); + for (Future workerTask : workerTasks) { + if (workerTask != null && !workerTask.isDone()) { + workerTask.cancel(true); + } + } + workers.shutdownNow(); + boolean workersTerminated = workers.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + queue.close(); + if (queue.getUsedCount() > 0) { + queue.release(resource); + } + Assert.assertTrue("Churn workers did not terminate", workersTerminated); + } + } + + private static CompletableFuture enqueue(WaitingQueue queue) { + CompletableFuture acquire = new CompletableFuture<>(); + queue.acquire(acquire); + return acquire; + } + + private static void assertWaiting(CompletableFuture future, String message) { + Assert.assertFalse(message + ": result completed exceptionally", future.isCompletedExceptionally()); + Assert.assertFalse(message + ": result completed before a resource was released", future.isDone()); + } + + private static void recordBoundedWaitingCount(WaitingQueue queue, AtomicInteger maximumObserved) { + int waitingCount = queue.getWaitingCount(); + Assert.assertTrue("Waiting count should stay between zero and the configured limit", + waitingCount >= 0 && waitingCount <= WAITING_LIMIT); + maximumObserved.accumulateAndGet(waitingCount, Math::max); + } + + private static void awaitAll(Future[] tasks) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); + for (Future task : tasks) { + long remaining = deadline - System.nanoTime(); + Assert.assertTrue("Timed out while joining churn workers", remaining > 0); + task.get(remaining, TimeUnit.NANOSECONDS); + } + } + + private static int countServed(boolean[] served) { + int count = 0; + for (boolean value : served) { + if (value) { + count++; + } + } + return count; + } +} diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 922555f21..d0ecfd985 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -694,6 +694,63 @@ public void canceledWaitingAfterRequeueDoesNotConsumeReleasedResourceTest() { queue.close(); } + @Test + public void cancellationWhileResizeHasDequeuedWaiterFreesSlot() throws Exception { + ResourceHandler rs = new ResourceHandler(); + ExecutorService worker = Executors.newSingleThreadExecutor(); + try (WaitingQueue queue = new WaitingQueue<>(rs, 1, 1)) { + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource held = pendingIsReady(first); + + AtomicReference resizeThread = new AtomicReference<>(); + CompletableFuture detached = new CompletableFuture<>(); + CountDownLatch resumeResize = new CountDownLatch(1); + CompletableFuture waiting = new CompletableFuture() { + @Override + public boolean isDone() { + // This is the first check after updateLimits has detached the oldest waiter. + if (Thread.currentThread() == resizeThread.get() && detached.complete(null)) { + try { + Assert.assertTrue("Resize did not resume", resumeResize.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new AssertionError(ex); + } + } + return super.isDone(); + } + }; + queue.acquire(waiting); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + + Future resize = worker.submit(() -> { + resizeThread.set(Thread.currentThread()); + queue.updateLimits(1, 1); + }); + CompletableFuture replacement; + try { + detached.get(5, TimeUnit.SECONDS); + Assert.assertTrue(waiting.cancel(false)); + replacement = new CompletableFuture<>(); + queue.acquire(replacement); + Assert.assertFalse("The replacement should wait for the checked-out resource: " + replacement, + replacement.isDone()); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + } finally { + resumeResize.countDown(); + } + resize.get(5, TimeUnit.SECONDS); + + queue.release(held); + Assert.assertSame(held, pendingIsReady(replacement)); + check(queue).waitingsCount(0); + queue.delete(held); + } finally { + worker.shutdownNow(); + } + } + @Test public void updateLimitsDequeuesOldestWaiterAtFrontTest() { ResourceHandler rs = new ResourceHandler(); From 23fd3c3ef026e1ddc327d2ed9fb1c727ef67123d Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 4 Dec 2026 15:12:16 +0300 Subject: [PATCH 18/29] Merge master --- CHANGELOG.md | 1 - .../ydb/core/auth/BackgroundIdentity.java | 49 +++----- .../ydb/core/grpc/GrpcTransportBuilder.java | 12 -- .../core/impl/FixedCallOptionsTransport.java | 4 +- .../ydb/core/impl/MultiChannelTransport.java | 7 +- .../ydb/core/impl/SingleChannelTransport.java | 7 +- .../ydb/core/impl/YdbSchedulerFactory.java | 13 +- .../tech/ydb/core/impl/YdbTransportImpl.java | 15 +-- .../tech/ydb/core/impl/auth/GrpcAuthRpc.java | 2 - .../tech/ydb/core/impl/pool/GrpcChannel.java | 18 ++- .../ydb/core/impl/pool/GrpcChannelPool.java | 10 +- .../java/tech/ydb/core/metrics/Meter.java | 12 -- .../ydb/core/metrics/OpenTelemetryMeter.java | 17 +-- .../ydb/core/auth/BackgroundIdentityTest.java | 112 ++++-------------- .../auth/CredentialsAuthProviderTest.java | 37 +++++- .../core/grpc/GrpcTransportBuilderTest.java | 28 ----- .../tech/ydb/core/impl/YdbDiscoveryTest.java | 3 +- .../ydb/core/impl/YdbTransportImplTest.java | 2 +- .../core/impl/pool/GrpcChannelPoolTest.java | 12 +- .../core/metrics/OpenTelemetryMeterTest.java | 19 --- .../ydb/table/impl/pool/SessionPoolTest.java | 4 +- .../ydb/topic/description/PartitionInfo.java | 50 +------- 22 files changed, 115 insertions(+), 319 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24c1fe57d..90f512701 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +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 * Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately -* Core: added Meter histograms with explicit bucket boundaries, OpenTelemetryMeter uses OpenTelemetry database latency boundaries by default ## 2.5.0 ## * Core: upgraded to grpc-java v1.82.4 diff --git a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java index 02ddc9915..048c1ef35 100644 --- a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java +++ b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java @@ -5,7 +5,6 @@ import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; @@ -20,10 +19,6 @@ public class BackgroundIdentity implements tech.ydb.auth.AuthIdentity { private static final Logger logger = LoggerFactory.getLogger(BackgroundIdentity.class); - // Max backoff will be random delay from 28.8s to 57.6s - private static final long RETRY_BACKOFF_MS = 450; - private static final long RETRY_CEILING = 6; - public interface Rpc extends AutoCloseable { class Token { private final String token; @@ -90,12 +85,6 @@ public String getToken() { return state.get().validate(clock.instant()).token(); } - private static Instant nextRetry(Instant now, int retryNumber) { - int slots = 1 << Math.min(retryNumber, RETRY_CEILING); - long delay = RETRY_BACKOFF_MS * slots; - return now.plusMillis(delay + ThreadLocalRandom.current().nextLong(delay)); - } - private T unwrap(CompletableFuture future) { try { return future.get(rpc.getTimeoutSeconds(), TimeUnit.SECONDS); @@ -154,12 +143,10 @@ public State validate(Instant now) { private class BackgroundLogin implements State { private final Rpc.Token token; - private final int retryNumber; private final CompletableFuture future = new CompletableFuture<>(); - BackgroundLogin(Rpc.Token token, int retryNumber) { + BackgroundLogin(Rpc.Token token) { this.token = token; - this.retryNumber = retryNumber; } @Override @@ -168,10 +155,7 @@ public void init() { if (nextToken != null) { future.complete(new LoggedInState(nextToken)); } else { - // retry background login after a delay counted from the failure moment, - // every getToken() would retry it immediately otherwise - Instant nextUpdateAt = nextRetry(clock.instant(), retryNumber); - future.complete(new LoggedInState(token, nextUpdateAt, retryNumber + 1)); + future.completeExceptionally(th); } }); } @@ -183,8 +167,17 @@ public String token() { @Override public State validate(Instant now) { + if (future.isCompletedExceptionally()) { + if (now.isAfter(token.expiredAt())) { + // If token had already expired, switch to sync mode and wait for finishing + return updateState(this, new SyncLogin()).validate(now); + } + // else retry background login + return updateState(this, new BackgroundLogin(token)); + } + if (future.isDone()) { - return updateState(this, future.join()).validate(now); + return updateState(this, future.join()); } return this; @@ -193,25 +186,13 @@ public State validate(Instant now) { private class LoggedInState implements State { private final Rpc.Token token; - private final Instant updateAt; - private final int failedUpdates; LoggedInState(Rpc.Token token) { - this(token, token.updateAt(), 0); - } - - LoggedInState(Rpc.Token token, Instant updateAt, int failedUpdates) { this.token = token; - this.updateAt = updateAt; - this.failedUpdates = failedUpdates; } @Override - public void init() { - if (failedUpdates > 0) { - logger.warn("background token update failed {} time(s), next attempt at {}", failedUpdates, updateAt); - } - } + public void init() { } @Override public String token() { @@ -224,8 +205,8 @@ public State validate(Instant now) { // If token had already expired, switch to sync mode and wait for finishing return updateState(this, new SyncLogin()).validate(now); } - if (now.isAfter(updateAt)) { - return updateState(this, new BackgroundLogin(token, failedUpdates)); + if (now.isAfter(token.updateAt())) { + return updateState(this, new BackgroundLogin(token)); } return this; } diff --git a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java index 9de5023d2..a014bf782 100644 --- a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java +++ b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java @@ -86,7 +86,6 @@ public enum InitMode { private AuthRpcProvider authProvider = NopAuthProvider.INSTANCE; private long readTimeoutMillis = 0; private long discoveryTimeoutMillis = 60_000; - private Duration channelShutdownTimeout = Duration.ofSeconds(5); private boolean useDefaultGrpcResolver = false; private GrpcCompression compression = GrpcCompression.NO_COMPRESSION; private InitMode initMode = InitMode.SYNC; @@ -192,10 +191,6 @@ public long getDiscoveryTimeoutMillis() { return discoveryTimeoutMillis; } - public Duration getChannelShutdownTimeout() { - return channelShutdownTimeout; - } - public GrpcCompression getGrpcCompression() { return compression; } @@ -360,13 +355,6 @@ public GrpcTransportBuilder withDiscoveryTimeout(long timeout, TimeUnit unit) { return this; } - public GrpcTransportBuilder withChannelShutdownTimeout(Duration timeout) { - Preconditions.checkArgument(timeout.compareTo(Duration.ofHours(1)) < 1 && !timeout.isNegative() - && !timeout.isZero(), "withChannelShutdownTimeout must be greater than 0 and at most 1 hour"); - this.channelShutdownTimeout = timeout; - return this; - } - public GrpcTransportBuilder withGrpcKeepAliveTime(Duration time) { if (time == null) { this.grpcKeepAliveTimeMillis = null; diff --git a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java index b747b359b..4a0edfc48 100644 --- a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.concurrent.ScheduledExecutorService; import tech.ydb.core.grpc.GrpcRequestSettings; @@ -24,14 +23,13 @@ public FixedCallOptionsTransport( AuthCallOptions callOptions, String database, String buildInfo, - Duration channelShutdownTimeout, EndpointRecord endpoint, ManagedChannelFactory channelFactory) { super(endpoint, buildInfo); this.scheduler = scheduler; this.callOptions = callOptions; this.database = database; - this.channel = new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); + this.channel = new GrpcChannel(endpoint, channelFactory); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java index eea0984ca..7ea557569 100644 --- a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -36,7 +35,6 @@ public class MultiChannelTransport extends BaseGrpcTransport { private final List endpoints; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; - private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public MultiChannelTransport(GrpcTransportBuilder builder, List hosts) { @@ -53,8 +51,7 @@ public MultiChannelTransport(GrpcTransportBuilder builder, List hos .collect(Collectors.toList()); this.callOptions = new AuthCallOptions(scheduler, endpoints, channelFactory, builder); - this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler, channelShutdownTimeout); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler); this.endpointPool = new EndpointPool(BalancingSettings.defaultInstance()); this.endpointPool.setNewState(null, Piles.EMPTY, endpoints); } @@ -73,7 +70,7 @@ public String getDatabase() { protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); + YdbSchedulerFactory.shutdownScheduler(scheduler); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java index 132d35f37..b68177117 100644 --- a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.Collections; import java.util.concurrent.ScheduledExecutorService; @@ -23,7 +22,6 @@ public class SingleChannelTransport extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final GrpcChannel channel; private final String database; - private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public SingleChannelTransport(GrpcTransportBuilder builder) { @@ -33,8 +31,7 @@ public SingleChannelTransport(GrpcTransportBuilder builder) { logger.info("creating single channel transport with endpoint {}", serverEndpoint); this.database = Strings.nullToEmpty(builder.getDatabase()); - this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); - this.channel = new GrpcChannel(serverEndpoint, channelFactory, channelShutdownTimeout); + this.channel = new GrpcChannel(serverEndpoint, channelFactory); this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions( scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder @@ -55,7 +52,7 @@ public String getDatabase() { protected void shutdown() { channel.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); + YdbSchedulerFactory.shutdownScheduler(scheduler); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java index d9fd8ca09..93b782559 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -26,7 +25,7 @@ * @author Aleksandr Gorshenin */ public class YdbSchedulerFactory { - /** Minimal time to wait for scheduler tasks, including the ones closing grpc channels */ + /** Scheduler waits for closing of channels so this timeout must be greater that GrpcChannel.WAIT_FOR_CLOSING_MS */ private static final long WAIT_FOR_SHUTDOWN_MS = 2 * 5000; private static final Logger logger = LoggerFactory.getLogger(YdbSchedulerFactory.class); @@ -39,22 +38,16 @@ public static ScheduledExecutorService createScheduler() { return Executors.newScheduledThreadPool(threads, new YdbThreadFactory()); } - @Deprecated public static boolean shutdownScheduler(ScheduledExecutorService scheduler) { - return shutdownScheduler(scheduler, Duration.ofMillis(WAIT_FOR_SHUTDOWN_MS)); - } - - public static boolean shutdownScheduler(ScheduledExecutorService scheduler, Duration timeout) { - long waitMs = Math.max(timeout.toMillis(), WAIT_FOR_SHUTDOWN_MS); try { scheduler.shutdown(); - boolean closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); + boolean closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown timeout exceeded, terminate"); for (Runnable task: scheduler.shutdownNow()) { logger.warn(" task {} is terminated", task); } - closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); + closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown problem"); } diff --git a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java index f3f4fc0b9..dd6410b6f 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java @@ -37,7 +37,6 @@ public class YdbTransportImpl extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; - private final Duration channelShutdownTimeout; private final YdbDiscovery discovery; private final Tracer tracer; @@ -56,10 +55,8 @@ public YdbTransportImpl(GrpcTransportBuilder builder) { this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions(scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler, builder.getChannelShutdownTimeout()); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler); this.endpointPool = new EndpointPool(balancingSettings); - this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); - DiscoveryHandler handler = new DiscoveryHandler(builder.getBuildInfo()); this.discovery = new YdbDiscovery(handler, scheduler, database, discoveryTimeout); } @@ -87,7 +84,7 @@ protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); + YdbSchedulerFactory.shutdownScheduler(scheduler); } @Override @@ -159,13 +156,7 @@ public CompletableFuture handleEndpoints(List endpoints public GrpcTransport createDiscoveryTransport() { String buildInfo = Observability.getDiscoveryBuildInfo(baseBuildInfo); return new FixedCallOptionsTransport( - scheduler, - callOptions, - database, - buildInfo, - Duration.ofSeconds(1), // discovery transport must not use long-life calls - serverEndpoint, - channelFactory + scheduler, callOptions, database, buildInfo, serverEndpoint, channelFactory ); } } diff --git a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java index 820b66101..8a7afcf5c 100644 --- a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java +++ b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.auth; -import java.time.Duration; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; @@ -65,7 +64,6 @@ public GrpcTransport createTransport() { new AuthCallOptions(), database, buildInfo, - Duration.ofSeconds(1), // auth provider transport must not use long-life calls endpoints.get(endpointIdx.get()), channelFactory ); diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java index 1e6c662a4..2e9a1135d 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.pool; -import java.time.Duration; import java.util.concurrent.TimeUnit; import io.grpc.Channel; @@ -13,17 +12,18 @@ * @author Nikolay Perfilov */ public final class GrpcChannel implements Runnable { + + /* Channel shutdown waits for finish of active grpc calls, so there must be enough time to complete them all */ + static final long WAIT_FOR_CLOSING_MS = 5000; private static final Logger logger = LoggerFactory.getLogger(GrpcChannel.class); private final EndpointRecord endpoint; private final ManagedChannel channel; - private final Duration shutdownTimeout; - public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory, Duration shutdownTimeout) { + public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory) { try { logger.debug("Creating grpc channel with {}", endpoint); this.endpoint = endpoint; - this.shutdownTimeout = shutdownTimeout; this.channel = factory.newManagedChannel(endpoint.getHost(), endpoint.getPort(), endpoint.getAuthority()); checkState(); } catch (Throwable th) { @@ -49,9 +49,8 @@ public boolean shutdown() { } try { - long deadline = System.nanoTime() + shutdownTimeout.toNanos(); initShutdown(); - return awaitTermination(deadline); + return awaitTermination(closingDeadline()); } catch (InterruptedException e) { logger.warn("transport shutdown interrupted for channel {}: ", endpoint, e); Thread.currentThread().interrupt(); @@ -61,6 +60,13 @@ public boolean shutdown() { } } + /** + * @return the {@link System#nanoTime()} based deadline for the termination of channels shut down now + */ + static long closingDeadline() { + return System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_FOR_CLOSING_MS); + } + /** * Initiates an orderly shutdown: new calls are rejected, but the active ones are allowed to complete. */ diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java index 76ebf68c5..f36a8b1b9 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.pool; -import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -26,13 +25,10 @@ public class GrpcChannelPool { private final Map channels = new ConcurrentHashMap<>(); private final ManagedChannelFactory channelFactory; private final ScheduledExecutorService executor; - private final Duration channelShutdownTimeout; - public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor, - Duration channelShutdownTimeout) { + public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor) { this.channelFactory = channelFactory; this.executor = executor; - this.channelShutdownTimeout = channelShutdownTimeout; } public Set getReadyEndpoints() { @@ -46,7 +42,7 @@ public GrpcChannel getChannel(EndpointRecord endpoint) { return result != null ? result : channels.computeIfAbsent(endpoint.getHostAndPort(), (key) -> { logger.debug("channel {} was not found in pool, creating one...", endpoint.getHostAndPort()); - return new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); + return new GrpcChannel(endpoint, channelFactory); }); } @@ -62,7 +58,7 @@ private CompletableFuture shutdownChannels(Collection chan // instead of waiting for each other channelsList.forEach(GrpcChannel::initShutdown); return CompletableFuture.supplyAsync(() -> { - long deadline = System.nanoTime() + channelShutdownTimeout.toNanos(); + long deadline = GrpcChannel.closingDeadline(); int closed = 0; try { diff --git a/core/src/main/java/tech/ydb/core/metrics/Meter.java b/core/src/main/java/tech/ydb/core/metrics/Meter.java index e43d3b9e0..fde4c3fd1 100644 --- a/core/src/main/java/tech/ydb/core/metrics/Meter.java +++ b/core/src/main/java/tech/ydb/core/metrics/Meter.java @@ -1,6 +1,5 @@ package tech.ydb.core.metrics; -import java.util.List; import java.util.function.Consumer; import io.grpc.ExperimentalApi; @@ -17,21 +16,10 @@ default LongCounter createCounter(String name, String unit, String description) return LongCounter.NOOP; } - /** - * Creates a histogram of durations in seconds. {@link OpenTelemetryMeter} uses the OpenTelemetry database - * semantic conventions latency bucket boundaries. - */ default DoubleHistogram createHistogram(String name, String unit, String description) { return DoubleHistogram.NOOP; } - /** - * Creates a histogram with recommended explicit bucket boundaries. - */ - default DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { - return DoubleHistogram.NOOP; - } - /** * Creates a gauge callback without a registration handle. * diff --git a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java index 5c840ddde..6f817a769 100644 --- a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java +++ b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java @@ -1,7 +1,5 @@ package tech.ydb.core.metrics; -import java.util.Arrays; -import java.util.List; import java.util.Objects; import java.util.function.Consumer; @@ -24,14 +22,6 @@ public final class OpenTelemetryMeter implements Meter { private static final String DEFAULT_SCOPE = "tech.ydb.sdk"; - /** - * Latency bucket boundaries in seconds recommended by the OpenTelemetry database semantic conventions for - * {@code db.client.operation.duration}: - * Semantic conventions for database - * client metrics. - */ - private static final List LATENCY_BUCKETS = Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d); - private final io.opentelemetry.api.metrics.Meter meter; private OpenTelemetryMeter(io.opentelemetry.api.metrics.Meter meter) { @@ -62,12 +52,7 @@ public LongCounter createCounter(String name, String unit, String description) { @Override public DoubleHistogram createHistogram(String name, String unit, String description) { - return createHistogram(name, unit, description, LATENCY_BUCKETS); - } - - @Override - public DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { - DoubleHistogramBuilder builder = meter.histogramBuilder(name).setExplicitBucketBoundariesAdvice(buckets); + DoubleHistogramBuilder builder = meter.histogramBuilder(name); if (unit != null) { builder.setUnit(unit); } diff --git a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java index 2b1c69831..4a9ed0221 100644 --- a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java +++ b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java @@ -1,104 +1,36 @@ package tech.ydb.core.auth; import java.time.Clock; +import java.time.Duration; import java.time.Instant; +import java.time.ZoneId; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import org.mockito.Mockito; - public class BackgroundIdentityTest { - private final Clock clock = Mockito.mock(Clock.class); - private final BackgroundIdentity.Rpc rpc = Mockito.mock(BackgroundIdentity.Rpc.class); - - // Wednesday, June 1, 2022 00:00:00 UTC - private final Instant now = Instant.ofEpochSecond(1654041600); - private final AtomicReference currentTime = new AtomicReference<>(now); - - @Before - public void init() { - Mockito.when(clock.instant()).thenAnswer(invocation -> currentTime.get()); - Mockito.when(rpc.getTimeoutSeconds()).thenReturn(10); - } - - @Test - public void retryFailsTest() { - CompletableFuture req1 = new CompletableFuture<>(); - CompletableFuture req2 = new CompletableFuture<>(); - CompletableFuture req3 = new CompletableFuture<>(); - CompletableFuture req4 = new CompletableFuture<>(); - - Mockito.when(rpc.getTokenAsync()) - .thenReturn(req1) - .thenReturn(req2) - .thenReturn(req3) - .thenReturn(req4); - - BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); - req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); - Assert.assertEquals("token-1", identity.getToken()); - - currentTime.set(now.plusMillis(101)); - Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh - req2.completeExceptionally(new RuntimeException("first refresh failed")); - Assert.assertEquals("token-1", identity.getToken()); // schedules a retry 450–899 ms later - Assert.assertEquals("token-1", identity.getToken()); // repeated reads do not retry immediately - Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); + private final Instant now = Instant.EPOCH; + private final Clock clock = Clock.fixed(now, ZoneId.of("UTC")); - currentTime.set(now.plusMillis(551)); // minimum delay is 450 ms; the deadline comparison is strict - Assert.assertEquals("token-1", identity.getToken()); - Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); + private static class MockedRpc implements BackgroundIdentity.Rpc { + private final CompletableFuture tokenFuture = new CompletableFuture<>(); - currentTime.set(now.plusMillis(1001)); // 900 ms guarantees the first retry deadline has passed - Assert.assertEquals("token-1", identity.getToken()); // starts the second refresh - req3.completeExceptionally(new RuntimeException("second refresh failed")); - Assert.assertEquals("token-1", identity.getToken()); // schedules a 900–1799 ms backoff - Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + @Override + public CompletableFuture getTokenAsync() { + return tokenFuture; + } - currentTime.set(now.plusMillis(1900)); // 899 ms after failure is below the second backoff minimum - Assert.assertEquals("token-1", identity.getToken()); - Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); - - currentTime.set(now.plusMillis(2801)); // 1800 ms guarantees the second retry deadline has passed - Assert.assertEquals("token-1", identity.getToken()); // starts the third refresh - req4.complete(new BackgroundIdentity.Rpc.Token("token-2", now.plusSeconds(7200), now.plusMillis(5000))); - Assert.assertEquals("token-2", identity.getToken()); - Mockito.verify(rpc, Mockito.times(4)).getTokenAsync(); - } - - @Test - public void retryDelayStartsFromFailureTest() { - CompletableFuture req1 = new CompletableFuture<>(); - CompletableFuture req2 = new CompletableFuture<>(); - CompletableFuture req3 = new CompletableFuture<>(); - - Mockito.when(rpc.getTokenAsync()) - .thenReturn(req1) - .thenReturn(req2) - .thenReturn(req3); - - BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); - req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); - Assert.assertEquals("token-1", identity.getToken()); - - currentTime.set(now.plusMillis(101)); - Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh - req2.completeExceptionally(new RuntimeException("first refresh failed")); - - currentTime.set(now.plusMillis(1101)); // the first retry delay (450-899 ms) has passed since the failure - Assert.assertEquals("token-1", identity.getToken()); // starts the retry immediately - Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + @Override + public int getTimeoutSeconds() { + return 60; + } } @Test(timeout = 30_000) public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { - CompletableFuture f1 = new CompletableFuture<>(); - Mockito.when(rpc.getTokenAsync()).thenReturn(f1); - + MockedRpc rpc = new MockedRpc(); BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); AtomicReference caught = new AtomicReference<>(); @@ -117,11 +49,19 @@ public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedExceptio reader.join(); Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); - Assert.assertTrue(caught.get().getClass() == RuntimeException.class); - Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); + Assert.assertFalse( + "interrupt must not surface as a NullPointerException", + caught.get() instanceof NullPointerException + ); // the identity must recover once the login completes - f1.complete(new BackgroundIdentity.Rpc.Token("token-value", now.plusSeconds(3600), now.plusSeconds(1800))); + rpc.getTokenAsync().complete( + new BackgroundIdentity.Rpc.Token( + "token-value", + now.plus(Duration.ofHours(2)), + now.plus(Duration.ofHours(1)) + ) + ); Assert.assertEquals("token-value", identity.getToken()); } diff --git a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java index 139004612..4ed8bf832 100644 --- a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java +++ b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.time.Instant; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicReference; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.Any; @@ -202,8 +203,42 @@ public void syncRefreshTokenTest() { identity.close(); } + @Test + public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { + Mockito.when(clock.instant()).thenReturn(now); + + CompletableFuture> result = new CompletableFuture<>(); + Mockito.when(transport.unaryCall(Mockito.eq(AuthServiceGrpc.getLoginMethod()), Mockito.any(), Mockito.any())) + .thenReturn(result); + + tech.ydb.auth.AuthIdentity identity = createAuth("user", "password"); + + AtomicReference caught = new AtomicReference<>(); + Thread reader = new Thread(() -> { + try { + identity.getToken(); + } catch (Throwable th) { + caught.set(th); + } + }); + + reader.start(); + reader.interrupt(); + reader.join(); + + Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); + Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); + + String token = JwtBuilder.create(now.plus(Duration.ofHours(2)), now); + result.complete(Result.success(responseOk(token))); + + // the identity must recover once the login completes + Assert.assertEquals(token, identity.getToken()); + } + private tech.ydb.auth.AuthIdentity createAuth(String login, String password) { - return new StaticCredentials(clock, login, password).createAuthIdentity(rpc); + return new StaticCredentials(clock, login, password) + .createAuthIdentity(rpc); } private static YdbAuth.LoginResponse responseOk(String token) { diff --git a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java index e43dfff01..64880f96f 100644 --- a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java +++ b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java @@ -1,7 +1,5 @@ package tech.ydb.core.grpc; -import java.time.Duration; - import org.junit.Assert; import org.junit.Test; @@ -21,7 +19,6 @@ public void defaultValuesTest() { Assert.assertNull(builder.getCert()); Assert.assertEquals(GrpcTransportBuilder.InitMode.SYNC, builder.getInitMode()); Assert.assertNotNull(builder.getManagedChannelFactory()); - Assert.assertEquals(Duration.ofSeconds(5), builder.getChannelShutdownTimeout()); } @Test @@ -54,29 +51,4 @@ public void balancingSettingsTest() { Assert.assertEquals(BalancingSettings.Policy.USE_DETECT_LOCAL_DC, mixed.getPolicy()); Assert.assertNull(mixed.getPreferableLocation()); } - - @Test - public void channelShutdownTimeoutTest() { - GrpcTransportBuilder builder = GrpcTransport.forConnectionString(YDB); - - Exception ex1 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ZERO)); - Exception ex2 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(5).negated())); - Exception ex3 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofHours(1).plusNanos(1))); - Exception ex4 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofMillis(Long.MAX_VALUE))); - - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex1.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex2.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex3.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex4.getMessage()); - - builder.withChannelShutdownTimeout(Duration.ofMinutes(10)); - Assert.assertEquals(Duration.ofSeconds(600), builder.getChannelShutdownTimeout()); - - builder.withChannelShutdownTimeout(Duration.ofHours(1)); - Assert.assertEquals(Duration.ofHours(1), builder.getChannelShutdownTimeout()); - } } diff --git a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java index 1bc3b818e..9414f5d84 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java @@ -299,8 +299,7 @@ public Instant instant() { public GrpcTransport createDiscoveryTransport() { EndpointRecord discovery = new EndpointRecord("unknown", 1234); AuthCallOptions options = new AuthCallOptions(); - return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", Duration.ofSeconds(1), - discovery, channelFactory); + return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", discovery, channelFactory); } @Override diff --git a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java index 83e7b7b6f..aef1d5259 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java @@ -313,7 +313,7 @@ public void customSchedulerTest() { Assert.assertFalse(scheduler.isShutdown()); Assert.assertFalse(scheduler.isTerminated()); - YdbSchedulerFactory.shutdownScheduler(custom, Duration.ofSeconds(1)); + YdbSchedulerFactory.shutdownScheduler(custom); } @Test diff --git a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java index a79423150..42cc0495d 100644 --- a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java +++ b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.pool; -import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -38,7 +37,6 @@ public void setUp() { } @After - @SuppressWarnings("deprecation") public void tearDown() { YdbSchedulerFactory.shutdownScheduler(scheduler); } @@ -48,7 +46,7 @@ public void simpleTest() { EndpointRecord e1 = new EndpointRecord("host1", 1234, 10); EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); Assert.assertEquals(0, pool.getChannels().size()); GrpcChannel channel1 = pool.getChannel(e1); @@ -81,7 +79,7 @@ public void removeChannels() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -140,7 +138,7 @@ public void badShutdownTest() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -202,7 +200,7 @@ private GrpcChannelPool poolWithBusyChannels(ScheduledExecutorService executor, Mockito.when(factoryMock.newManagedChannel(Mockito.any(), Mockito.anyInt(), Mockito.isNull())) .thenReturn(c1, c2, c3); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor); pool.getChannel(new EndpointRecord("host1", 1234, 10)); pool.getChannel(new EndpointRecord("host1", 1235, 11)); pool.getChannel(new EndpointRecord("host1", 1236, 12)); @@ -228,7 +226,7 @@ public void channelsShutdownInParallelTest() throws InterruptedException { // and they share one deadline, so the last channel waits only for the rest of it Assert.assertEquals(3, awaitTimeouts.size()); - long fullTimeout = Duration.ofSeconds(5).toNanos(); + long fullTimeout = TimeUnit.MILLISECONDS.toNanos(GrpcChannel.WAIT_FOR_CLOSING_MS); long lastTimeout = awaitTimeouts.get(2); Assert.assertTrue("Unexpected timeout " + lastTimeout, lastTimeout <= fullTimeout - 2 * 300_000_000L); } diff --git a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java index 58b1d05af..17287ecf8 100644 --- a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java +++ b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java @@ -1,7 +1,6 @@ package tech.ydb.core.metrics; import java.io.IOException; -import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; @@ -75,24 +74,6 @@ public void histogramReportsValueAndAttributes() { Assert.assertEquals("my-pool", point.getAttributes().get(POOL)); } - @Test - public void histogramUsesLatencyBucketsByDefault() { - meter.createHistogram("ydb.test.latency", "s", "test latency").record(0.02d); - - HistogramPointData point = single("ydb.test.latency").getHistogramData().getPoints().iterator().next(); - Assert.assertEquals(Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d), point.getBoundaries()); - Assert.assertEquals(Arrays.asList(0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), point.getCounts()); - } - - @Test - public void histogramUsesExplicitBuckets() { - meter.createHistogram("ydb.test.buckets", "{attempt}", "test buckets", Arrays.asList(1d, 2d, 5d)).record(3d); - - HistogramPointData point = single("ydb.test.buckets").getHistogramData().getPoints().iterator().next(); - Assert.assertEquals(Arrays.asList(1d, 2d, 5d), point.getBoundaries()); - Assert.assertEquals(Arrays.asList(0L, 0L, 1L, 0L), point.getCounts()); - } - @Test public void gaugeInvokesCallbackOnCollect() { AtomicLong value = new AtomicLong(7L); diff --git a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java index e38e72d28..d8730e621 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java @@ -104,7 +104,7 @@ public void increaseLimitsTest() { tableRpc.check().sessionRequests(1); check(pool).idle(0).acquired(0).pending(1).size(0, 1).totalClient(0, 0).totalServer(1, 0, 0, 0); - // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue + // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue for (int i = 0; i < wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } @@ -149,7 +149,7 @@ public void decreaseLimitsTest() { tableRpc.check().sessionRequests(2); check(pool).idle(0).acquired(0).pending(2).size(0, 2).totalClient(0, 0).totalServer(2, 0, 0, 0); - // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue + // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue for (int i = 0; i < 2 * wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } diff --git a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java index ce2b8bd18..0f7474210 100644 --- a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java +++ b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java @@ -6,7 +6,6 @@ import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; -import com.google.protobuf.ByteString; import tech.ydb.proto.topic.YdbTopic; @@ -19,11 +18,6 @@ public class PartitionInfo { private final List childPartitionIds; private final List parentPartitionIds; private final PartitionStats partitionStats; - private final boolean keyRange; - @Nullable - private final ByteString fromBound; - @Nullable - private final ByteString toBound; public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.partitionId = info.getPartitionId(); @@ -31,10 +25,6 @@ public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.childPartitionIds = ImmutableList.copyOf(info.getChildPartitionIdsList()); this.parentPartitionIds = ImmutableList.copyOf(info.getParentPartitionIdsList()); this.partitionStats = info.hasPartitionStats() ? new PartitionStats(info.getPartitionStats()) : null; - this.keyRange = info.hasKeyRange(); - YdbTopic.PartitionKeyRange range = info.getKeyRange(); - this.fromBound = range.hasFromBound() ? range.getFromBound() : null; - this.toBound = range.hasToBound() ? range.getToBound() : null; } public long getPartitionId() { @@ -53,38 +43,6 @@ public List getParentPartitionIds() { return parentPartitionIds; } - /** - * Whether the server supplied a key range, including a range with both ends unbounded. - * @return true if key-range metadata is present - */ - public boolean hasKeyRange() { - return keyRange; - } - - public boolean hasFromBound() { - return fromBound != null; - } - - public boolean hasToBound() { - return toBound != null; - } - - /** - * Inclusive lower bound, compared as unsigned bytes. Empty means unbounded. - * @return a defensive copy of the bound - */ - public byte[] getFromBound() { - return fromBound == null ? new byte[0] : fromBound.toByteArray(); - } - - /** - * Exclusive upper bound, compared as unsigned bytes. Empty means unbounded. - * @return a defensive copy of the bound - */ - public byte[] getToBound() { - return toBound == null ? new byte[0] : toBound.toByteArray(); - } - @Nullable public PartitionStats getPartitionStats() { return partitionStats; @@ -103,15 +61,11 @@ public boolean equals(Object o) { active == that.active && Objects.equals(childPartitionIds, that.childPartitionIds) && Objects.equals(parentPartitionIds, that.parentPartitionIds) && - Objects.equals(partitionStats, that.partitionStats) && - keyRange == that.keyRange && - Objects.equals(fromBound, that.fromBound) && - Objects.equals(toBound, that.toBound); + Objects.equals(partitionStats, that.partitionStats); } @Override public int hashCode() { - return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats, - keyRange, fromBound, toBound); + return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats); } } From 6e9636d4e70bd8b776bbfd4ddbe68445d972e3c9 Mon Sep 17 00:00:00 2001 From: lebmax Date: Tue, 24 Nov 2026 19:20:47 +0300 Subject: [PATCH 19/29] Fix canceled session pool waiters and add acquire metrics --- CHANGELOG.md | 2 + .../tech/ydb/core/impl/Observability.java | 2 +- .../tech/ydb/core/impl/ObservabilityTest.java | 6 +- .../java/tech/ydb/query/impl/SessionPool.java | 25 ++++++- .../tech/ydb/query/impl/PoolMetricsTest.java | 38 +++++++++- .../tech/ydb/table/impl/pool/PoolMetrics.java | 28 +++++++ .../tech/ydb/table/impl/pool/SessionPool.java | 27 +++++++ .../ydb/table/impl/pool/WaitingQueue.java | 28 +++++++ .../ydb/table/impl/pool/PoolMetricsTest.java | 44 ++++++++++- .../ydb/table/impl/pool/SessionPoolTest.java | 50 +++++++++++++ .../ydb/table/impl/pool/WaitingQueueTest.java | 73 ++++++++++++++++++- 11 files changed, 312 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 706a60fe2..26e8bb9a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ ## 2.5.1 ## * Core: added opt-in PRIMARY/PROMOTED Bridge pile preference with synchronized-pile fallback +* Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately +* Table/Query: added session-pool acquire duration and bounded failure-reason metrics * Core: added Meter histograms with explicit bucket boundaries, OpenTelemetryMeter uses OpenTelemetry database latency boundaries by default * Core: added GrpcTransportBuilder.withChannelShutdownTimeout option * Core: added backoff with jitter to background token refresh retries diff --git a/core/src/main/java/tech/ydb/core/impl/Observability.java b/core/src/main/java/tech/ydb/core/impl/Observability.java index 3eba77589..ea94778c7 100644 --- a/core/src/main/java/tech/ydb/core/impl/Observability.java +++ b/core/src/main/java/tech/ydb/core/impl/Observability.java @@ -12,7 +12,7 @@ */ public final class Observability { public static final String TRACING_CHAIN = ";ydb-sdk-tracing/0.1.0"; - public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.3.0"; + public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.4.0"; private static volatile boolean isTracingEnabled = false; private static volatile boolean isMetricsEnabled = false; diff --git a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java index b6fc8dec4..9ce29f45b 100644 --- a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java +++ b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java @@ -31,18 +31,18 @@ public void baseTest() { Assert.assertEquals(BASE, Observability.getDiscoveryBuildInfo(BASE)); Observability.reportMetricsUsage(new Meter() { }); - Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE)); + Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE)); Observability.reportTracingUsage((String spanName, SpanKind spanKind) -> Span.NOOP); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE) ); Observability.reportMetricsUsage(Meter.NOOP); Observability.reportTracingUsage(NoopTracer.getInstance()); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE) ); } diff --git a/query/src/main/java/tech/ydb/query/impl/SessionPool.java b/query/src/main/java/tech/ydb/query/impl/SessionPool.java index 5b0cf272c..5d2cba7d2 100644 --- a/query/src/main/java/tech/ydb/query/impl/SessionPool.java +++ b/query/src/main/java/tech/ydb/query/impl/SessionPool.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -106,7 +107,9 @@ public void close() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire QuerySession with timeout {}", timeout); + long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); + future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -120,6 +123,26 @@ public CompletableFuture> acquire(Duration timeout) { return future; } + private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { + metrics.onAcquireTime(System.nanoTime() - startNanos); + if (error instanceof CancellationException) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (error != null || result == null) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } else if (!result.isSuccess()) { + StatusCode code = result.getStatus().getCode(); + if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); + } else if (code == StatusCode.CLIENT_CANCELLED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); + } else { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } + } + } + private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); @@ -128,10 +151,10 @@ private boolean pollNext(CompletableFuture> future) { return tryComplete(future, nextSession.join()); } + future.whenComplete((result, error) -> nextSession.cancel(false)); nextSession.whenComplete((session, th) -> { if (th != null) { if (future.isDone()) { - logger.warn("can't get QuerySession, future is already canceled", th); return; } diff --git a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java index 7fb29f879..5370c5443 100644 --- a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java @@ -64,6 +64,7 @@ public class PoolMetricsTest { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); + private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); private Runnable cleaner; @@ -85,7 +86,8 @@ public void setup() { when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); + when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> + PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -102,7 +104,9 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); + verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); + verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -131,6 +135,7 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); + verify(acquireTime).record(anyDouble(), argThat(poolName)); session.close(); verify(counter("released")).add(eq(1L), argThat(poolName)); @@ -139,6 +144,23 @@ public void sessionLifecycleRecordsCounters() { verify(counter("failed"), never()).add(anyLong(), any()); } + @Test + public void cancelledAcquireRemovesPendingRequestAndRecordsFailure() { + try (SessionPool pool = createPool(0, 1)) { + QuerySession occupied = acquireReady(pool); + CompletableFuture> cancelled = pool.acquire(TIMEOUT); + + Assert.assertTrue(cancelled.cancel(false)); + Assert.assertTrue(cancelled.isCancelled()); + assertPendingRequests(pool, 0L); + verifyAcquireFailure("cancelled"); + + occupied.close(); + assertPendingRequests(pool, 0L); + verify(counter("acquired")).add(eq(1L), argThat(poolName)); + } + } + @Test public void failedCreateRecordsFailedCounter() { rpc.overloaded = true; @@ -429,6 +451,20 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } + private void assertPendingRequests(SessionPool pool, long expected) { + LongMeasurement pending = mock(LongMeasurement.class); + gauges.get(PREFIX + "pending_requests").accept(pending); + verify(pending).record(eq(expected), argThat(poolName)); + } + + private void verifyAcquireFailure(String reason) { + verify(counter("acquire_failures")).add( + eq(1L), + argThat(poolName), + argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) + ); + } + private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java index daefe70af..722cc2c20 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java @@ -11,6 +11,19 @@ import tech.ydb.core.metrics.MetricRegistration; public final class PoolMetrics implements AutoCloseable { + public enum AcquireFailureReason { + TIMEOUT("timeout"), + CANCELLED("cancelled"), + REJECTED("rejected"), + OTHER("other"); + + private final String code; + + AcquireFailureReason(String code) { + this.code = code; + } + } + public enum Reason { UNKNOWN("unknown"), @@ -69,6 +82,7 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final Attr[] idleAttrs; private final Attr[] inUseAttrs; private final String statusKey; + private final String acquireFailureReasonKey; private final LongCounter created; private final LongCounter acquired; @@ -76,7 +90,9 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final LongCounter requested; private final LongCounter failed; private final LongCounter closed; + private final LongCounter acquireFailures; private final DoubleHistogram createTime; + private final DoubleHistogram acquireTime; private final MetricRegistration maxGauge; private final MetricRegistration minGauge; private final MetricRegistration countGauge; @@ -85,6 +101,7 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue queue, int minSize) { String prefix = "ydb." + name + ".session."; this.statusKey = prefix + "status_code"; + this.acquireFailureReasonKey = prefix + "reason"; this.poolNameAttr = Attr.of(prefix + "pool.name", poolName); this.poolAttrs = new Attr[]{poolNameAttr}; @@ -97,7 +114,10 @@ public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue qu this.requested = meter.createCounter(prefix + "requested", UNIT, "Total CreateSession calls."); this.failed = meter.createCounter(prefix + "failed", UNIT, "Total failed session creations."); this.closed = meter.createCounter(prefix + "closed", UNIT, "Total closed sessions."); + this.acquireFailures = meter.createCounter(prefix + "acquire_failures", "{request}", + "Total failed session acquire attempts."); this.createTime = meter.createHistogram(prefix + "create_time", "s", "Session creation cost."); + this.acquireTime = meter.createHistogram(prefix + "acquire_time", "s", "Session acquire duration."); this.maxGauge = meter.registerLongGauge(prefix + "max", UNIT, "Configured MaxPoolSize", m -> m.record(queue.getTotalLimit(), poolAttrs)); @@ -130,6 +150,14 @@ public void onCreateTime(long createTimeNanos) { createTime.record(createTimeNanos / NANOS_IN_SECOND, poolAttrs); } + public void onAcquireTime(long acquireTimeNanos) { + acquireTime.record(acquireTimeNanos / NANOS_IN_SECOND, poolAttrs); + } + + public void onAcquireFailure(@Nonnull AcquireFailureReason reason) { + acquireFailures.add(1L, poolNameAttr, Attr.of(acquireFailureReasonKey, reason.code)); + } + public void onSessionCreated() { created.add(1L, poolAttrs); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java index 9a497d2a2..516c36079 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -98,7 +99,9 @@ public SessionPoolStats stats() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire session with timeout {}", timeout); + long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); + future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -112,6 +115,26 @@ public CompletableFuture> acquire(Duration timeout) { return future; } + private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { + metrics.onAcquireTime(System.nanoTime() - startNanos); + if (error instanceof CancellationException) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (error != null || result == null) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } else if (!result.isSuccess()) { + StatusCode code = result.getStatus().getCode(); + if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); + } else if (code == StatusCode.CLIENT_CANCELLED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); + } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); + } else { + metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); + } + } + } + private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); @@ -120,8 +143,12 @@ private boolean pollNext(CompletableFuture> future) { return validateSession(nextSession.join(), future); } + future.whenComplete((result, error) -> nextSession.cancel(false)); nextSession.whenComplete((session, th) -> { if (th != null) { + if (future.isDone()) { + return; + } Throwable ex = FutureTools.unwrapCompletionException(th); Result fail = (ex instanceof UnexpectedResultException) ? Result.fail((UnexpectedResultException) ex) diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index a82572118..6a4146306 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -248,6 +248,13 @@ private boolean tryToCreateNewWaiting(CompletableFuture acquire) { } waitingAcquires.offer(acquire); // ConcurrentLinkedQueue always return true + acquire.whenComplete((ignored, th) -> removeWaitingAcquire(acquire)); + // close() can run after the count is reserved but before this offer. + // In that case clear() cannot see the new entry, so clean it here. + if (stopped && waitingAcquires.remove(acquire)) { + waitingAcqueireCount.decrementAndGet(); + acquire.completeExceptionally(new CancellationException("Queue is already closed")); + } return true; } @@ -291,10 +298,30 @@ private void checkNextWaitingAcquire() { waitingAcqueireCount.decrementAndGet(); } else { waitingAcquires.offerFirst(next); + // The future might have completed while it was temporarily removed from the deque. + // Its completion handler cannot remove it in that interval. + if (next.isDone()) { + removeWaitingAcquire(next); + } + if (stopped && waitingAcquires.remove(next)) { + waitingAcqueireCount.decrementAndGet(); + next.completeExceptionally(new CancellationException("Queue is already closed")); + } } } } + /** + * Removes a waiting acquire if it is still enqueued and updates the count + * exactly once. Polling paths update the count themselves after taking an + * acquire out of the deque. + */ + private void removeWaitingAcquire(CompletableFuture acquire) { + if (waitingAcquires.remove(acquire)) { + waitingAcqueireCount.decrementAndGet(); + } + } + private void clear() { for (CompletableFuture key : pendingRequests.keySet()) { if (pendingRequests.remove(key, key)) { @@ -304,6 +331,7 @@ private void clear() { CompletableFuture waiting = waitingAcquires.poll(); while (waiting != null) { + waitingAcqueireCount.decrementAndGet(); waiting.completeExceptionally(new CancellationException("Queue is already closed")); waiting = waitingAcquires.poll(); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java index 152a86b10..488af1fa8 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java @@ -49,6 +49,7 @@ public class PoolMetricsTest extends FutureHelper { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); + private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); @@ -62,7 +63,8 @@ public void setup() { clock.reset(Instant.parse("2022-07-01T00:00:00.000Z")); when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); + when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> + PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -87,7 +89,9 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); + verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); + verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -108,6 +112,7 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); + verify(acquireTime).record(anyDouble(), argThat(poolName)); Session s1 = futureIsReady(f1).getValue(); s1.close(); @@ -120,6 +125,35 @@ public void sessionLifecycleRecordsCounters() { verify(counter("failed"), never()).add(anyLong(), any()); } + @Test + public void acquireMetricsUseSecondsAndBoundedFailureReasons() { + WaitingQueue queue = new WaitingQueue<>(new WaitingQueue.Handler() { + @Override + public CompletableFuture create() { + return new CompletableFuture<>(); + } + + @Override + public void destroy(Object object) { + } + }, 1); + PoolMetrics metrics = new PoolMetrics(meter, "table", POOL, queue, 0); + + metrics.onAcquireTime(500_000_000L); + for (PoolMetrics.AcquireFailureReason reason : PoolMetrics.AcquireFailureReason.values()) { + metrics.onAcquireFailure(reason); + } + + verify(acquireTime).record(eq(0.5d), argThat(poolName)); + verifyAcquireFailure("timeout"); + verifyAcquireFailure("cancelled"); + verifyAcquireFailure("rejected"); + verifyAcquireFailure("other"); + + metrics.close(); + queue.close(); + } + @Test public void gracefulShutdownRecordsClosedReason() { SessionPool pool = createPool(0, 2); @@ -247,6 +281,14 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } + private void verifyAcquireFailure(String reason) { + verify(counter("acquire_failures")).add( + eq(1L), + argThat(poolName), + argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) + ); + } + private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java index b47f14cda..d8730e621 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java @@ -445,6 +445,56 @@ public void canceledSessionsTest() { tableRpc.completeSessionDeleteRequests(); } + @Test + public void timedOutWaitingAcquireReleasesQueueSlot() { + SessionPool pool = new SessionPool(clock, tableRpc, true, + SessionPoolOptions.DEFAULT.withSize(0, 1)); + + CompletableFuture> first = pendingFuture(pool.acquire(TIMEOUT)); + tableRpc.nextCreateSession().completeSuccess(); + Session held = futureIsReady(first).getValue(); + + CompletableFuture> timedOut = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + scheduler.runTasksTo(clock.instant().plus(TIMEOUT)); + resultIsWrong(timedOut, StatusCode.CLIENT_DEADLINE_EXPIRED); + check(pool).pending(0); + + CompletableFuture> next = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + held.close(); + Session acquired = futureIsReady(next).getValue(); + check(pool).pending(0).acquired(1); + + acquired.close(); + pool.close(); + tableRpc.completeSessionDeleteRequests(); + } + + @Test + public void cancelledWaitingAcquireReleasesQueueSlot() { + SessionPool pool = new SessionPool(clock, tableRpc, true, + SessionPoolOptions.DEFAULT.withSize(0, 1)); + + CompletableFuture> first = pendingFuture(pool.acquire(TIMEOUT)); + tableRpc.nextCreateSession().completeSuccess(); + Session held = futureIsReady(first).getValue(); + + CompletableFuture> cancelled = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + Assert.assertTrue(cancelled.cancel(true)); + check(pool).pending(0); + + CompletableFuture> next = pendingFuture(pool.acquire(TIMEOUT)); + held.close(); + Session acquired = futureIsReady(next).getValue(); + check(pool).pending(0).acquired(1); + + acquired.close(); + pool.close(); + tableRpc.completeSessionDeleteRequests(); + } + @Test public void sessionDataQueryErrorsTest() { SessionPool pool = new SessionPool(clock, tableRpc, true, diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 9616ebf2e..bf53e1dc1 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -562,11 +562,11 @@ public void canceledWaitingTest() { Resource r2 = pendingIsReady(w1); Assert.assertEquals("Next waiting got same resource ", r1, r2); - // Cancellation of waiting doesn't affect to queue - w2.cancel(true); - check(queue).queueSize(1).idleSize(0).waitingsCount(2); + // Cancellation immediately removes the waiter and frees a waiting slot. + Assert.assertTrue(w2.cancel(true)); + check(queue).queueSize(1).idleSize(0).waitingsCount(1); - // Canceled waiting must be deleted when queue process next released resource + // The next released resource goes directly to the remaining waiter. queue.release(r2); check(queue).queueSize(1).idleSize(0).waitingsCount(0); @@ -580,6 +580,71 @@ public void canceledWaitingTest() { check(rs).requestsCount(0).activeCount(0); } + @Test + public void completedWaitingIsRemovedImmediatelyTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + waiting.completeExceptionally(new RuntimeException("caller stopped waiting")); + check(queue).waitingsCount(0); + + rs.completeNext(); + Resource resource = pendingIsReady(first); + queue.release(resource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + } + + @Test + public void canceledWaitingAfterRequeueDoesNotConsumeReleasedResourceTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 2, 1); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture second = pendingFuture(acquire(queue)); + rs.completeNext().completeNext(); + Resource firstResource = pendingIsReady(first); + Resource secondResource = pendingIsReady(second); + + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + // Reducing the limit polls and requeues the waiter because both resources are in use. + queue.updateLimits(1, 1); + check(queue).waitingsCount(1); + + waiting.cancel(true); + check(queue).waitingsCount(0); + + queue.release(firstResource); + queue.release(secondResource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + } + + @Test + public void closeRemovesWaitingCountImmediatelyTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + queue.close(); + futureIsCanceled(waiting, QUEUE_IS_CLOSED); + check(queue).queueSize(0).waitingsCount(0); + + rs.completeNext(); + futureIsCanceled(first, QUEUE_IS_CLOSED); + } + @Test public void immediatellyCompletedWaitingsTest() { ResourceHandler rs = new ResourceHandler(); From d7511f24f80809684ecaab60cccd835468eb728c Mon Sep 17 00:00:00 2001 From: lebmax Date: Wed, 25 Nov 2026 00:03:13 +0300 Subject: [PATCH 20/29] Test queue admission after waiter cancellation --- .../ydb/table/impl/pool/WaitingQueueTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index bf53e1dc1..07fa3c67c 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -580,6 +580,38 @@ public void canceledWaitingTest() { check(rs).requestsCount(0).activeCount(0); } + @Test + public void cancelledWaitingFreesFullQueueSlotTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + CompletableFuture cancelled = pendingFuture(acquire(queue)); + CompletableFuture remaining = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + + Assert.assertTrue(cancelled.cancel(true)); + check(queue).waitingsCount(1); + CompletableFuture replacement = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + + queue.release(resource); + Resource next = pendingIsReady(remaining); + Assert.assertSame(resource, next); + queue.release(next); + Resource last = pendingIsReady(replacement); + Assert.assertSame(resource, last); + + queue.delete(last); + queue.close(); + check(queue).queueSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + @Test public void completedWaitingIsRemovedImmediatelyTest() { ResourceHandler rs = new ResourceHandler(); From 82e36ddbf1b60cbc69795aa62b8ca62ddd537655 Mon Sep 17 00:00:00 2001 From: lebmax Date: Thu, 26 Nov 2026 11:24:27 +0300 Subject: [PATCH 21/29] Fix waiting acquire count field name --- .../ydb/table/impl/pool/WaitingQueue.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index 6a4146306..79f0208af 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -58,7 +58,7 @@ default void destroy(T object, PoolMetrics.Reason reason) { /** Queue of waiting acquire requests */ private final ConcurrentLinkedDeque> waitingAcquires = new ConcurrentLinkedDeque<>(); /** Size of waiting acquires queue */ - private final AtomicInteger waitingAcqueireCount = new AtomicInteger(); + private final AtomicInteger waitingAcquireCount = new AtomicInteger(); private final ThreadLocal localGuard = new ThreadLocal<>(); @@ -178,7 +178,7 @@ public int getPendingCount() { } public int getWaitingCount() { - return waitingAcqueireCount.get(); + return waitingAcquireCount.get(); } public int getTotalLimit() { @@ -240,10 +240,10 @@ private boolean tryToCreateNewPending(CompletableFuture acquire) { } private boolean tryToCreateNewWaiting(CompletableFuture acquire) { - int waitingsCount = waitingAcqueireCount.get(); + int waitingsCount = waitingAcquireCount.get(); while (waitingsCount < limits.waitingsLimit) { - if (!waitingAcqueireCount.compareAndSet(waitingsCount, waitingsCount + 1)) { - waitingsCount = waitingAcqueireCount.get(); + if (!waitingAcquireCount.compareAndSet(waitingsCount, waitingsCount + 1)) { + waitingsCount = waitingAcquireCount.get(); continue; } @@ -252,7 +252,7 @@ private boolean tryToCreateNewWaiting(CompletableFuture acquire) { // close() can run after the count is reserved but before this offer. // In that case clear() cannot see the new entry, so clean it here. if (stopped && waitingAcquires.remove(acquire)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); acquire.completeExceptionally(new CancellationException("Queue is already closed")); } return true; @@ -270,7 +270,7 @@ private boolean tryToCompleteWaiting(T object) { CompletableFuture next = waitingAcquires.poll(); while (next != null) { guard.init(); - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); if (safeAcquireObject(next, object) && !guard.isBroken()) { return true; } @@ -289,13 +289,13 @@ private void checkNextWaitingAcquire() { CompletableFuture next = waitingAcquires.poll(); while (next != null && next.isDone()) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); next = waitingAcquires.poll(); } if (next != null) { if (tryToCreateNewPending(next)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); } else { waitingAcquires.offerFirst(next); // The future might have completed while it was temporarily removed from the deque. @@ -304,7 +304,7 @@ private void checkNextWaitingAcquire() { removeWaitingAcquire(next); } if (stopped && waitingAcquires.remove(next)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); next.completeExceptionally(new CancellationException("Queue is already closed")); } } @@ -318,7 +318,7 @@ private void checkNextWaitingAcquire() { */ private void removeWaitingAcquire(CompletableFuture acquire) { if (waitingAcquires.remove(acquire)) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); } } @@ -331,7 +331,7 @@ private void clear() { CompletableFuture waiting = waitingAcquires.poll(); while (waiting != null) { - waitingAcqueireCount.decrementAndGet(); + waitingAcquireCount.decrementAndGet(); waiting.completeExceptionally(new CancellationException("Queue is already closed")); waiting = waitingAcquires.poll(); } From 2a9da5d3a96a099bdff57859523078309567c59b Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 27 Nov 2026 13:42:34 +0300 Subject: [PATCH 22/29] Fix canceled session acquires with constant-time waiter removal --- .../tech/ydb/core/impl/Observability.java | 2 +- .../tech/ydb/core/impl/ObservabilityTest.java | 6 +- .../java/tech/ydb/query/impl/SessionPool.java | 22 --- .../tech/ydb/query/impl/PoolMetricsTest.java | 24 +-- .../tech/ydb/table/impl/pool/PoolMetrics.java | 28 ---- .../tech/ydb/table/impl/pool/SessionPool.java | 23 --- .../ydb/table/impl/pool/WaitingAcquires.java | 113 +++++++++++++ .../ydb/table/impl/pool/WaitingQueue.java | 75 ++++----- .../ydb/table/impl/pool/PoolMetricsTest.java | 44 +---- .../ydb/table/impl/pool/SessionPoolTest.java | 4 +- .../ydb/table/impl/pool/WaitingQueueTest.java | 150 +++++++++++++++++- 11 files changed, 301 insertions(+), 190 deletions(-) create mode 100644 table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java diff --git a/core/src/main/java/tech/ydb/core/impl/Observability.java b/core/src/main/java/tech/ydb/core/impl/Observability.java index ea94778c7..3eba77589 100644 --- a/core/src/main/java/tech/ydb/core/impl/Observability.java +++ b/core/src/main/java/tech/ydb/core/impl/Observability.java @@ -12,7 +12,7 @@ */ public final class Observability { public static final String TRACING_CHAIN = ";ydb-sdk-tracing/0.1.0"; - public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.4.0"; + public static final String METRICS_CHAIN = ";ydb-sdk-metrics/0.3.0"; private static volatile boolean isTracingEnabled = false; private static volatile boolean isMetricsEnabled = false; diff --git a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java index 9ce29f45b..b6fc8dec4 100644 --- a/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java +++ b/core/src/test/java/tech/ydb/core/impl/ObservabilityTest.java @@ -31,18 +31,18 @@ public void baseTest() { Assert.assertEquals(BASE, Observability.getDiscoveryBuildInfo(BASE)); Observability.reportMetricsUsage(new Meter() { }); - Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.4.0", Observability.getDiscoveryBuildInfo(BASE)); + Assert.assertEquals(BASE + ";ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE)); Observability.reportTracingUsage((String spanName, SpanKind spanKind) -> Span.NOOP); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE) ); Observability.reportMetricsUsage(Meter.NOOP); Observability.reportTracingUsage(NoopTracer.getInstance()); Assert.assertEquals( - BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.4.0", + BASE + ";ydb-sdk-tracing/0.1.0;ydb-sdk-metrics/0.3.0", Observability.getDiscoveryBuildInfo(BASE) ); } diff --git a/query/src/main/java/tech/ydb/query/impl/SessionPool.java b/query/src/main/java/tech/ydb/query/impl/SessionPool.java index 5d2cba7d2..a19fba94f 100644 --- a/query/src/main/java/tech/ydb/query/impl/SessionPool.java +++ b/query/src/main/java/tech/ydb/query/impl/SessionPool.java @@ -107,9 +107,7 @@ public void close() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire QuerySession with timeout {}", timeout); - long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); - future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -123,26 +121,6 @@ public CompletableFuture> acquire(Duration timeout) { return future; } - private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { - metrics.onAcquireTime(System.nanoTime() - startNanos); - if (error instanceof CancellationException) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (error != null || result == null) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } else if (!result.isSuccess()) { - StatusCode code = result.getStatus().getCode(); - if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); - } else if (code == StatusCode.CLIENT_CANCELLED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); - } else { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } - } - } - private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); diff --git a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java index 5370c5443..65d1a85d6 100644 --- a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java @@ -64,7 +64,6 @@ public class PoolMetricsTest { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); - private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); private Runnable cleaner; @@ -86,8 +85,7 @@ public void setup() { when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> - PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); + when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -104,9 +102,7 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); - verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); - verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -135,7 +131,6 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); - verify(acquireTime).record(anyDouble(), argThat(poolName)); session.close(); verify(counter("released")).add(eq(1L), argThat(poolName)); @@ -145,18 +140,17 @@ public void sessionLifecycleRecordsCounters() { } @Test - public void cancelledAcquireRemovesPendingRequestAndRecordsFailure() { + public void cancelledAcquireRemovesPendingRequest() { try (SessionPool pool = createPool(0, 1)) { QuerySession occupied = acquireReady(pool); CompletableFuture> cancelled = pool.acquire(TIMEOUT); Assert.assertTrue(cancelled.cancel(false)); Assert.assertTrue(cancelled.isCancelled()); - assertPendingRequests(pool, 0L); - verifyAcquireFailure("cancelled"); + assertPendingRequests(0L); occupied.close(); - assertPendingRequests(pool, 0L); + assertPendingRequests(0L); verify(counter("acquired")).add(eq(1L), argThat(poolName)); } } @@ -451,20 +445,12 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } - private void assertPendingRequests(SessionPool pool, long expected) { + private void assertPendingRequests(long expected) { LongMeasurement pending = mock(LongMeasurement.class); gauges.get(PREFIX + "pending_requests").accept(pending); verify(pending).record(eq(expected), argThat(poolName)); } - private void verifyAcquireFailure(String reason) { - verify(counter("acquire_failures")).add( - eq(1L), - argThat(poolName), - argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) - ); - } - private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java index 722cc2c20..daefe70af 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/PoolMetrics.java @@ -11,19 +11,6 @@ import tech.ydb.core.metrics.MetricRegistration; public final class PoolMetrics implements AutoCloseable { - public enum AcquireFailureReason { - TIMEOUT("timeout"), - CANCELLED("cancelled"), - REJECTED("rejected"), - OTHER("other"); - - private final String code; - - AcquireFailureReason(String code) { - this.code = code; - } - } - public enum Reason { UNKNOWN("unknown"), @@ -82,7 +69,6 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final Attr[] idleAttrs; private final Attr[] inUseAttrs; private final String statusKey; - private final String acquireFailureReasonKey; private final LongCounter created; private final LongCounter acquired; @@ -90,9 +76,7 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { private final LongCounter requested; private final LongCounter failed; private final LongCounter closed; - private final LongCounter acquireFailures; private final DoubleHistogram createTime; - private final DoubleHistogram acquireTime; private final MetricRegistration maxGauge; private final MetricRegistration minGauge; private final MetricRegistration countGauge; @@ -101,7 +85,6 @@ public static Reason fromStatusCode(Throwable th, StatusCode code) { public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue queue, int minSize) { String prefix = "ydb." + name + ".session."; this.statusKey = prefix + "status_code"; - this.acquireFailureReasonKey = prefix + "reason"; this.poolNameAttr = Attr.of(prefix + "pool.name", poolName); this.poolAttrs = new Attr[]{poolNameAttr}; @@ -114,10 +97,7 @@ public PoolMetrics(Meter meter, String name, String poolName, WaitingQueue qu this.requested = meter.createCounter(prefix + "requested", UNIT, "Total CreateSession calls."); this.failed = meter.createCounter(prefix + "failed", UNIT, "Total failed session creations."); this.closed = meter.createCounter(prefix + "closed", UNIT, "Total closed sessions."); - this.acquireFailures = meter.createCounter(prefix + "acquire_failures", "{request}", - "Total failed session acquire attempts."); this.createTime = meter.createHistogram(prefix + "create_time", "s", "Session creation cost."); - this.acquireTime = meter.createHistogram(prefix + "acquire_time", "s", "Session acquire duration."); this.maxGauge = meter.registerLongGauge(prefix + "max", UNIT, "Configured MaxPoolSize", m -> m.record(queue.getTotalLimit(), poolAttrs)); @@ -150,14 +130,6 @@ public void onCreateTime(long createTimeNanos) { createTime.record(createTimeNanos / NANOS_IN_SECOND, poolAttrs); } - public void onAcquireTime(long acquireTimeNanos) { - acquireTime.record(acquireTimeNanos / NANOS_IN_SECOND, poolAttrs); - } - - public void onAcquireFailure(@Nonnull AcquireFailureReason reason) { - acquireFailures.add(1L, poolNameAttr, Attr.of(acquireFailureReasonKey, reason.code)); - } - public void onSessionCreated() { created.add(1L, poolAttrs); } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java index 516c36079..72239b43f 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java @@ -4,7 +4,6 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; -import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -99,9 +98,7 @@ public SessionPoolStats stats() { public CompletableFuture> acquire(Duration timeout) { logger.trace("acquire session with timeout {}", timeout); - long startNanos = System.nanoTime(); CompletableFuture> future = new CompletableFuture<>(); - future.whenComplete((result, error) -> recordAcquireOutcome(result, error, startNanos)); // If next session is not ready - add timeout canceler if (!pollNext(future)) { @@ -115,26 +112,6 @@ public CompletableFuture> acquire(Duration timeout) { return future; } - private void recordAcquireOutcome(Result result, Throwable error, long startNanos) { - metrics.onAcquireTime(System.nanoTime() - startNanos); - if (error instanceof CancellationException) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (error != null || result == null) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } else if (!result.isSuccess()) { - StatusCode code = result.getStatus().getCode(); - if (code == StatusCode.CLIENT_DEADLINE_EXPIRED || code == StatusCode.CLIENT_DEADLINE_EXCEEDED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.TIMEOUT); - } else if (code == StatusCode.CLIENT_CANCELLED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.CANCELLED); - } else if (code == StatusCode.CLIENT_RESOURCE_EXHAUSTED) { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.REJECTED); - } else { - metrics.onAcquireFailure(PoolMetrics.AcquireFailureReason.OTHER); - } - } - } - private boolean pollNext(CompletableFuture> future) { CompletableFuture nextSession = new CompletableFuture<>(); queue.acquire(nextSession); diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java new file mode 100644 index 000000000..74b9b9a6a --- /dev/null +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java @@ -0,0 +1,113 @@ +package tech.ydb.table.impl.pool; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; + +final class WaitingAcquires { + private final AtomicInteger count = new AtomicInteger(); + + private Waiter first; + private Waiter last; + + int count() { + return count.get(); + } + + boolean compareAndReserve(int expectedCount) { + return count.compareAndSet(expectedCount, expectedCount + 1); + } + + void releaseReservation() { + count.decrementAndGet(); + } + + Waiter newWaiter(CompletableFuture acquire) { + return new Waiter<>(this, acquire); + } + + synchronized void offerLast(Waiter waiter) { + if (waiter.linked) { + unlink(waiter); + } + waiter.previous = last; + waiter.next = null; + waiter.linked = true; + if (last == null) { + first = waiter; + } else { + last.next = waiter; + } + last = waiter; + } + + synchronized void offerFirst(Waiter waiter) { + if (waiter.linked) { + unlink(waiter); + } + waiter.previous = null; + waiter.next = first; + waiter.linked = true; + if (first == null) { + last = waiter; + } else { + first.previous = waiter; + } + first = waiter; + } + + synchronized Waiter pollFirst() { + if (first == null) { + return null; + } + Waiter waiter = first; + unlink(waiter); + // Polling only unlinks; callers decide when to release the reservation. + return waiter; + } + + synchronized boolean remove(Waiter waiter) { + if (!waiter.linked) { + return false; + } + unlink(waiter); + count.decrementAndGet(); + return true; + } + + private void unlink(Waiter waiter) { + Waiter previous = waiter.previous; + Waiter next = waiter.next; + if (previous == null) { + first = next; + } else { + previous.next = next; + } + if (next == null) { + last = previous; + } else { + next.previous = previous; + } + waiter.previous = null; + waiter.next = null; + waiter.linked = false; + } + + static final class Waiter implements BiConsumer { + private final WaitingAcquires owner; + final CompletableFuture acquire; + private Waiter previous; + private Waiter next; + private boolean linked; + + private Waiter(WaitingAcquires owner, CompletableFuture acquire) { + this.owner = owner; + this.acquire = acquire; + } + + @Override + public void accept(T object, Throwable error) { + owner.remove(this); + } + } +} diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index 79f0208af..8c09d3f7c 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -55,10 +55,7 @@ default void destroy(T object, PoolMetrics.Reason reason) { /** Summary size of queue = idle.size() + used.size() + pendingRequests.size() */ private final AtomicInteger queueSize = new AtomicInteger(); - /** Queue of waiting acquire requests */ - private final ConcurrentLinkedDeque> waitingAcquires = new ConcurrentLinkedDeque<>(); - /** Size of waiting acquires queue */ - private final AtomicInteger waitingAcquireCount = new AtomicInteger(); + private final WaitingAcquires waitingAcquires = new WaitingAcquires<>(); private final ThreadLocal localGuard = new ThreadLocal<>(); @@ -178,7 +175,7 @@ public int getPendingCount() { } public int getWaitingCount() { - return waitingAcquireCount.get(); + return waitingAcquires.count(); } public int getTotalLimit() { @@ -240,19 +237,19 @@ private boolean tryToCreateNewPending(CompletableFuture acquire) { } private boolean tryToCreateNewWaiting(CompletableFuture acquire) { - int waitingsCount = waitingAcquireCount.get(); + int waitingsCount = waitingAcquires.count(); while (waitingsCount < limits.waitingsLimit) { - if (!waitingAcquireCount.compareAndSet(waitingsCount, waitingsCount + 1)) { - waitingsCount = waitingAcquireCount.get(); + if (!waitingAcquires.compareAndReserve(waitingsCount)) { + waitingsCount = waitingAcquires.count(); continue; } - waitingAcquires.offer(acquire); // ConcurrentLinkedQueue always return true - acquire.whenComplete((ignored, th) -> removeWaitingAcquire(acquire)); + WaitingAcquires.Waiter waiter = waitingAcquires.newWaiter(acquire); + waitingAcquires.offerLast(waiter); + acquire.whenComplete(waiter); // close() can run after the count is reserved but before this offer. // In that case clear() cannot see the new entry, so clean it here. - if (stopped && waitingAcquires.remove(acquire)) { - waitingAcquireCount.decrementAndGet(); + if (stopped && waitingAcquires.remove(waiter)) { acquire.completeExceptionally(new CancellationException("Queue is already closed")); } return true; @@ -267,15 +264,15 @@ private boolean tryToCompleteWaiting(T object) { } try (WaitingGuard guard = new WaitingGuard(object)) { - CompletableFuture next = waitingAcquires.poll(); - while (next != null) { + WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); + while (waiter != null) { guard.init(); - waitingAcquireCount.decrementAndGet(); - if (safeAcquireObject(next, object) && !guard.isBroken()) { + waitingAcquires.releaseReservation(); + if (safeAcquireObject(waiter.acquire, object) && !guard.isBroken()) { return true; } - next = waitingAcquires.poll(); + waiter = waitingAcquires.pollFirst(); } return false; @@ -287,41 +284,29 @@ private void checkNextWaitingAcquire() { return; } - CompletableFuture next = waitingAcquires.poll(); - while (next != null && next.isDone()) { - waitingAcquireCount.decrementAndGet(); - next = waitingAcquires.poll(); + WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); + while (waiter != null && waiter.acquire.isDone()) { + waitingAcquires.releaseReservation(); + waiter = waitingAcquires.pollFirst(); } - if (next != null) { - if (tryToCreateNewPending(next)) { - waitingAcquireCount.decrementAndGet(); + if (waiter != null) { + if (tryToCreateNewPending(waiter.acquire)) { + waitingAcquires.releaseReservation(); } else { - waitingAcquires.offerFirst(next); + waitingAcquires.offerFirst(waiter); // The future might have completed while it was temporarily removed from the deque. // Its completion handler cannot remove it in that interval. - if (next.isDone()) { - removeWaitingAcquire(next); + if (waiter.acquire.isDone()) { + waitingAcquires.remove(waiter); } - if (stopped && waitingAcquires.remove(next)) { - waitingAcquireCount.decrementAndGet(); - next.completeExceptionally(new CancellationException("Queue is already closed")); + if (stopped && waitingAcquires.remove(waiter)) { + waiter.acquire.completeExceptionally(new CancellationException("Queue is already closed")); } } } } - /** - * Removes a waiting acquire if it is still enqueued and updates the count - * exactly once. Polling paths update the count themselves after taking an - * acquire out of the deque. - */ - private void removeWaitingAcquire(CompletableFuture acquire) { - if (waitingAcquires.remove(acquire)) { - waitingAcquireCount.decrementAndGet(); - } - } - private void clear() { for (CompletableFuture key : pendingRequests.keySet()) { if (pendingRequests.remove(key, key)) { @@ -329,11 +314,11 @@ private void clear() { } } - CompletableFuture waiting = waitingAcquires.poll(); + WaitingAcquires.Waiter waiting = waitingAcquires.pollFirst(); while (waiting != null) { - waitingAcquireCount.decrementAndGet(); - waiting.completeExceptionally(new CancellationException("Queue is already closed")); - waiting = waitingAcquires.poll(); + waitingAcquires.releaseReservation(); + waiting.acquire.completeExceptionally(new CancellationException("Queue is already closed")); + waiting = waitingAcquires.pollFirst(); } T nextIdle = idle.poll(); diff --git a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java index 488af1fa8..152a86b10 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/PoolMetricsTest.java @@ -49,7 +49,6 @@ public class PoolMetricsTest extends FutureHelper { private final Meter meter = mock(Meter.class); private final DoubleHistogram createTime = mock(DoubleHistogram.class); - private final DoubleHistogram acquireTime = mock(DoubleHistogram.class); private final Map counters = new HashMap<>(); private final Map> gauges = new HashMap<>(); @@ -63,8 +62,7 @@ public void setup() { clock.reset(Instant.parse("2022-07-01T00:00:00.000Z")); when(meter.createCounter(anyString(), any(), any())) .thenAnswer(inv -> counters.computeIfAbsent(inv.getArgument(0), k -> mock(LongCounter.class))); - when(meter.createHistogram(anyString(), any(), any())).thenAnswer(inv -> - PREFIX.concat("create_time").equals(inv.getArgument(0)) ? createTime : acquireTime); + when(meter.createHistogram(anyString(), any(), any())).thenReturn(createTime); doAnswer(inv -> { String name = inv.getArgument(0); gauges.put(name, inv.getArgument(3)); @@ -89,9 +87,7 @@ public void allInstrumentsAreCreated() { verify(meter).createCounter(eq(PREFIX + "requested"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "failed"), eq("{session}"), anyString()); verify(meter).createCounter(eq(PREFIX + "closed"), eq("{session}"), anyString()); - verify(meter).createCounter(eq(PREFIX + "acquire_failures"), eq("{request}"), anyString()); verify(meter).createHistogram(eq(PREFIX + "create_time"), eq("s"), anyString()); - verify(meter).createHistogram(eq(PREFIX + "acquire_time"), eq("s"), anyString()); verify(meter).registerLongGauge(eq(PREFIX + "max"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "min"), eq("{session}"), anyString(), any()); verify(meter).registerLongGauge(eq(PREFIX + "count"), eq("{session}"), anyString(), any()); @@ -112,7 +108,6 @@ public void sessionLifecycleRecordsCounters() { verify(counter("created")).add(eq(1L), argThat(poolName)); verify(createTime).record(anyDouble(), argThat(poolName)); verify(counter("acquired")).add(eq(1L), argThat(poolName)); - verify(acquireTime).record(anyDouble(), argThat(poolName)); Session s1 = futureIsReady(f1).getValue(); s1.close(); @@ -125,35 +120,6 @@ public void sessionLifecycleRecordsCounters() { verify(counter("failed"), never()).add(anyLong(), any()); } - @Test - public void acquireMetricsUseSecondsAndBoundedFailureReasons() { - WaitingQueue queue = new WaitingQueue<>(new WaitingQueue.Handler() { - @Override - public CompletableFuture create() { - return new CompletableFuture<>(); - } - - @Override - public void destroy(Object object) { - } - }, 1); - PoolMetrics metrics = new PoolMetrics(meter, "table", POOL, queue, 0); - - metrics.onAcquireTime(500_000_000L); - for (PoolMetrics.AcquireFailureReason reason : PoolMetrics.AcquireFailureReason.values()) { - metrics.onAcquireFailure(reason); - } - - verify(acquireTime).record(eq(0.5d), argThat(poolName)); - verifyAcquireFailure("timeout"); - verifyAcquireFailure("cancelled"); - verifyAcquireFailure("rejected"); - verifyAcquireFailure("other"); - - metrics.close(); - queue.close(); - } - @Test public void gracefulShutdownRecordsClosedReason() { SessionPool pool = createPool(0, 2); @@ -281,14 +247,6 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } - private void verifyAcquireFailure(String reason) { - verify(counter("acquire_failures")).add( - eq(1L), - argThat(poolName), - argThat(a -> a.getKey().equals(PREFIX + "reason") && a.getValue().equals(reason)) - ); - } - private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java index d8730e621..e38e72d28 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java @@ -104,7 +104,7 @@ public void increaseLimitsTest() { tableRpc.check().sessionRequests(1); check(pool).idle(0).acquired(0).pending(1).size(0, 1).totalClient(0, 0).totalServer(1, 0, 0, 0); - // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue + // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue for (int i = 0; i < wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } @@ -149,7 +149,7 @@ public void decreaseLimitsTest() { tableRpc.check().sessionRequests(2); check(pool).idle(0).acquired(0).pending(2).size(0, 2).totalClient(0, 0).totalServer(2, 0, 0, 0); - // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue + // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue for (int i = 0; i < 2 * wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 07fa3c67c..7e1e25391 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -1,14 +1,19 @@ package tech.ydb.table.impl.pool; import java.util.ArrayDeque; +import java.util.ArrayList; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.junit.Assert; @@ -527,6 +532,7 @@ public void simpleWaitingRequests() { // After release resource must be moved to next waiting future queue.release(next); CompletableFuture waiting = waitings.poll(); + Assert.assertNotNull(waiting); next = pendingIsReady(waiting); Assert.assertEquals("All waitings got single resource ", r1, next); @@ -612,6 +618,31 @@ public void cancelledWaitingFreesFullQueueSlotTest() { check(rs).requestsCount(0).activeCount(0); } + @Test + public void cancelDuplicatedWaitingAcquireRemovesBothReservationsTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + CompletableFuture duplicated = new CompletableFuture<>(); + queue.acquire(duplicated); + queue.acquire(duplicated); + check(queue).waitingsCount(2); + + Assert.assertTrue(duplicated.cancel(true)); + check(queue).queueSize(1).idleSize(0).waitingsCount(0); + + queue.release(resource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + @Test public void completedWaitingIsRemovedImmediatelyTest() { ResourceHandler rs = new ResourceHandler(); @@ -660,21 +691,132 @@ public void canceledWaitingAfterRequeueDoesNotConsumeReleasedResourceTest() { queue.close(); } + @Test + public void updateLimitsDequeuesOldestWaiterAtFrontTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 2, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture second = pendingFuture(acquire(queue)); + rs.completeNext().completeNext(); + Resource firstResource = pendingIsReady(first); + Resource secondResource = pendingIsReady(second); + + CompletableFuture oldestWaiting = pendingFuture(acquire(queue)); + CompletableFuture laterWaiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + + // With both resources in use, the oldest waiter cannot reserve a new resource. + // It must remain ahead of the later waiter when it is returned to the queue. + queue.updateLimits(1, 2); + check(queue).waitingsCount(2); + + queue.release(firstResource); + Assert.assertSame(firstResource, pendingIsReady(oldestWaiting)); + futureIsPending(laterWaiting); + + queue.release(secondResource); + Assert.assertSame(secondResource, pendingIsReady(laterWaiting)); + + queue.delete(firstResource); + queue.delete(secondResource); + queue.close(); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + @Test public void closeRemovesWaitingCountImmediatelyTest() { ResourceHandler rs = new ResourceHandler(); - WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 3); CompletableFuture first = pendingFuture(acquire(queue)); - CompletableFuture waiting = pendingFuture(acquire(queue)); - check(queue).waitingsCount(1); + CompletableFuture firstWaiting = pendingFuture(acquire(queue)); + CompletableFuture middleWaiting = pendingFuture(acquire(queue)); + CompletableFuture lastWaiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(3); queue.close(); - futureIsCanceled(waiting, QUEUE_IS_CLOSED); + futureIsCanceled(firstWaiting, QUEUE_IS_CLOSED); + futureIsCanceled(middleWaiting, QUEUE_IS_CLOSED); + futureIsCanceled(lastWaiting, QUEUE_IS_CLOSED); check(queue).queueSize(0).waitingsCount(0); rs.completeNext(); futureIsCanceled(first, QUEUE_IS_CLOSED); + check(rs).requestsCount(0).activeCount(0); + } + + @Test + public void concurrentCancelAndCloseRemovesAllWaitingAcquiresTest() throws InterruptedException { + final int waitingCount = 64; + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, waitingCount); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + List> waitings = new ArrayList<>(); + for (int idx = 0; idx < waitingCount; idx++) { + CompletableFuture waiting = new CompletableFuture<>(); + queue.acquire(waiting); + waitings.add(waiting); + } + check(queue).waitingsCount(waitingCount); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + AtomicReference workerFailure = new AtomicReference<>(); + + Thread cancellation = new Thread(() -> { + ready.countDown(); + try { + Assert.assertTrue("Cancellation worker did not start", start.await(5, TimeUnit.SECONDS)); + for (CompletableFuture waiting : waitings) { + waiting.cancel(true); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + workerFailure.compareAndSet(null, ex); + } catch (Throwable th) { + workerFailure.compareAndSet(null, th); + } + }, "waiting-queue-cancellation-test"); + Thread closing = new Thread(() -> { + ready.countDown(); + try { + Assert.assertTrue("Close worker did not start", start.await(5, TimeUnit.SECONDS)); + queue.close(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + workerFailure.compareAndSet(null, ex); + } catch (Throwable th) { + workerFailure.compareAndSet(null, th); + } + }, "waiting-queue-close-test"); + cancellation.setDaemon(true); + closing.setDaemon(true); + cancellation.start(); + closing.start(); + + boolean workersReady = ready.await(5, TimeUnit.SECONDS); + start.countDown(); + cancellation.join(5000); + closing.join(5000); + + Assert.assertTrue("Workers did not become ready", workersReady); + Assert.assertFalse("Cancellation worker did not finish", cancellation.isAlive()); + Assert.assertFalse("Close worker did not finish", closing.isAlive()); + Assert.assertNull("Concurrent worker failed", workerFailure.get()); + check(queue).queueSize(1).idleSize(0).waitingsCount(0); + for (CompletableFuture waiting : waitings) { + Assert.assertTrue("Waiting future is terminal", waiting.isDone()); + } + + queue.release(resource); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); } @Test From 250e728d2acd321d16189051a3f5db30eff7dd53 Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 27 Nov 2026 13:57:13 +0300 Subject: [PATCH 23/29] Remove unused cancellation import --- query/src/main/java/tech/ydb/query/impl/SessionPool.java | 1 - 1 file changed, 1 deletion(-) diff --git a/query/src/main/java/tech/ydb/query/impl/SessionPool.java b/query/src/main/java/tech/ydb/query/impl/SessionPool.java index a19fba94f..ef93223e1 100644 --- a/query/src/main/java/tech/ydb/query/impl/SessionPool.java +++ b/query/src/main/java/tech/ydb/query/impl/SessionPool.java @@ -4,7 +4,6 @@ import java.time.Duration; import java.time.Instant; import java.util.Iterator; -import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; From ff1d8859035271bad21017f92f5004afdc9b4bb0 Mon Sep 17 00:00:00 2001 From: Kirill Kurdyukov Date: Mon, 30 Nov 2026 15:52:08 +0300 Subject: [PATCH 24/29] Merge pull request #803 from ydb-platform/histogram-buckets Set latency bucket boundaries for duration histograms --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26e8bb9a1..c6fd147fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 2.5.1 ## * 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 * Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately * Table/Query: added session-pool acquire duration and bounded failure-reason metrics * Core: added Meter histograms with explicit bucket boundaries, OpenTelemetryMeter uses OpenTelemetry database latency boundaries by default From 321197adec78e968c3d5b95f5d8218fe89429e21 Mon Sep 17 00:00:00 2001 From: lebmax Date: Thu, 3 Dec 2026 01:00:36 +0300 Subject: [PATCH 25/29] Fix canceled session acquires with constant-time waiter removal --- .../QueryClientSessionPoolWaiterTest.java | 189 ++++++++++++++++++ .../ydb/table/impl/pool/WaitingQueueTest.java | 60 ++++++ 2 files changed, 249 insertions(+) create mode 100644 query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java diff --git a/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java b/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java new file mode 100644 index 000000000..f1a035349 --- /dev/null +++ b/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java @@ -0,0 +1,189 @@ +package tech.ydb.query.impl; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; +import org.junit.ClassRule; +import org.junit.Test; + +import tech.ydb.core.Result; +import tech.ydb.core.StatusCode; +import tech.ydb.query.QueryClient; +import tech.ydb.query.QuerySession; +import tech.ydb.table.SessionPoolStats; +import tech.ydb.test.junit4.GrpcTransportRule; + +public class QueryClientSessionPoolWaiterTest { + private static final Duration LONG_ACQUIRE_TIMEOUT = Duration.ofMinutes(1); + private static final Duration SHORT_ACQUIRE_TIMEOUT = Duration.ofSeconds(3); + private static final long ASYNC_ASSERTION_TIMEOUT_SECONDS = 10; + private static final int MAX_QUEUE_FILL_ATTEMPTS = 100; + + @ClassRule + public static final GrpcTransportRule YDB = new GrpcTransportRule(); + + @Test + public void cancelledPublicWaiterReleasesSaturatedQueueSlotAndPreservesFifo() throws Exception { + try (QueryClient client = newClient()) { + QuerySession held = awaitSession(client.createSession(LONG_ACQUIRE_TIMEOUT)); + List>> waiters = new ArrayList<>(); + fillWaitingQueue(client, waiters); + + int cancelledIndex = waiters.size() / 2; + CompletableFuture> cancelled = waiters.get(cancelledIndex); + Assert.assertTrue("The selected waiting acquire should be cancelable", cancelled.cancel(true)); + + CompletableFuture> replacement = + acquirePendingWhenQueueHasSlot(client, LONG_ACQUIRE_TIMEOUT); + List>> liveWaiters = without(waiters, cancelledIndex); + liveWaiters.add(replacement); + + assertOnlyHeldSession(client); + Assert.assertNotNull(replacement); + Assert.assertFalse("The replacement must wait while the only session is held", replacement.isDone()); + drainInFifoOrder(client, held, liveWaiters); + } + } + + @Test + public void timedOutPublicWaiterReleasesSaturatedQueueSlot() throws Exception { + try (QueryClient client = newClient()) { + List>> waiters = new ArrayList<>(); + CompletableFuture> replacement = null; + + try (QuerySession held = awaitSession(client.createSession(LONG_ACQUIRE_TIMEOUT))) { + try { + // Put the timeout acquire into the queue before filling the remaining slots. + waiters.add(client.createSession(LONG_ACQUIRE_TIMEOUT)); + CompletableFuture> timedOut = + client.createSession(SHORT_ACQUIRE_TIMEOUT); + waiters.add(timedOut); + + fillWaitingQueue(client, waiters); + Assert.assertFalse("The queue should be observed full before the timed acquire expires", timedOut.isDone()); + + Result timeoutResult = + timedOut.get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertEquals(StatusCode.CLIENT_DEADLINE_EXPIRED, timeoutResult.getStatus().getCode()); + + // The timeout completes the public future before its cancellation callback is + // necessarily observed by this thread. Retry only the expected full-queue rejection + // until the public API admits a new waiter. + replacement = acquirePendingWhenQueueHasSlot(client, LONG_ACQUIRE_TIMEOUT); + Assert.assertNotNull(replacement); + Assert.assertFalse("The replacement must wait while the only session is held", replacement.isDone()); + assertOnlyHeldSession(client); + } finally { + for (CompletableFuture> waiter : waiters) { + waiter.cancel(true); + } + if (replacement != null) { + replacement.cancel(true); + } + } + } + } + } + + private static QueryClient newClient() { + return QueryClient.newClient(YDB) + .sessionPoolMaxSize(1) + .build(); + } + + private static QuerySession awaitSession(CompletableFuture> future) throws Exception { + Result result = future.get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertTrue("Session creation should succeed: " + result.getStatus(), result.isSuccess()); + return result.getValue(); + } + + private static void fillWaitingQueue( + QueryClient client, List>> waiters) { + for (int attempt = 0; attempt < MAX_QUEUE_FILL_ATTEMPTS; attempt += 1) { + CompletableFuture> waiter = client.createSession(LONG_ACQUIRE_TIMEOUT); + if (!waiter.isDone()) { + waiters.add(waiter); + continue; + } + + Result overflow = waiter.join(); + Assert.assertEquals( + "The queue should reject the first acquire beyond its waiting limit", + StatusCode.CLIENT_RESOURCE_EXHAUSTED, + overflow.getStatus().getCode() + ); + Assert.assertFalse("The queue should admit at least one waiter", waiters.isEmpty()); + return; + } + + Assert.fail("The bounded session-pool waiting queue did not reject an overflow acquire"); + } + + private static CompletableFuture> acquirePendingWhenQueueHasSlot( + QueryClient client, Duration timeout) throws InterruptedException { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(ASYNC_ASSERTION_TIMEOUT_SECONDS); + while (System.nanoTime() < deadlineNanos) { + CompletableFuture> candidate = client.createSession(timeout); + if (!candidate.isDone()) { + return candidate; + } + + Result result = candidate.join(); + Assert.assertEquals( + "A saturated queue may reject only with CLIENT_RESOURCE_EXHAUSTED", + StatusCode.CLIENT_RESOURCE_EXHAUSTED, + result.getStatus().getCode() + ); + Thread.sleep(5); + } + + Assert.fail("No new acquire was admitted after a waiting acquire became terminal"); + return null; + } + + private static List>> without( + List>> futures, int excludedIndex) { + List>> result = new ArrayList<>(futures.size() - 1); + for (int i = 0; i < futures.size(); i += 1) { + if (i != excludedIndex) { + result.add(futures.get(i)); + } + } + return result; + } + + private static void assertOnlyHeldSession(QueryClient client) { + SessionPoolStats stats = client.getSessionPoolStats(); + Assert.assertEquals("The only session remains acquired", 1, stats.getAcquiredCount()); + Assert.assertEquals("No session should be idle while the held session is open", 0, stats.getIdleCount()); + } + + private static void drainInFifoOrder( + QueryClient client, + QuerySession held, + List>> waiters) throws Exception { + String heldId = held.getId(); + QuerySession current = held; + for (int i = 0; i < waiters.size(); i += 1) { + current.close(); + + Result result = waiters.get(i).get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertTrue("The next live waiter should receive the released session", result.isSuccess()); + QuerySession next = result.getValue(); + Assert.assertEquals("The pool should hand off the same session in FIFO order", heldId, next.getId()); + + for (int j = i + 1; j < waiters.size(); j += 1) { + Assert.assertFalse("A later waiter must remain pending", waiters.get(j).isDone()); + } + current = next; + } + + current.close(); + Assert.assertEquals(0, client.getSessionPoolStats().getAcquiredCount()); + Assert.assertEquals(1, client.getSessionPoolStats().getIdleCount()); + } +} diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 7e1e25391..922555f21 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -11,6 +11,9 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -819,6 +822,63 @@ public void concurrentCancelAndCloseRemovesAllWaitingAcquiresTest() throws Inter check(rs).requestsCount(0).activeCount(0); } + @Test + public void cancellationRacingWithReleasePreservesWaitingCapacity() throws Exception { + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + for (int attempt = 0; attempt < 32; attempt++) { + checkCancellationRacingWithRelease(workers); + } + } finally { + workers.shutdownNow(); + } + } + + private void checkCancellationRacingWithRelease(ExecutorService workers) throws Exception { + ResourceHandler handler = new ResourceHandler(); + try (WaitingQueue queue = new WaitingQueue<>(handler, 1, 2)) { + CompletableFuture first = pendingFuture(acquire(queue)); + handler.completeNext(); + Resource held = pendingIsReady(first); + CompletableFuture contested = pendingFuture(acquire(queue)); + CompletableFuture surviving = pendingFuture(acquire(queue)); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + Future cancelled = workers.submit(() -> { + ready.countDown(); + Assert.assertTrue(start.await(5, TimeUnit.SECONDS)); + return contested.cancel(false); + }); + Future released = workers.submit(() -> { + ready.countDown(); + Assert.assertTrue(start.await(5, TimeUnit.SECONDS)); + queue.release(held); + return null; + }); + boolean bothReady = ready.await(5, TimeUnit.SECONDS); + start.countDown(); + Assert.assertTrue("Both workers should be ready", bothReady); + released.get(5, TimeUnit.SECONDS); + if (cancelled.get(5, TimeUnit.SECONDS)) { + Assert.assertTrue(contested.isCancelled()); + } else { + Assert.assertSame(held, pendingIsReady(contested)); + queue.release(held); + } + Assert.assertSame(held, pendingIsReady(surviving)); + + CompletableFuture next = pendingFuture(acquire(queue)); + CompletableFuture last = pendingFuture(acquire(queue)); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + queue.release(held); + Assert.assertSame(held, pendingIsReady(next)); + queue.release(held); + Assert.assertSame(held, pendingIsReady(last)); + queue.release(held); + } + } + @Test public void immediatellyCompletedWaitingsTest() { ResourceHandler rs = new ResourceHandler(); From 4f4959eece815739baeed15d9e95318e4718ce3d Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 4 Dec 2026 13:16:58 +0300 Subject: [PATCH 26/29] Remove cancelled session waiters by key without a shared monitor Release each waiting slot once, including when resize has detached the waiter. Skip removal on normal handoff and cover both concurrent cases. --- .../ydb/table/impl/pool/WaitingAcquires.java | 112 ++++------ .../ydb/table/impl/pool/WaitingQueue.java | 17 +- .../pool/WaitingQueueParallelChurnTest.java | 204 ++++++++++++++++++ .../ydb/table/impl/pool/WaitingQueueTest.java | 57 +++++ 4 files changed, 314 insertions(+), 76 deletions(-) create mode 100644 table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java index 74b9b9a6a..7dffd44ed 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java @@ -1,15 +1,18 @@ package tech.ydb.table.impl.pool; +import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; final class WaitingAcquires { + private final ConcurrentSkipListMap, Waiter> queue = new ConcurrentSkipListMap<>(); + private final AtomicLong sequence = new AtomicLong(); private final AtomicInteger count = new AtomicInteger(); - private Waiter first; - private Waiter last; - int count() { return count.get(); } @@ -18,96 +21,67 @@ boolean compareAndReserve(int expectedCount) { return count.compareAndSet(expectedCount, expectedCount + 1); } - void releaseReservation() { - count.decrementAndGet(); + void releaseReservation(Waiter waiter) { + if (waiter.release()) { + count.decrementAndGet(); + } } Waiter newWaiter(CompletableFuture acquire) { - return new Waiter<>(this, acquire); + return new Waiter<>(this, acquire, sequence.getAndIncrement()); } - synchronized void offerLast(Waiter waiter) { - if (waiter.linked) { - unlink(waiter); - } - waiter.previous = last; - waiter.next = null; - waiter.linked = true; - if (last == null) { - first = waiter; - } else { - last.next = waiter; - } - last = waiter; + void offer(Waiter waiter) { + // The waiter is also the key, so enqueue does not need to box the sequence number. + queue.put(waiter, waiter); } - synchronized void offerFirst(Waiter waiter) { - if (waiter.linked) { - unlink(waiter); - } - waiter.previous = null; - waiter.next = first; - waiter.linked = true; - if (first == null) { - last = waiter; - } else { - first.previous = waiter; - } - first = waiter; - } - - synchronized Waiter pollFirst() { - if (first == null) { - return null; - } - Waiter waiter = first; - unlink(waiter); - // Polling only unlinks; callers decide when to release the reservation. - return waiter; + Waiter pollFirst() { + Map.Entry, Waiter> entry = queue.pollFirstEntry(); + return entry == null ? null : entry.getValue(); } - synchronized boolean remove(Waiter waiter) { - if (!waiter.linked) { + boolean remove(Waiter waiter) { + if (!queue.remove(waiter, waiter)) { return false; } - unlink(waiter); - count.decrementAndGet(); + releaseReservation(waiter); return true; } - private void unlink(Waiter waiter) { - Waiter previous = waiter.previous; - Waiter next = waiter.next; - if (previous == null) { - first = next; - } else { - previous.next = next; - } - if (next == null) { - last = previous; - } else { - next.previous = previous; - } - waiter.previous = null; - waiter.next = null; - waiter.linked = false; - } + static final class Waiter implements Comparable>, BiConsumer { + @SuppressWarnings("rawtypes") + private static final AtomicIntegerFieldUpdater RELEASED = + AtomicIntegerFieldUpdater.newUpdater(Waiter.class, "released"); - static final class Waiter implements BiConsumer { private final WaitingAcquires owner; final CompletableFuture acquire; - private Waiter previous; - private Waiter next; - private boolean linked; + private final long order; + private volatile int released; - private Waiter(WaitingAcquires owner, CompletableFuture acquire) { + private Waiter(WaitingAcquires owner, CompletableFuture acquire, long order) { this.owner = owner; this.acquire = acquire; + this.order = order; + } + + private boolean release() { + return released == 0 && RELEASED.compareAndSet(this, 0, 1); + } + + @Override + public int compareTo(Waiter other) { + return Long.compareUnsigned(order, other.order); } @Override public void accept(T object, Throwable error) { - owner.remove(this); + if (released == 0) { + // A resize can temporarily detach this waiter. Completion still frees its slot. + if (!owner.remove(this)) { + owner.releaseReservation(this); + } + } } } } diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index 8c09d3f7c..76700b056 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -245,7 +245,7 @@ private boolean tryToCreateNewWaiting(CompletableFuture acquire) { } WaitingAcquires.Waiter waiter = waitingAcquires.newWaiter(acquire); - waitingAcquires.offerLast(waiter); + waitingAcquires.offer(waiter); acquire.whenComplete(waiter); // close() can run after the count is reserved but before this offer. // In that case clear() cannot see the new entry, so clean it here. @@ -267,7 +267,7 @@ private boolean tryToCompleteWaiting(T object) { WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); while (waiter != null) { guard.init(); - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiter); if (safeAcquireObject(waiter.acquire, object) && !guard.isBroken()) { return true; } @@ -286,16 +286,19 @@ private void checkNextWaitingAcquire() { WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); while (waiter != null && waiter.acquire.isDone()) { - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiter); waiter = waitingAcquires.pollFirst(); } if (waiter != null) { if (tryToCreateNewPending(waiter.acquire)) { - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiter); + } else if (waiter.acquire.isDone()) { + waitingAcquires.releaseReservation(waiter); } else { - waitingAcquires.offerFirst(waiter); - // The future might have completed while it was temporarily removed from the deque. + // Keep the original order when returning an older waiter after a resize. + waitingAcquires.offer(waiter); + // The future might have completed while it was temporarily removed. // Its completion handler cannot remove it in that interval. if (waiter.acquire.isDone()) { waitingAcquires.remove(waiter); @@ -316,7 +319,7 @@ private void clear() { WaitingAcquires.Waiter waiting = waitingAcquires.pollFirst(); while (waiting != null) { - waitingAcquires.releaseReservation(); + waitingAcquires.releaseReservation(waiting); waiting.acquire.completeExceptionally(new CancellationException("Queue is already closed")); waiting = waitingAcquires.pollFirst(); } diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java new file mode 100644 index 000000000..7f30412dc --- /dev/null +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java @@ -0,0 +1,204 @@ +package tech.ydb.table.impl.pool; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReferenceArray; + +import org.junit.Assert; +import org.junit.Test; + +public class WaitingQueueParallelChurnTest { + private static final int TIMEOUT_SECONDS = 10; + private static final int PREFIX_WAITERS = 3; + private static final int WORKER_COUNT = 8; + private static final int CHURN_ITERATIONS = 128; + private static final int WAITING_LIMIT = PREFIX_WAITERS + WORKER_COUNT; + + @Test + public void admitsParallelCancelAndReplaceChurnAndPreservesFifo() throws Exception { + CompletableFuture resourceCreation = new CompletableFuture<>(); + WaitingQueue.Handler handler = new WaitingQueue.Handler() { + @Override + public CompletableFuture create() { + return resourceCreation; + } + + @Override + public void destroy(Object object) { + // The queue owns one resource for this test. + } + }; + + WaitingQueue queue = new WaitingQueue<>(handler, 1, WAITING_LIMIT); + ExecutorService workers = Executors.newFixedThreadPool(WORKER_COUNT); + CountDownLatch workersReady = new CountDownLatch(WORKER_COUNT); + CountDownLatch startWorkers = new CountDownLatch(1); + AtomicReferenceArray> workerWaiters = + new AtomicReferenceArray<>(WORKER_COUNT); + AtomicInteger maximumObservedWaitingCount = new AtomicInteger(); + Future[] workerTasks = new Future[WORKER_COUNT]; + Object resource = new Object(); + + try { + CompletableFuture heldAcquire = new CompletableFuture<>(); + queue.acquire(heldAcquire); + Assert.assertTrue("Resource creation should complete", resourceCreation.complete(resource)); + Assert.assertSame("The only resource remains checked out", resource, + heldAcquire.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + List> prefix = new ArrayList<>(); + for (int i = 0; i < PREFIX_WAITERS; i++) { + CompletableFuture waiter = enqueue(queue); + assertWaiting(waiter, "Prefix waiter should be admitted"); + prefix.add(waiter); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + } + + for (int workerId = 0; workerId < WORKER_COUNT; workerId++) { + CompletableFuture initialWaiter = enqueue(queue); + assertWaiting(initialWaiter, "Worker's initial waiter should be admitted"); + workerWaiters.set(workerId, initialWaiter); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + + final int id = workerId; + workerTasks[workerId] = workers.submit(() -> { + workersReady.countDown(); + if (!startWorkers.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("Timed out waiting for the churn start latch"); + } + + CompletableFuture current = workerWaiters.get(id); + for (int i = 0; i < CHURN_ITERATIONS; i++) { + Assert.assertTrue("Canceling the worker's active waiter should succeed", + current.cancel(false)); + + CompletableFuture replacement = new CompletableFuture<>(); + queue.acquire(replacement); + assertWaiting(replacement, "Replacement waiter should be admitted"); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + + current = replacement; + workerWaiters.set(id, current); + } + return null; + }); + } + + Assert.assertEquals("The prefix and workers should fill all waiting slots", + WAITING_LIMIT, queue.getWaitingCount()); + Assert.assertTrue("Workers did not reach the start latch", + workersReady.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + startWorkers.countDown(); + awaitAll(workerTasks); + + Assert.assertEquals("Every worker should retain one final active waiter", + WAITING_LIMIT, queue.getWaitingCount()); + Assert.assertEquals("The observed waiting count should reach but not exceed the limit", + WAITING_LIMIT, maximumObservedWaitingCount.get()); + + List> replacements = new ArrayList<>(); + for (int i = 0; i < WORKER_COUNT; i++) { + CompletableFuture replacement = workerWaiters.get(i); + assertWaiting(replacement, "Final replacement should remain queued"); + replacements.add(replacement); + } + + Object currentResource = resource; + for (int i = 0; i < prefix.size(); i++) { + queue.release(currentResource); + currentResource = prefix.get(i).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertSame("Untouched prefix waiters should receive the resource FIFO", + resource, currentResource); + + for (int later = i + 1; later < prefix.size(); later++) { + Assert.assertFalse("Later prefix waiter must not overtake the current waiter", + prefix.get(later).isDone()); + } + for (CompletableFuture replacement : replacements) { + Assert.assertFalse("Worker replacements must remain behind the untouched prefix", + replacement.isDone()); + } + } + + boolean[] served = new boolean[replacements.size()]; + for (int count = 0; count < replacements.size(); count++) { + queue.release(currentResource); + + int newlyServed = -1; + for (int i = 0; i < replacements.size(); i++) { + if (!served[i] && replacements.get(i).isDone()) { + Assert.assertEquals("One release should serve one replacement", -1, newlyServed); + newlyServed = i; + } + } + + Assert.assertNotEquals("Each release should serve a worker replacement", -1, newlyServed); + currentResource = replacements.get(newlyServed).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertSame("Each replacement should receive the released resource", + resource, currentResource); + served[newlyServed] = true; + } + Assert.assertEquals("All worker replacements should have received the resource", + WORKER_COUNT, countServed(served)); + } finally { + startWorkers.countDown(); + for (Future workerTask : workerTasks) { + if (workerTask != null && !workerTask.isDone()) { + workerTask.cancel(true); + } + } + workers.shutdownNow(); + boolean workersTerminated = workers.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + queue.close(); + if (queue.getUsedCount() > 0) { + queue.release(resource); + } + Assert.assertTrue("Churn workers did not terminate", workersTerminated); + } + } + + private static CompletableFuture enqueue(WaitingQueue queue) { + CompletableFuture acquire = new CompletableFuture<>(); + queue.acquire(acquire); + return acquire; + } + + private static void assertWaiting(CompletableFuture future, String message) { + Assert.assertFalse(message + ": result completed exceptionally", future.isCompletedExceptionally()); + Assert.assertFalse(message + ": result completed before a resource was released", future.isDone()); + } + + private static void recordBoundedWaitingCount(WaitingQueue queue, AtomicInteger maximumObserved) { + int waitingCount = queue.getWaitingCount(); + Assert.assertTrue("Waiting count should stay between zero and the configured limit", + waitingCount >= 0 && waitingCount <= WAITING_LIMIT); + maximumObserved.accumulateAndGet(waitingCount, Math::max); + } + + private static void awaitAll(Future[] tasks) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); + for (Future task : tasks) { + long remaining = deadline - System.nanoTime(); + Assert.assertTrue("Timed out while joining churn workers", remaining > 0); + task.get(remaining, TimeUnit.NANOSECONDS); + } + } + + private static int countServed(boolean[] served) { + int count = 0; + for (boolean value : served) { + if (value) { + count++; + } + } + return count; + } +} diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 922555f21..d0ecfd985 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -694,6 +694,63 @@ public void canceledWaitingAfterRequeueDoesNotConsumeReleasedResourceTest() { queue.close(); } + @Test + public void cancellationWhileResizeHasDequeuedWaiterFreesSlot() throws Exception { + ResourceHandler rs = new ResourceHandler(); + ExecutorService worker = Executors.newSingleThreadExecutor(); + try (WaitingQueue queue = new WaitingQueue<>(rs, 1, 1)) { + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource held = pendingIsReady(first); + + AtomicReference resizeThread = new AtomicReference<>(); + CompletableFuture detached = new CompletableFuture<>(); + CountDownLatch resumeResize = new CountDownLatch(1); + CompletableFuture waiting = new CompletableFuture() { + @Override + public boolean isDone() { + // This is the first check after updateLimits has detached the oldest waiter. + if (Thread.currentThread() == resizeThread.get() && detached.complete(null)) { + try { + Assert.assertTrue("Resize did not resume", resumeResize.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new AssertionError(ex); + } + } + return super.isDone(); + } + }; + queue.acquire(waiting); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + + Future resize = worker.submit(() -> { + resizeThread.set(Thread.currentThread()); + queue.updateLimits(1, 1); + }); + CompletableFuture replacement; + try { + detached.get(5, TimeUnit.SECONDS); + Assert.assertTrue(waiting.cancel(false)); + replacement = new CompletableFuture<>(); + queue.acquire(replacement); + Assert.assertFalse("The replacement should wait for the checked-out resource: " + replacement, + replacement.isDone()); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + } finally { + resumeResize.countDown(); + } + resize.get(5, TimeUnit.SECONDS); + + queue.release(held); + Assert.assertSame(held, pendingIsReady(replacement)); + check(queue).waitingsCount(0); + queue.delete(held); + } finally { + worker.shutdownNow(); + } + } + @Test public void updateLimitsDequeuesOldestWaiterAtFrontTest() { ResourceHandler rs = new ResourceHandler(); From afbd0ed3cc18f0f14987a5b8eb268bf4ba15fc2e Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 4 Dec 2026 15:12:16 +0300 Subject: [PATCH 27/29] Merge master --- .../ydb/core/auth/BackgroundIdentity.java | 49 +++----- .../ydb/core/grpc/GrpcTransportBuilder.java | 12 -- .../core/impl/FixedCallOptionsTransport.java | 4 +- .../ydb/core/impl/MultiChannelTransport.java | 7 +- .../ydb/core/impl/SingleChannelTransport.java | 7 +- .../ydb/core/impl/YdbSchedulerFactory.java | 13 +- .../tech/ydb/core/impl/YdbTransportImpl.java | 15 +-- .../tech/ydb/core/impl/auth/GrpcAuthRpc.java | 2 - .../tech/ydb/core/impl/pool/GrpcChannel.java | 18 ++- .../ydb/core/impl/pool/GrpcChannelPool.java | 10 +- .../java/tech/ydb/core/metrics/Meter.java | 12 -- .../ydb/core/metrics/OpenTelemetryMeter.java | 17 +-- .../ydb/core/auth/BackgroundIdentityTest.java | 112 ++++-------------- .../auth/CredentialsAuthProviderTest.java | 37 +++++- .../core/grpc/GrpcTransportBuilderTest.java | 28 ----- .../tech/ydb/core/impl/YdbDiscoveryTest.java | 3 +- .../ydb/core/impl/YdbTransportImplTest.java | 2 +- .../core/impl/pool/GrpcChannelPoolTest.java | 12 +- .../core/metrics/OpenTelemetryMeterTest.java | 19 --- .../ydb/table/impl/pool/SessionPoolTest.java | 4 +- .../ydb/topic/description/PartitionInfo.java | 50 +------- 21 files changed, 115 insertions(+), 318 deletions(-) diff --git a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java index 02ddc9915..048c1ef35 100644 --- a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java +++ b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java @@ -5,7 +5,6 @@ import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; @@ -20,10 +19,6 @@ public class BackgroundIdentity implements tech.ydb.auth.AuthIdentity { private static final Logger logger = LoggerFactory.getLogger(BackgroundIdentity.class); - // Max backoff will be random delay from 28.8s to 57.6s - private static final long RETRY_BACKOFF_MS = 450; - private static final long RETRY_CEILING = 6; - public interface Rpc extends AutoCloseable { class Token { private final String token; @@ -90,12 +85,6 @@ public String getToken() { return state.get().validate(clock.instant()).token(); } - private static Instant nextRetry(Instant now, int retryNumber) { - int slots = 1 << Math.min(retryNumber, RETRY_CEILING); - long delay = RETRY_BACKOFF_MS * slots; - return now.plusMillis(delay + ThreadLocalRandom.current().nextLong(delay)); - } - private T unwrap(CompletableFuture future) { try { return future.get(rpc.getTimeoutSeconds(), TimeUnit.SECONDS); @@ -154,12 +143,10 @@ public State validate(Instant now) { private class BackgroundLogin implements State { private final Rpc.Token token; - private final int retryNumber; private final CompletableFuture future = new CompletableFuture<>(); - BackgroundLogin(Rpc.Token token, int retryNumber) { + BackgroundLogin(Rpc.Token token) { this.token = token; - this.retryNumber = retryNumber; } @Override @@ -168,10 +155,7 @@ public void init() { if (nextToken != null) { future.complete(new LoggedInState(nextToken)); } else { - // retry background login after a delay counted from the failure moment, - // every getToken() would retry it immediately otherwise - Instant nextUpdateAt = nextRetry(clock.instant(), retryNumber); - future.complete(new LoggedInState(token, nextUpdateAt, retryNumber + 1)); + future.completeExceptionally(th); } }); } @@ -183,8 +167,17 @@ public String token() { @Override public State validate(Instant now) { + if (future.isCompletedExceptionally()) { + if (now.isAfter(token.expiredAt())) { + // If token had already expired, switch to sync mode and wait for finishing + return updateState(this, new SyncLogin()).validate(now); + } + // else retry background login + return updateState(this, new BackgroundLogin(token)); + } + if (future.isDone()) { - return updateState(this, future.join()).validate(now); + return updateState(this, future.join()); } return this; @@ -193,25 +186,13 @@ public State validate(Instant now) { private class LoggedInState implements State { private final Rpc.Token token; - private final Instant updateAt; - private final int failedUpdates; LoggedInState(Rpc.Token token) { - this(token, token.updateAt(), 0); - } - - LoggedInState(Rpc.Token token, Instant updateAt, int failedUpdates) { this.token = token; - this.updateAt = updateAt; - this.failedUpdates = failedUpdates; } @Override - public void init() { - if (failedUpdates > 0) { - logger.warn("background token update failed {} time(s), next attempt at {}", failedUpdates, updateAt); - } - } + public void init() { } @Override public String token() { @@ -224,8 +205,8 @@ public State validate(Instant now) { // If token had already expired, switch to sync mode and wait for finishing return updateState(this, new SyncLogin()).validate(now); } - if (now.isAfter(updateAt)) { - return updateState(this, new BackgroundLogin(token, failedUpdates)); + if (now.isAfter(token.updateAt())) { + return updateState(this, new BackgroundLogin(token)); } return this; } diff --git a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java index 9de5023d2..a014bf782 100644 --- a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java +++ b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java @@ -86,7 +86,6 @@ public enum InitMode { private AuthRpcProvider authProvider = NopAuthProvider.INSTANCE; private long readTimeoutMillis = 0; private long discoveryTimeoutMillis = 60_000; - private Duration channelShutdownTimeout = Duration.ofSeconds(5); private boolean useDefaultGrpcResolver = false; private GrpcCompression compression = GrpcCompression.NO_COMPRESSION; private InitMode initMode = InitMode.SYNC; @@ -192,10 +191,6 @@ public long getDiscoveryTimeoutMillis() { return discoveryTimeoutMillis; } - public Duration getChannelShutdownTimeout() { - return channelShutdownTimeout; - } - public GrpcCompression getGrpcCompression() { return compression; } @@ -360,13 +355,6 @@ public GrpcTransportBuilder withDiscoveryTimeout(long timeout, TimeUnit unit) { return this; } - public GrpcTransportBuilder withChannelShutdownTimeout(Duration timeout) { - Preconditions.checkArgument(timeout.compareTo(Duration.ofHours(1)) < 1 && !timeout.isNegative() - && !timeout.isZero(), "withChannelShutdownTimeout must be greater than 0 and at most 1 hour"); - this.channelShutdownTimeout = timeout; - return this; - } - public GrpcTransportBuilder withGrpcKeepAliveTime(Duration time) { if (time == null) { this.grpcKeepAliveTimeMillis = null; diff --git a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java index b747b359b..4a0edfc48 100644 --- a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.concurrent.ScheduledExecutorService; import tech.ydb.core.grpc.GrpcRequestSettings; @@ -24,14 +23,13 @@ public FixedCallOptionsTransport( AuthCallOptions callOptions, String database, String buildInfo, - Duration channelShutdownTimeout, EndpointRecord endpoint, ManagedChannelFactory channelFactory) { super(endpoint, buildInfo); this.scheduler = scheduler; this.callOptions = callOptions; this.database = database; - this.channel = new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); + this.channel = new GrpcChannel(endpoint, channelFactory); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java index eea0984ca..7ea557569 100644 --- a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -36,7 +35,6 @@ public class MultiChannelTransport extends BaseGrpcTransport { private final List endpoints; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; - private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public MultiChannelTransport(GrpcTransportBuilder builder, List hosts) { @@ -53,8 +51,7 @@ public MultiChannelTransport(GrpcTransportBuilder builder, List hos .collect(Collectors.toList()); this.callOptions = new AuthCallOptions(scheduler, endpoints, channelFactory, builder); - this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler, channelShutdownTimeout); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler); this.endpointPool = new EndpointPool(BalancingSettings.defaultInstance()); this.endpointPool.setNewState(null, Piles.EMPTY, endpoints); } @@ -73,7 +70,7 @@ public String getDatabase() { protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); + YdbSchedulerFactory.shutdownScheduler(scheduler); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java index 132d35f37..b68177117 100644 --- a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.Collections; import java.util.concurrent.ScheduledExecutorService; @@ -23,7 +22,6 @@ public class SingleChannelTransport extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final GrpcChannel channel; private final String database; - private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public SingleChannelTransport(GrpcTransportBuilder builder) { @@ -33,8 +31,7 @@ public SingleChannelTransport(GrpcTransportBuilder builder) { logger.info("creating single channel transport with endpoint {}", serverEndpoint); this.database = Strings.nullToEmpty(builder.getDatabase()); - this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); - this.channel = new GrpcChannel(serverEndpoint, channelFactory, channelShutdownTimeout); + this.channel = new GrpcChannel(serverEndpoint, channelFactory); this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions( scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder @@ -55,7 +52,7 @@ public String getDatabase() { protected void shutdown() { channel.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); + YdbSchedulerFactory.shutdownScheduler(scheduler); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java index d9fd8ca09..93b782559 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl; -import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -26,7 +25,7 @@ * @author Aleksandr Gorshenin */ public class YdbSchedulerFactory { - /** Minimal time to wait for scheduler tasks, including the ones closing grpc channels */ + /** Scheduler waits for closing of channels so this timeout must be greater that GrpcChannel.WAIT_FOR_CLOSING_MS */ private static final long WAIT_FOR_SHUTDOWN_MS = 2 * 5000; private static final Logger logger = LoggerFactory.getLogger(YdbSchedulerFactory.class); @@ -39,22 +38,16 @@ public static ScheduledExecutorService createScheduler() { return Executors.newScheduledThreadPool(threads, new YdbThreadFactory()); } - @Deprecated public static boolean shutdownScheduler(ScheduledExecutorService scheduler) { - return shutdownScheduler(scheduler, Duration.ofMillis(WAIT_FOR_SHUTDOWN_MS)); - } - - public static boolean shutdownScheduler(ScheduledExecutorService scheduler, Duration timeout) { - long waitMs = Math.max(timeout.toMillis(), WAIT_FOR_SHUTDOWN_MS); try { scheduler.shutdown(); - boolean closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); + boolean closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown timeout exceeded, terminate"); for (Runnable task: scheduler.shutdownNow()) { logger.warn(" task {} is terminated", task); } - closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); + closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown problem"); } diff --git a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java index f3f4fc0b9..dd6410b6f 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java @@ -37,7 +37,6 @@ public class YdbTransportImpl extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; - private final Duration channelShutdownTimeout; private final YdbDiscovery discovery; private final Tracer tracer; @@ -56,10 +55,8 @@ public YdbTransportImpl(GrpcTransportBuilder builder) { this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions(scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler, builder.getChannelShutdownTimeout()); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler); this.endpointPool = new EndpointPool(balancingSettings); - this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); - DiscoveryHandler handler = new DiscoveryHandler(builder.getBuildInfo()); this.discovery = new YdbDiscovery(handler, scheduler, database, discoveryTimeout); } @@ -87,7 +84,7 @@ protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); + YdbSchedulerFactory.shutdownScheduler(scheduler); } @Override @@ -159,13 +156,7 @@ public CompletableFuture handleEndpoints(List endpoints public GrpcTransport createDiscoveryTransport() { String buildInfo = Observability.getDiscoveryBuildInfo(baseBuildInfo); return new FixedCallOptionsTransport( - scheduler, - callOptions, - database, - buildInfo, - Duration.ofSeconds(1), // discovery transport must not use long-life calls - serverEndpoint, - channelFactory + scheduler, callOptions, database, buildInfo, serverEndpoint, channelFactory ); } } diff --git a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java index 820b66101..8a7afcf5c 100644 --- a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java +++ b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.auth; -import java.time.Duration; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; @@ -65,7 +64,6 @@ public GrpcTransport createTransport() { new AuthCallOptions(), database, buildInfo, - Duration.ofSeconds(1), // auth provider transport must not use long-life calls endpoints.get(endpointIdx.get()), channelFactory ); diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java index 1e6c662a4..2e9a1135d 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.pool; -import java.time.Duration; import java.util.concurrent.TimeUnit; import io.grpc.Channel; @@ -13,17 +12,18 @@ * @author Nikolay Perfilov */ public final class GrpcChannel implements Runnable { + + /* Channel shutdown waits for finish of active grpc calls, so there must be enough time to complete them all */ + static final long WAIT_FOR_CLOSING_MS = 5000; private static final Logger logger = LoggerFactory.getLogger(GrpcChannel.class); private final EndpointRecord endpoint; private final ManagedChannel channel; - private final Duration shutdownTimeout; - public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory, Duration shutdownTimeout) { + public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory) { try { logger.debug("Creating grpc channel with {}", endpoint); this.endpoint = endpoint; - this.shutdownTimeout = shutdownTimeout; this.channel = factory.newManagedChannel(endpoint.getHost(), endpoint.getPort(), endpoint.getAuthority()); checkState(); } catch (Throwable th) { @@ -49,9 +49,8 @@ public boolean shutdown() { } try { - long deadline = System.nanoTime() + shutdownTimeout.toNanos(); initShutdown(); - return awaitTermination(deadline); + return awaitTermination(closingDeadline()); } catch (InterruptedException e) { logger.warn("transport shutdown interrupted for channel {}: ", endpoint, e); Thread.currentThread().interrupt(); @@ -61,6 +60,13 @@ public boolean shutdown() { } } + /** + * @return the {@link System#nanoTime()} based deadline for the termination of channels shut down now + */ + static long closingDeadline() { + return System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_FOR_CLOSING_MS); + } + /** * Initiates an orderly shutdown: new calls are rejected, but the active ones are allowed to complete. */ diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java index 76ebf68c5..f36a8b1b9 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.pool; -import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -26,13 +25,10 @@ public class GrpcChannelPool { private final Map channels = new ConcurrentHashMap<>(); private final ManagedChannelFactory channelFactory; private final ScheduledExecutorService executor; - private final Duration channelShutdownTimeout; - public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor, - Duration channelShutdownTimeout) { + public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor) { this.channelFactory = channelFactory; this.executor = executor; - this.channelShutdownTimeout = channelShutdownTimeout; } public Set getReadyEndpoints() { @@ -46,7 +42,7 @@ public GrpcChannel getChannel(EndpointRecord endpoint) { return result != null ? result : channels.computeIfAbsent(endpoint.getHostAndPort(), (key) -> { logger.debug("channel {} was not found in pool, creating one...", endpoint.getHostAndPort()); - return new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); + return new GrpcChannel(endpoint, channelFactory); }); } @@ -62,7 +58,7 @@ private CompletableFuture shutdownChannels(Collection chan // instead of waiting for each other channelsList.forEach(GrpcChannel::initShutdown); return CompletableFuture.supplyAsync(() -> { - long deadline = System.nanoTime() + channelShutdownTimeout.toNanos(); + long deadline = GrpcChannel.closingDeadline(); int closed = 0; try { diff --git a/core/src/main/java/tech/ydb/core/metrics/Meter.java b/core/src/main/java/tech/ydb/core/metrics/Meter.java index e43d3b9e0..fde4c3fd1 100644 --- a/core/src/main/java/tech/ydb/core/metrics/Meter.java +++ b/core/src/main/java/tech/ydb/core/metrics/Meter.java @@ -1,6 +1,5 @@ package tech.ydb.core.metrics; -import java.util.List; import java.util.function.Consumer; import io.grpc.ExperimentalApi; @@ -17,21 +16,10 @@ default LongCounter createCounter(String name, String unit, String description) return LongCounter.NOOP; } - /** - * Creates a histogram of durations in seconds. {@link OpenTelemetryMeter} uses the OpenTelemetry database - * semantic conventions latency bucket boundaries. - */ default DoubleHistogram createHistogram(String name, String unit, String description) { return DoubleHistogram.NOOP; } - /** - * Creates a histogram with recommended explicit bucket boundaries. - */ - default DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { - return DoubleHistogram.NOOP; - } - /** * Creates a gauge callback without a registration handle. * diff --git a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java index 5c840ddde..6f817a769 100644 --- a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java +++ b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java @@ -1,7 +1,5 @@ package tech.ydb.core.metrics; -import java.util.Arrays; -import java.util.List; import java.util.Objects; import java.util.function.Consumer; @@ -24,14 +22,6 @@ public final class OpenTelemetryMeter implements Meter { private static final String DEFAULT_SCOPE = "tech.ydb.sdk"; - /** - * Latency bucket boundaries in seconds recommended by the OpenTelemetry database semantic conventions for - * {@code db.client.operation.duration}: - * Semantic conventions for database - * client metrics. - */ - private static final List LATENCY_BUCKETS = Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d); - private final io.opentelemetry.api.metrics.Meter meter; private OpenTelemetryMeter(io.opentelemetry.api.metrics.Meter meter) { @@ -62,12 +52,7 @@ public LongCounter createCounter(String name, String unit, String description) { @Override public DoubleHistogram createHistogram(String name, String unit, String description) { - return createHistogram(name, unit, description, LATENCY_BUCKETS); - } - - @Override - public DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { - DoubleHistogramBuilder builder = meter.histogramBuilder(name).setExplicitBucketBoundariesAdvice(buckets); + DoubleHistogramBuilder builder = meter.histogramBuilder(name); if (unit != null) { builder.setUnit(unit); } diff --git a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java index 2b1c69831..4a9ed0221 100644 --- a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java +++ b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java @@ -1,104 +1,36 @@ package tech.ydb.core.auth; import java.time.Clock; +import java.time.Duration; import java.time.Instant; +import java.time.ZoneId; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import org.mockito.Mockito; - public class BackgroundIdentityTest { - private final Clock clock = Mockito.mock(Clock.class); - private final BackgroundIdentity.Rpc rpc = Mockito.mock(BackgroundIdentity.Rpc.class); - - // Wednesday, June 1, 2022 00:00:00 UTC - private final Instant now = Instant.ofEpochSecond(1654041600); - private final AtomicReference currentTime = new AtomicReference<>(now); - - @Before - public void init() { - Mockito.when(clock.instant()).thenAnswer(invocation -> currentTime.get()); - Mockito.when(rpc.getTimeoutSeconds()).thenReturn(10); - } - - @Test - public void retryFailsTest() { - CompletableFuture req1 = new CompletableFuture<>(); - CompletableFuture req2 = new CompletableFuture<>(); - CompletableFuture req3 = new CompletableFuture<>(); - CompletableFuture req4 = new CompletableFuture<>(); - - Mockito.when(rpc.getTokenAsync()) - .thenReturn(req1) - .thenReturn(req2) - .thenReturn(req3) - .thenReturn(req4); - - BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); - req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); - Assert.assertEquals("token-1", identity.getToken()); - - currentTime.set(now.plusMillis(101)); - Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh - req2.completeExceptionally(new RuntimeException("first refresh failed")); - Assert.assertEquals("token-1", identity.getToken()); // schedules a retry 450–899 ms later - Assert.assertEquals("token-1", identity.getToken()); // repeated reads do not retry immediately - Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); + private final Instant now = Instant.EPOCH; + private final Clock clock = Clock.fixed(now, ZoneId.of("UTC")); - currentTime.set(now.plusMillis(551)); // minimum delay is 450 ms; the deadline comparison is strict - Assert.assertEquals("token-1", identity.getToken()); - Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); + private static class MockedRpc implements BackgroundIdentity.Rpc { + private final CompletableFuture tokenFuture = new CompletableFuture<>(); - currentTime.set(now.plusMillis(1001)); // 900 ms guarantees the first retry deadline has passed - Assert.assertEquals("token-1", identity.getToken()); // starts the second refresh - req3.completeExceptionally(new RuntimeException("second refresh failed")); - Assert.assertEquals("token-1", identity.getToken()); // schedules a 900–1799 ms backoff - Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + @Override + public CompletableFuture getTokenAsync() { + return tokenFuture; + } - currentTime.set(now.plusMillis(1900)); // 899 ms after failure is below the second backoff minimum - Assert.assertEquals("token-1", identity.getToken()); - Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); - - currentTime.set(now.plusMillis(2801)); // 1800 ms guarantees the second retry deadline has passed - Assert.assertEquals("token-1", identity.getToken()); // starts the third refresh - req4.complete(new BackgroundIdentity.Rpc.Token("token-2", now.plusSeconds(7200), now.plusMillis(5000))); - Assert.assertEquals("token-2", identity.getToken()); - Mockito.verify(rpc, Mockito.times(4)).getTokenAsync(); - } - - @Test - public void retryDelayStartsFromFailureTest() { - CompletableFuture req1 = new CompletableFuture<>(); - CompletableFuture req2 = new CompletableFuture<>(); - CompletableFuture req3 = new CompletableFuture<>(); - - Mockito.when(rpc.getTokenAsync()) - .thenReturn(req1) - .thenReturn(req2) - .thenReturn(req3); - - BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); - req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); - Assert.assertEquals("token-1", identity.getToken()); - - currentTime.set(now.plusMillis(101)); - Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh - req2.completeExceptionally(new RuntimeException("first refresh failed")); - - currentTime.set(now.plusMillis(1101)); // the first retry delay (450-899 ms) has passed since the failure - Assert.assertEquals("token-1", identity.getToken()); // starts the retry immediately - Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + @Override + public int getTimeoutSeconds() { + return 60; + } } @Test(timeout = 30_000) public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { - CompletableFuture f1 = new CompletableFuture<>(); - Mockito.when(rpc.getTokenAsync()).thenReturn(f1); - + MockedRpc rpc = new MockedRpc(); BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); AtomicReference caught = new AtomicReference<>(); @@ -117,11 +49,19 @@ public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedExceptio reader.join(); Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); - Assert.assertTrue(caught.get().getClass() == RuntimeException.class); - Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); + Assert.assertFalse( + "interrupt must not surface as a NullPointerException", + caught.get() instanceof NullPointerException + ); // the identity must recover once the login completes - f1.complete(new BackgroundIdentity.Rpc.Token("token-value", now.plusSeconds(3600), now.plusSeconds(1800))); + rpc.getTokenAsync().complete( + new BackgroundIdentity.Rpc.Token( + "token-value", + now.plus(Duration.ofHours(2)), + now.plus(Duration.ofHours(1)) + ) + ); Assert.assertEquals("token-value", identity.getToken()); } diff --git a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java index 139004612..4ed8bf832 100644 --- a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java +++ b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.time.Instant; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicReference; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.Any; @@ -202,8 +203,42 @@ public void syncRefreshTokenTest() { identity.close(); } + @Test + public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { + Mockito.when(clock.instant()).thenReturn(now); + + CompletableFuture> result = new CompletableFuture<>(); + Mockito.when(transport.unaryCall(Mockito.eq(AuthServiceGrpc.getLoginMethod()), Mockito.any(), Mockito.any())) + .thenReturn(result); + + tech.ydb.auth.AuthIdentity identity = createAuth("user", "password"); + + AtomicReference caught = new AtomicReference<>(); + Thread reader = new Thread(() -> { + try { + identity.getToken(); + } catch (Throwable th) { + caught.set(th); + } + }); + + reader.start(); + reader.interrupt(); + reader.join(); + + Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); + Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); + + String token = JwtBuilder.create(now.plus(Duration.ofHours(2)), now); + result.complete(Result.success(responseOk(token))); + + // the identity must recover once the login completes + Assert.assertEquals(token, identity.getToken()); + } + private tech.ydb.auth.AuthIdentity createAuth(String login, String password) { - return new StaticCredentials(clock, login, password).createAuthIdentity(rpc); + return new StaticCredentials(clock, login, password) + .createAuthIdentity(rpc); } private static YdbAuth.LoginResponse responseOk(String token) { diff --git a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java index e43dfff01..64880f96f 100644 --- a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java +++ b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java @@ -1,7 +1,5 @@ package tech.ydb.core.grpc; -import java.time.Duration; - import org.junit.Assert; import org.junit.Test; @@ -21,7 +19,6 @@ public void defaultValuesTest() { Assert.assertNull(builder.getCert()); Assert.assertEquals(GrpcTransportBuilder.InitMode.SYNC, builder.getInitMode()); Assert.assertNotNull(builder.getManagedChannelFactory()); - Assert.assertEquals(Duration.ofSeconds(5), builder.getChannelShutdownTimeout()); } @Test @@ -54,29 +51,4 @@ public void balancingSettingsTest() { Assert.assertEquals(BalancingSettings.Policy.USE_DETECT_LOCAL_DC, mixed.getPolicy()); Assert.assertNull(mixed.getPreferableLocation()); } - - @Test - public void channelShutdownTimeoutTest() { - GrpcTransportBuilder builder = GrpcTransport.forConnectionString(YDB); - - Exception ex1 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ZERO)); - Exception ex2 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(5).negated())); - Exception ex3 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofHours(1).plusNanos(1))); - Exception ex4 = Assert.assertThrows(IllegalArgumentException.class, - () -> builder.withChannelShutdownTimeout(Duration.ofMillis(Long.MAX_VALUE))); - - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex1.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex2.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex3.getMessage()); - Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex4.getMessage()); - - builder.withChannelShutdownTimeout(Duration.ofMinutes(10)); - Assert.assertEquals(Duration.ofSeconds(600), builder.getChannelShutdownTimeout()); - - builder.withChannelShutdownTimeout(Duration.ofHours(1)); - Assert.assertEquals(Duration.ofHours(1), builder.getChannelShutdownTimeout()); - } } diff --git a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java index 1bc3b818e..9414f5d84 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java @@ -299,8 +299,7 @@ public Instant instant() { public GrpcTransport createDiscoveryTransport() { EndpointRecord discovery = new EndpointRecord("unknown", 1234); AuthCallOptions options = new AuthCallOptions(); - return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", Duration.ofSeconds(1), - discovery, channelFactory); + return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", discovery, channelFactory); } @Override diff --git a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java index 83e7b7b6f..aef1d5259 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java @@ -313,7 +313,7 @@ public void customSchedulerTest() { Assert.assertFalse(scheduler.isShutdown()); Assert.assertFalse(scheduler.isTerminated()); - YdbSchedulerFactory.shutdownScheduler(custom, Duration.ofSeconds(1)); + YdbSchedulerFactory.shutdownScheduler(custom); } @Test diff --git a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java index a79423150..42cc0495d 100644 --- a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java +++ b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java @@ -1,6 +1,5 @@ package tech.ydb.core.impl.pool; -import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -38,7 +37,6 @@ public void setUp() { } @After - @SuppressWarnings("deprecation") public void tearDown() { YdbSchedulerFactory.shutdownScheduler(scheduler); } @@ -48,7 +46,7 @@ public void simpleTest() { EndpointRecord e1 = new EndpointRecord("host1", 1234, 10); EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); Assert.assertEquals(0, pool.getChannels().size()); GrpcChannel channel1 = pool.getChannel(e1); @@ -81,7 +79,7 @@ public void removeChannels() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -140,7 +138,7 @@ public void badShutdownTest() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -202,7 +200,7 @@ private GrpcChannelPool poolWithBusyChannels(ScheduledExecutorService executor, Mockito.when(factoryMock.newManagedChannel(Mockito.any(), Mockito.anyInt(), Mockito.isNull())) .thenReturn(c1, c2, c3); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor, Duration.ofSeconds(5)); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor); pool.getChannel(new EndpointRecord("host1", 1234, 10)); pool.getChannel(new EndpointRecord("host1", 1235, 11)); pool.getChannel(new EndpointRecord("host1", 1236, 12)); @@ -228,7 +226,7 @@ public void channelsShutdownInParallelTest() throws InterruptedException { // and they share one deadline, so the last channel waits only for the rest of it Assert.assertEquals(3, awaitTimeouts.size()); - long fullTimeout = Duration.ofSeconds(5).toNanos(); + long fullTimeout = TimeUnit.MILLISECONDS.toNanos(GrpcChannel.WAIT_FOR_CLOSING_MS); long lastTimeout = awaitTimeouts.get(2); Assert.assertTrue("Unexpected timeout " + lastTimeout, lastTimeout <= fullTimeout - 2 * 300_000_000L); } diff --git a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java index 58b1d05af..17287ecf8 100644 --- a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java +++ b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java @@ -1,7 +1,6 @@ package tech.ydb.core.metrics; import java.io.IOException; -import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; @@ -75,24 +74,6 @@ public void histogramReportsValueAndAttributes() { Assert.assertEquals("my-pool", point.getAttributes().get(POOL)); } - @Test - public void histogramUsesLatencyBucketsByDefault() { - meter.createHistogram("ydb.test.latency", "s", "test latency").record(0.02d); - - HistogramPointData point = single("ydb.test.latency").getHistogramData().getPoints().iterator().next(); - Assert.assertEquals(Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d), point.getBoundaries()); - Assert.assertEquals(Arrays.asList(0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), point.getCounts()); - } - - @Test - public void histogramUsesExplicitBuckets() { - meter.createHistogram("ydb.test.buckets", "{attempt}", "test buckets", Arrays.asList(1d, 2d, 5d)).record(3d); - - HistogramPointData point = single("ydb.test.buckets").getHistogramData().getPoints().iterator().next(); - Assert.assertEquals(Arrays.asList(1d, 2d, 5d), point.getBoundaries()); - Assert.assertEquals(Arrays.asList(0L, 0L, 1L, 0L), point.getCounts()); - } - @Test public void gaugeInvokesCallbackOnCollect() { AtomicLong value = new AtomicLong(7L); diff --git a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java index e38e72d28..d8730e621 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java @@ -104,7 +104,7 @@ public void increaseLimitsTest() { tableRpc.check().sessionRequests(1); check(pool).idle(0).acquired(0).pending(1).size(0, 1).totalClient(0, 0).totalServer(1, 0, 0, 0); - // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue + // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue for (int i = 0; i < wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } @@ -149,7 +149,7 @@ public void decreaseLimitsTest() { tableRpc.check().sessionRequests(2); check(pool).idle(0).acquired(0).pending(2).size(0, 2).totalClient(0, 0).totalServer(2, 0, 0, 0); - // and WAITING_LIMIT_FACTOR extra requests will be in waiting queue + // and WAITINGS_LIMIT_FACTOR extra requests will be in waitings queue for (int i = 0; i < 2 * wsize; i += 1) { futures.addLast(pendingFuture(pool.acquire(TIMEOUT))); } diff --git a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java index ce2b8bd18..0f7474210 100644 --- a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java +++ b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java @@ -6,7 +6,6 @@ import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; -import com.google.protobuf.ByteString; import tech.ydb.proto.topic.YdbTopic; @@ -19,11 +18,6 @@ public class PartitionInfo { private final List childPartitionIds; private final List parentPartitionIds; private final PartitionStats partitionStats; - private final boolean keyRange; - @Nullable - private final ByteString fromBound; - @Nullable - private final ByteString toBound; public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.partitionId = info.getPartitionId(); @@ -31,10 +25,6 @@ public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.childPartitionIds = ImmutableList.copyOf(info.getChildPartitionIdsList()); this.parentPartitionIds = ImmutableList.copyOf(info.getParentPartitionIdsList()); this.partitionStats = info.hasPartitionStats() ? new PartitionStats(info.getPartitionStats()) : null; - this.keyRange = info.hasKeyRange(); - YdbTopic.PartitionKeyRange range = info.getKeyRange(); - this.fromBound = range.hasFromBound() ? range.getFromBound() : null; - this.toBound = range.hasToBound() ? range.getToBound() : null; } public long getPartitionId() { @@ -53,38 +43,6 @@ public List getParentPartitionIds() { return parentPartitionIds; } - /** - * Whether the server supplied a key range, including a range with both ends unbounded. - * @return true if key-range metadata is present - */ - public boolean hasKeyRange() { - return keyRange; - } - - public boolean hasFromBound() { - return fromBound != null; - } - - public boolean hasToBound() { - return toBound != null; - } - - /** - * Inclusive lower bound, compared as unsigned bytes. Empty means unbounded. - * @return a defensive copy of the bound - */ - public byte[] getFromBound() { - return fromBound == null ? new byte[0] : fromBound.toByteArray(); - } - - /** - * Exclusive upper bound, compared as unsigned bytes. Empty means unbounded. - * @return a defensive copy of the bound - */ - public byte[] getToBound() { - return toBound == null ? new byte[0] : toBound.toByteArray(); - } - @Nullable public PartitionStats getPartitionStats() { return partitionStats; @@ -103,15 +61,11 @@ public boolean equals(Object o) { active == that.active && Objects.equals(childPartitionIds, that.childPartitionIds) && Objects.equals(parentPartitionIds, that.parentPartitionIds) && - Objects.equals(partitionStats, that.partitionStats) && - keyRange == that.keyRange && - Objects.equals(fromBound, that.fromBound) && - Objects.equals(toBound, that.toBound); + Objects.equals(partitionStats, that.partitionStats); } @Override public int hashCode() { - return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats, - keyRange, fromBound, toBound); + return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats); } } From a020e5d2d229739b1c060de237f828f0b8790f0d Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 4 Dec 2026 15:26:31 +0300 Subject: [PATCH 28/29] Merge master --- CHANGELOG.md | 12 +- .../ydb/core/auth/BackgroundIdentity.java | 49 +++++--- .../ydb/core/grpc/GrpcTransportBuilder.java | 12 ++ .../core/impl/FixedCallOptionsTransport.java | 4 +- .../ydb/core/impl/MultiChannelTransport.java | 7 +- .../ydb/core/impl/SingleChannelTransport.java | 7 +- .../ydb/core/impl/YdbSchedulerFactory.java | 13 +- .../tech/ydb/core/impl/YdbTransportImpl.java | 15 ++- .../tech/ydb/core/impl/auth/GrpcAuthRpc.java | 2 + .../tech/ydb/core/impl/pool/GrpcChannel.java | 18 +-- .../ydb/core/impl/pool/GrpcChannelPool.java | 10 +- .../java/tech/ydb/core/metrics/Meter.java | 12 ++ .../ydb/core/metrics/OpenTelemetryMeter.java | 17 ++- .../ydb/core/auth/BackgroundIdentityTest.java | 112 ++++++++++++++---- .../auth/CredentialsAuthProviderTest.java | 37 +----- .../core/grpc/GrpcTransportBuilderTest.java | 28 +++++ .../tech/ydb/core/impl/YdbDiscoveryTest.java | 3 +- .../ydb/core/impl/YdbTransportImplTest.java | 2 +- .../core/impl/pool/GrpcChannelPoolTest.java | 12 +- .../core/metrics/OpenTelemetryMeterTest.java | 19 +++ .../ydb/topic/description/PartitionInfo.java | 50 +++++++- 21 files changed, 327 insertions(+), 114 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90f512701..fccb45429 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,16 @@ +* Query: allowed null operation name in SessionRetryContext, retry metrics are reported without `operation.name` attribute +* Table: allowed null operation name in SessionRetryContext, retry metrics are reported without `operation.name` attribute +* Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately + +## 2.5.1 ## * 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 -* Table/Query: removed canceled or timed-out session acquires from the waiting queue immediately +* Core: added GrpcTransportBuilder.withChannelShutdownTimeout option +* Core: added backoff with jitter to background token refresh retries +* Core: updated metrics schema version to 0.3.0 +* 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 +* Topic: added partition key ranges to PartitionInfo ## 2.5.0 ## * Core: upgraded to grpc-java v1.82.4 diff --git a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java index 048c1ef35..02ddc9915 100644 --- a/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java +++ b/core/src/main/java/tech/ydb/core/auth/BackgroundIdentity.java @@ -5,6 +5,7 @@ import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; @@ -19,6 +20,10 @@ public class BackgroundIdentity implements tech.ydb.auth.AuthIdentity { private static final Logger logger = LoggerFactory.getLogger(BackgroundIdentity.class); + // Max backoff will be random delay from 28.8s to 57.6s + private static final long RETRY_BACKOFF_MS = 450; + private static final long RETRY_CEILING = 6; + public interface Rpc extends AutoCloseable { class Token { private final String token; @@ -85,6 +90,12 @@ public String getToken() { return state.get().validate(clock.instant()).token(); } + private static Instant nextRetry(Instant now, int retryNumber) { + int slots = 1 << Math.min(retryNumber, RETRY_CEILING); + long delay = RETRY_BACKOFF_MS * slots; + return now.plusMillis(delay + ThreadLocalRandom.current().nextLong(delay)); + } + private T unwrap(CompletableFuture future) { try { return future.get(rpc.getTimeoutSeconds(), TimeUnit.SECONDS); @@ -143,10 +154,12 @@ public State validate(Instant now) { private class BackgroundLogin implements State { private final Rpc.Token token; + private final int retryNumber; private final CompletableFuture future = new CompletableFuture<>(); - BackgroundLogin(Rpc.Token token) { + BackgroundLogin(Rpc.Token token, int retryNumber) { this.token = token; + this.retryNumber = retryNumber; } @Override @@ -155,7 +168,10 @@ public void init() { if (nextToken != null) { future.complete(new LoggedInState(nextToken)); } else { - future.completeExceptionally(th); + // retry background login after a delay counted from the failure moment, + // every getToken() would retry it immediately otherwise + Instant nextUpdateAt = nextRetry(clock.instant(), retryNumber); + future.complete(new LoggedInState(token, nextUpdateAt, retryNumber + 1)); } }); } @@ -167,17 +183,8 @@ public String token() { @Override public State validate(Instant now) { - if (future.isCompletedExceptionally()) { - if (now.isAfter(token.expiredAt())) { - // If token had already expired, switch to sync mode and wait for finishing - return updateState(this, new SyncLogin()).validate(now); - } - // else retry background login - return updateState(this, new BackgroundLogin(token)); - } - if (future.isDone()) { - return updateState(this, future.join()); + return updateState(this, future.join()).validate(now); } return this; @@ -186,13 +193,25 @@ public State validate(Instant now) { private class LoggedInState implements State { private final Rpc.Token token; + private final Instant updateAt; + private final int failedUpdates; LoggedInState(Rpc.Token token) { + this(token, token.updateAt(), 0); + } + + LoggedInState(Rpc.Token token, Instant updateAt, int failedUpdates) { this.token = token; + this.updateAt = updateAt; + this.failedUpdates = failedUpdates; } @Override - public void init() { } + public void init() { + if (failedUpdates > 0) { + logger.warn("background token update failed {} time(s), next attempt at {}", failedUpdates, updateAt); + } + } @Override public String token() { @@ -205,8 +224,8 @@ public State validate(Instant now) { // If token had already expired, switch to sync mode and wait for finishing return updateState(this, new SyncLogin()).validate(now); } - if (now.isAfter(token.updateAt())) { - return updateState(this, new BackgroundLogin(token)); + if (now.isAfter(updateAt)) { + return updateState(this, new BackgroundLogin(token, failedUpdates)); } return this; } diff --git a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java index a014bf782..9de5023d2 100644 --- a/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java +++ b/core/src/main/java/tech/ydb/core/grpc/GrpcTransportBuilder.java @@ -86,6 +86,7 @@ public enum InitMode { private AuthRpcProvider authProvider = NopAuthProvider.INSTANCE; private long readTimeoutMillis = 0; private long discoveryTimeoutMillis = 60_000; + private Duration channelShutdownTimeout = Duration.ofSeconds(5); private boolean useDefaultGrpcResolver = false; private GrpcCompression compression = GrpcCompression.NO_COMPRESSION; private InitMode initMode = InitMode.SYNC; @@ -191,6 +192,10 @@ public long getDiscoveryTimeoutMillis() { return discoveryTimeoutMillis; } + public Duration getChannelShutdownTimeout() { + return channelShutdownTimeout; + } + public GrpcCompression getGrpcCompression() { return compression; } @@ -355,6 +360,13 @@ public GrpcTransportBuilder withDiscoveryTimeout(long timeout, TimeUnit unit) { return this; } + public GrpcTransportBuilder withChannelShutdownTimeout(Duration timeout) { + Preconditions.checkArgument(timeout.compareTo(Duration.ofHours(1)) < 1 && !timeout.isNegative() + && !timeout.isZero(), "withChannelShutdownTimeout must be greater than 0 and at most 1 hour"); + this.channelShutdownTimeout = timeout; + return this; + } + public GrpcTransportBuilder withGrpcKeepAliveTime(Duration time) { if (time == null) { this.grpcKeepAliveTimeMillis = null; diff --git a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java index 4a0edfc48..b747b359b 100644 --- a/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/FixedCallOptionsTransport.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.concurrent.ScheduledExecutorService; import tech.ydb.core.grpc.GrpcRequestSettings; @@ -23,13 +24,14 @@ public FixedCallOptionsTransport( AuthCallOptions callOptions, String database, String buildInfo, + Duration channelShutdownTimeout, EndpointRecord endpoint, ManagedChannelFactory channelFactory) { super(endpoint, buildInfo); this.scheduler = scheduler; this.callOptions = callOptions; this.database = database; - this.channel = new GrpcChannel(endpoint, channelFactory); + this.channel = new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java index 7ea557569..eea0984ca 100644 --- a/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/MultiChannelTransport.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -35,6 +36,7 @@ public class MultiChannelTransport extends BaseGrpcTransport { private final List endpoints; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; + private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public MultiChannelTransport(GrpcTransportBuilder builder, List hosts) { @@ -51,7 +53,8 @@ public MultiChannelTransport(GrpcTransportBuilder builder, List hos .collect(Collectors.toList()); this.callOptions = new AuthCallOptions(scheduler, endpoints, channelFactory, builder); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler); + this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler, channelShutdownTimeout); this.endpointPool = new EndpointPool(BalancingSettings.defaultInstance()); this.endpointPool.setNewState(null, Piles.EMPTY, endpoints); } @@ -70,7 +73,7 @@ public String getDatabase() { protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler); + YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java index b68177117..132d35f37 100644 --- a/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java +++ b/core/src/main/java/tech/ydb/core/impl/SingleChannelTransport.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.Collections; import java.util.concurrent.ScheduledExecutorService; @@ -22,6 +23,7 @@ public class SingleChannelTransport extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final GrpcChannel channel; private final String database; + private final Duration channelShutdownTimeout; private final ScheduledExecutorService scheduler; public SingleChannelTransport(GrpcTransportBuilder builder) { @@ -31,7 +33,8 @@ public SingleChannelTransport(GrpcTransportBuilder builder) { logger.info("creating single channel transport with endpoint {}", serverEndpoint); this.database = Strings.nullToEmpty(builder.getDatabase()); - this.channel = new GrpcChannel(serverEndpoint, channelFactory); + this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); + this.channel = new GrpcChannel(serverEndpoint, channelFactory, channelShutdownTimeout); this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions( scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder @@ -52,7 +55,7 @@ public String getDatabase() { protected void shutdown() { channel.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler); + YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); } @Override diff --git a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java index 93b782559..d9fd8ca09 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbSchedulerFactory.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl; +import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -25,7 +26,7 @@ * @author Aleksandr Gorshenin */ public class YdbSchedulerFactory { - /** Scheduler waits for closing of channels so this timeout must be greater that GrpcChannel.WAIT_FOR_CLOSING_MS */ + /** Minimal time to wait for scheduler tasks, including the ones closing grpc channels */ private static final long WAIT_FOR_SHUTDOWN_MS = 2 * 5000; private static final Logger logger = LoggerFactory.getLogger(YdbSchedulerFactory.class); @@ -38,16 +39,22 @@ public static ScheduledExecutorService createScheduler() { return Executors.newScheduledThreadPool(threads, new YdbThreadFactory()); } + @Deprecated public static boolean shutdownScheduler(ScheduledExecutorService scheduler) { + return shutdownScheduler(scheduler, Duration.ofMillis(WAIT_FOR_SHUTDOWN_MS)); + } + + public static boolean shutdownScheduler(ScheduledExecutorService scheduler, Duration timeout) { + long waitMs = Math.max(timeout.toMillis(), WAIT_FOR_SHUTDOWN_MS); try { scheduler.shutdown(); - boolean closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); + boolean closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown timeout exceeded, terminate"); for (Runnable task: scheduler.shutdownNow()) { logger.warn(" task {} is terminated", task); } - closed = scheduler.awaitTermination(WAIT_FOR_SHUTDOWN_MS, TimeUnit.MILLISECONDS); + closed = scheduler.awaitTermination(waitMs, TimeUnit.MILLISECONDS); if (!closed) { logger.warn("ydb scheduler shutdown problem"); } diff --git a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java index dd6410b6f..f3f4fc0b9 100644 --- a/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java +++ b/core/src/main/java/tech/ydb/core/impl/YdbTransportImpl.java @@ -37,6 +37,7 @@ public class YdbTransportImpl extends BaseGrpcTransport { private final AuthCallOptions callOptions; private final EndpointPool endpointPool; private final GrpcChannelPool channelPool; + private final Duration channelShutdownTimeout; private final YdbDiscovery discovery; private final Tracer tracer; @@ -55,8 +56,10 @@ public YdbTransportImpl(GrpcTransportBuilder builder) { this.scheduler = builder.getSchedulerFactory().get(); this.callOptions = new AuthCallOptions(scheduler, Collections.singletonList(serverEndpoint), channelFactory, builder); - this.channelPool = new GrpcChannelPool(channelFactory, scheduler); + this.channelPool = new GrpcChannelPool(channelFactory, scheduler, builder.getChannelShutdownTimeout()); this.endpointPool = new EndpointPool(balancingSettings); + this.channelShutdownTimeout = builder.getChannelShutdownTimeout(); + DiscoveryHandler handler = new DiscoveryHandler(builder.getBuildInfo()); this.discovery = new YdbDiscovery(handler, scheduler, database, discoveryTimeout); } @@ -84,7 +87,7 @@ protected void shutdown() { channelPool.shutdown(); callOptions.close(); - YdbSchedulerFactory.shutdownScheduler(scheduler); + YdbSchedulerFactory.shutdownScheduler(scheduler, channelShutdownTimeout.plusSeconds(5)); } @Override @@ -156,7 +159,13 @@ public CompletableFuture handleEndpoints(List endpoints public GrpcTransport createDiscoveryTransport() { String buildInfo = Observability.getDiscoveryBuildInfo(baseBuildInfo); return new FixedCallOptionsTransport( - scheduler, callOptions, database, buildInfo, serverEndpoint, channelFactory + scheduler, + callOptions, + database, + buildInfo, + Duration.ofSeconds(1), // discovery transport must not use long-life calls + serverEndpoint, + channelFactory ); } } diff --git a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java index 8a7afcf5c..820b66101 100644 --- a/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java +++ b/core/src/main/java/tech/ydb/core/impl/auth/GrpcAuthRpc.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.auth; +import java.time.Duration; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; @@ -64,6 +65,7 @@ public GrpcTransport createTransport() { new AuthCallOptions(), database, buildInfo, + Duration.ofSeconds(1), // auth provider transport must not use long-life calls endpoints.get(endpointIdx.get()), channelFactory ); diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java index 2e9a1135d..1e6c662a4 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannel.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.pool; +import java.time.Duration; import java.util.concurrent.TimeUnit; import io.grpc.Channel; @@ -12,18 +13,17 @@ * @author Nikolay Perfilov */ public final class GrpcChannel implements Runnable { - - /* Channel shutdown waits for finish of active grpc calls, so there must be enough time to complete them all */ - static final long WAIT_FOR_CLOSING_MS = 5000; private static final Logger logger = LoggerFactory.getLogger(GrpcChannel.class); private final EndpointRecord endpoint; private final ManagedChannel channel; + private final Duration shutdownTimeout; - public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory) { + public GrpcChannel(EndpointRecord endpoint, ManagedChannelFactory factory, Duration shutdownTimeout) { try { logger.debug("Creating grpc channel with {}", endpoint); this.endpoint = endpoint; + this.shutdownTimeout = shutdownTimeout; this.channel = factory.newManagedChannel(endpoint.getHost(), endpoint.getPort(), endpoint.getAuthority()); checkState(); } catch (Throwable th) { @@ -49,8 +49,9 @@ public boolean shutdown() { } try { + long deadline = System.nanoTime() + shutdownTimeout.toNanos(); initShutdown(); - return awaitTermination(closingDeadline()); + return awaitTermination(deadline); } catch (InterruptedException e) { logger.warn("transport shutdown interrupted for channel {}: ", endpoint, e); Thread.currentThread().interrupt(); @@ -60,13 +61,6 @@ public boolean shutdown() { } } - /** - * @return the {@link System#nanoTime()} based deadline for the termination of channels shut down now - */ - static long closingDeadline() { - return System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_FOR_CLOSING_MS); - } - /** * Initiates an orderly shutdown: new calls are rejected, but the active ones are allowed to complete. */ diff --git a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java index f36a8b1b9..76ebf68c5 100644 --- a/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java +++ b/core/src/main/java/tech/ydb/core/impl/pool/GrpcChannelPool.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.pool; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -25,10 +26,13 @@ public class GrpcChannelPool { private final Map channels = new ConcurrentHashMap<>(); private final ManagedChannelFactory channelFactory; private final ScheduledExecutorService executor; + private final Duration channelShutdownTimeout; - public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor) { + public GrpcChannelPool(ManagedChannelFactory channelFactory, ScheduledExecutorService executor, + Duration channelShutdownTimeout) { this.channelFactory = channelFactory; this.executor = executor; + this.channelShutdownTimeout = channelShutdownTimeout; } public Set getReadyEndpoints() { @@ -42,7 +46,7 @@ public GrpcChannel getChannel(EndpointRecord endpoint) { return result != null ? result : channels.computeIfAbsent(endpoint.getHostAndPort(), (key) -> { logger.debug("channel {} was not found in pool, creating one...", endpoint.getHostAndPort()); - return new GrpcChannel(endpoint, channelFactory); + return new GrpcChannel(endpoint, channelFactory, channelShutdownTimeout); }); } @@ -58,7 +62,7 @@ private CompletableFuture shutdownChannels(Collection chan // instead of waiting for each other channelsList.forEach(GrpcChannel::initShutdown); return CompletableFuture.supplyAsync(() -> { - long deadline = GrpcChannel.closingDeadline(); + long deadline = System.nanoTime() + channelShutdownTimeout.toNanos(); int closed = 0; try { diff --git a/core/src/main/java/tech/ydb/core/metrics/Meter.java b/core/src/main/java/tech/ydb/core/metrics/Meter.java index fde4c3fd1..e43d3b9e0 100644 --- a/core/src/main/java/tech/ydb/core/metrics/Meter.java +++ b/core/src/main/java/tech/ydb/core/metrics/Meter.java @@ -1,5 +1,6 @@ package tech.ydb.core.metrics; +import java.util.List; import java.util.function.Consumer; import io.grpc.ExperimentalApi; @@ -16,10 +17,21 @@ default LongCounter createCounter(String name, String unit, String description) return LongCounter.NOOP; } + /** + * Creates a histogram of durations in seconds. {@link OpenTelemetryMeter} uses the OpenTelemetry database + * semantic conventions latency bucket boundaries. + */ default DoubleHistogram createHistogram(String name, String unit, String description) { return DoubleHistogram.NOOP; } + /** + * Creates a histogram with recommended explicit bucket boundaries. + */ + default DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { + return DoubleHistogram.NOOP; + } + /** * Creates a gauge callback without a registration handle. * diff --git a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java index 6f817a769..5c840ddde 100644 --- a/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java +++ b/core/src/main/java/tech/ydb/core/metrics/OpenTelemetryMeter.java @@ -1,5 +1,7 @@ package tech.ydb.core.metrics; +import java.util.Arrays; +import java.util.List; import java.util.Objects; import java.util.function.Consumer; @@ -22,6 +24,14 @@ public final class OpenTelemetryMeter implements Meter { private static final String DEFAULT_SCOPE = "tech.ydb.sdk"; + /** + * Latency bucket boundaries in seconds recommended by the OpenTelemetry database semantic conventions for + * {@code db.client.operation.duration}: + * Semantic conventions for database + * client metrics. + */ + private static final List LATENCY_BUCKETS = Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d); + private final io.opentelemetry.api.metrics.Meter meter; private OpenTelemetryMeter(io.opentelemetry.api.metrics.Meter meter) { @@ -52,7 +62,12 @@ public LongCounter createCounter(String name, String unit, String description) { @Override public DoubleHistogram createHistogram(String name, String unit, String description) { - DoubleHistogramBuilder builder = meter.histogramBuilder(name); + return createHistogram(name, unit, description, LATENCY_BUCKETS); + } + + @Override + public DoubleHistogram createHistogram(String name, String unit, String description, List buckets) { + DoubleHistogramBuilder builder = meter.histogramBuilder(name).setExplicitBucketBoundariesAdvice(buckets); if (unit != null) { builder.setUnit(unit); } diff --git a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java index 4a9ed0221..2b1c69831 100644 --- a/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java +++ b/core/src/test/java/tech/ydb/core/auth/BackgroundIdentityTest.java @@ -1,36 +1,104 @@ package tech.ydb.core.auth; import java.time.Clock; -import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; + public class BackgroundIdentityTest { - private final Instant now = Instant.EPOCH; - private final Clock clock = Clock.fixed(now, ZoneId.of("UTC")); + private final Clock clock = Mockito.mock(Clock.class); + private final BackgroundIdentity.Rpc rpc = Mockito.mock(BackgroundIdentity.Rpc.class); + + // Wednesday, June 1, 2022 00:00:00 UTC + private final Instant now = Instant.ofEpochSecond(1654041600); + private final AtomicReference currentTime = new AtomicReference<>(now); + + @Before + public void init() { + Mockito.when(clock.instant()).thenAnswer(invocation -> currentTime.get()); + Mockito.when(rpc.getTimeoutSeconds()).thenReturn(10); + } + + @Test + public void retryFailsTest() { + CompletableFuture req1 = new CompletableFuture<>(); + CompletableFuture req2 = new CompletableFuture<>(); + CompletableFuture req3 = new CompletableFuture<>(); + CompletableFuture req4 = new CompletableFuture<>(); + + Mockito.when(rpc.getTokenAsync()) + .thenReturn(req1) + .thenReturn(req2) + .thenReturn(req3) + .thenReturn(req4); + + BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); + req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); + Assert.assertEquals("token-1", identity.getToken()); + + currentTime.set(now.plusMillis(101)); + Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh + req2.completeExceptionally(new RuntimeException("first refresh failed")); + Assert.assertEquals("token-1", identity.getToken()); // schedules a retry 450–899 ms later + Assert.assertEquals("token-1", identity.getToken()); // repeated reads do not retry immediately + Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); - private static class MockedRpc implements BackgroundIdentity.Rpc { - private final CompletableFuture tokenFuture = new CompletableFuture<>(); + currentTime.set(now.plusMillis(551)); // minimum delay is 450 ms; the deadline comparison is strict + Assert.assertEquals("token-1", identity.getToken()); + Mockito.verify(rpc, Mockito.times(2)).getTokenAsync(); - @Override - public CompletableFuture getTokenAsync() { - return tokenFuture; - } + currentTime.set(now.plusMillis(1001)); // 900 ms guarantees the first retry deadline has passed + Assert.assertEquals("token-1", identity.getToken()); // starts the second refresh + req3.completeExceptionally(new RuntimeException("second refresh failed")); + Assert.assertEquals("token-1", identity.getToken()); // schedules a 900–1799 ms backoff + Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); - @Override - public int getTimeoutSeconds() { - return 60; - } + currentTime.set(now.plusMillis(1900)); // 899 ms after failure is below the second backoff minimum + Assert.assertEquals("token-1", identity.getToken()); + Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); + + currentTime.set(now.plusMillis(2801)); // 1800 ms guarantees the second retry deadline has passed + Assert.assertEquals("token-1", identity.getToken()); // starts the third refresh + req4.complete(new BackgroundIdentity.Rpc.Token("token-2", now.plusSeconds(7200), now.plusMillis(5000))); + Assert.assertEquals("token-2", identity.getToken()); + Mockito.verify(rpc, Mockito.times(4)).getTokenAsync(); + } + + @Test + public void retryDelayStartsFromFailureTest() { + CompletableFuture req1 = new CompletableFuture<>(); + CompletableFuture req2 = new CompletableFuture<>(); + CompletableFuture req3 = new CompletableFuture<>(); + + Mockito.when(rpc.getTokenAsync()) + .thenReturn(req1) + .thenReturn(req2) + .thenReturn(req3); + + BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); + req1.complete(new BackgroundIdentity.Rpc.Token("token-1", now.plusSeconds(3600), now.plusMillis(100))); + Assert.assertEquals("token-1", identity.getToken()); + + currentTime.set(now.plusMillis(101)); + Assert.assertEquals("token-1", identity.getToken()); // starts the first background refresh + req2.completeExceptionally(new RuntimeException("first refresh failed")); + + currentTime.set(now.plusMillis(1101)); // the first retry delay (450-899 ms) has passed since the failure + Assert.assertEquals("token-1", identity.getToken()); // starts the retry immediately + Mockito.verify(rpc, Mockito.times(3)).getTokenAsync(); } @Test(timeout = 30_000) public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { - MockedRpc rpc = new MockedRpc(); + CompletableFuture f1 = new CompletableFuture<>(); + Mockito.when(rpc.getTokenAsync()).thenReturn(f1); + BackgroundIdentity identity = new BackgroundIdentity(clock, rpc); AtomicReference caught = new AtomicReference<>(); @@ -49,19 +117,11 @@ public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedExceptio reader.join(); Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); - Assert.assertFalse( - "interrupt must not surface as a NullPointerException", - caught.get() instanceof NullPointerException - ); + Assert.assertTrue(caught.get().getClass() == RuntimeException.class); + Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); // the identity must recover once the login completes - rpc.getTokenAsync().complete( - new BackgroundIdentity.Rpc.Token( - "token-value", - now.plus(Duration.ofHours(2)), - now.plus(Duration.ofHours(1)) - ) - ); + f1.complete(new BackgroundIdentity.Rpc.Token("token-value", now.plusSeconds(3600), now.plusSeconds(1800))); Assert.assertEquals("token-value", identity.getToken()); } diff --git a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java index 4ed8bf832..139004612 100644 --- a/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java +++ b/core/src/test/java/tech/ydb/core/auth/CredentialsAuthProviderTest.java @@ -4,7 +4,6 @@ import java.time.Duration; import java.time.Instant; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicReference; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.Any; @@ -203,42 +202,8 @@ public void syncRefreshTokenTest() { identity.close(); } - @Test - public void interruptedGetTokenDoesNotBreakIdentity() throws InterruptedException { - Mockito.when(clock.instant()).thenReturn(now); - - CompletableFuture> result = new CompletableFuture<>(); - Mockito.when(transport.unaryCall(Mockito.eq(AuthServiceGrpc.getLoginMethod()), Mockito.any(), Mockito.any())) - .thenReturn(result); - - tech.ydb.auth.AuthIdentity identity = createAuth("user", "password"); - - AtomicReference caught = new AtomicReference<>(); - Thread reader = new Thread(() -> { - try { - identity.getToken(); - } catch (Throwable th) { - caught.set(th); - } - }); - - reader.start(); - reader.interrupt(); - reader.join(); - - Assert.assertNotNull("interrupted getToken must report a failure", caught.get()); - Assert.assertEquals("authentication update was interrupted", caught.get().getMessage()); - - String token = JwtBuilder.create(now.plus(Duration.ofHours(2)), now); - result.complete(Result.success(responseOk(token))); - - // the identity must recover once the login completes - Assert.assertEquals(token, identity.getToken()); - } - private tech.ydb.auth.AuthIdentity createAuth(String login, String password) { - return new StaticCredentials(clock, login, password) - .createAuthIdentity(rpc); + return new StaticCredentials(clock, login, password).createAuthIdentity(rpc); } private static YdbAuth.LoginResponse responseOk(String token) { diff --git a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java index 64880f96f..e43dfff01 100644 --- a/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java +++ b/core/src/test/java/tech/ydb/core/grpc/GrpcTransportBuilderTest.java @@ -1,5 +1,7 @@ package tech.ydb.core.grpc; +import java.time.Duration; + import org.junit.Assert; import org.junit.Test; @@ -19,6 +21,7 @@ public void defaultValuesTest() { Assert.assertNull(builder.getCert()); Assert.assertEquals(GrpcTransportBuilder.InitMode.SYNC, builder.getInitMode()); Assert.assertNotNull(builder.getManagedChannelFactory()); + Assert.assertEquals(Duration.ofSeconds(5), builder.getChannelShutdownTimeout()); } @Test @@ -51,4 +54,29 @@ public void balancingSettingsTest() { Assert.assertEquals(BalancingSettings.Policy.USE_DETECT_LOCAL_DC, mixed.getPolicy()); Assert.assertNull(mixed.getPreferableLocation()); } + + @Test + public void channelShutdownTimeoutTest() { + GrpcTransportBuilder builder = GrpcTransport.forConnectionString(YDB); + + Exception ex1 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ZERO)); + Exception ex2 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ofSeconds(5).negated())); + Exception ex3 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ofHours(1).plusNanos(1))); + Exception ex4 = Assert.assertThrows(IllegalArgumentException.class, + () -> builder.withChannelShutdownTimeout(Duration.ofMillis(Long.MAX_VALUE))); + + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex1.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex2.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex3.getMessage()); + Assert.assertEquals("withChannelShutdownTimeout must be greater than 0 and at most 1 hour", ex4.getMessage()); + + builder.withChannelShutdownTimeout(Duration.ofMinutes(10)); + Assert.assertEquals(Duration.ofSeconds(600), builder.getChannelShutdownTimeout()); + + builder.withChannelShutdownTimeout(Duration.ofHours(1)); + Assert.assertEquals(Duration.ofHours(1), builder.getChannelShutdownTimeout()); + } } diff --git a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java index 9414f5d84..1bc3b818e 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbDiscoveryTest.java @@ -299,7 +299,8 @@ public Instant instant() { public GrpcTransport createDiscoveryTransport() { EndpointRecord discovery = new EndpointRecord("unknown", 1234); AuthCallOptions options = new AuthCallOptions(); - return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", discovery, channelFactory); + return new FixedCallOptionsTransport(scheduler, options, "/test", "test_sdk", Duration.ofSeconds(1), + discovery, channelFactory); } @Override diff --git a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java index aef1d5259..83e7b7b6f 100644 --- a/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java +++ b/core/src/test/java/tech/ydb/core/impl/YdbTransportImplTest.java @@ -313,7 +313,7 @@ public void customSchedulerTest() { Assert.assertFalse(scheduler.isShutdown()); Assert.assertFalse(scheduler.isTerminated()); - YdbSchedulerFactory.shutdownScheduler(custom); + YdbSchedulerFactory.shutdownScheduler(custom, Duration.ofSeconds(1)); } @Test diff --git a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java index 42cc0495d..a79423150 100644 --- a/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java +++ b/core/src/test/java/tech/ydb/core/impl/pool/GrpcChannelPoolTest.java @@ -1,5 +1,6 @@ package tech.ydb.core.impl.pool; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -37,6 +38,7 @@ public void setUp() { } @After + @SuppressWarnings("deprecation") public void tearDown() { YdbSchedulerFactory.shutdownScheduler(scheduler); } @@ -46,7 +48,7 @@ public void simpleTest() { EndpointRecord e1 = new EndpointRecord("host1", 1234, 10); EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); Assert.assertEquals(0, pool.getChannels().size()); GrpcChannel channel1 = pool.getChannel(e1); @@ -79,7 +81,7 @@ public void removeChannels() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -138,7 +140,7 @@ public void badShutdownTest() { EndpointRecord e2 = new EndpointRecord("host1", 1235, 11); EndpointRecord e3 = new EndpointRecord("host1", 1236, 12); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, scheduler, Duration.ofSeconds(5)); Assert.assertEquals(0, pool.getChannels().size()); // create three channels @@ -200,7 +202,7 @@ private GrpcChannelPool poolWithBusyChannels(ScheduledExecutorService executor, Mockito.when(factoryMock.newManagedChannel(Mockito.any(), Mockito.anyInt(), Mockito.isNull())) .thenReturn(c1, c2, c3); - GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor); + GrpcChannelPool pool = new GrpcChannelPool(factoryMock, executor, Duration.ofSeconds(5)); pool.getChannel(new EndpointRecord("host1", 1234, 10)); pool.getChannel(new EndpointRecord("host1", 1235, 11)); pool.getChannel(new EndpointRecord("host1", 1236, 12)); @@ -226,7 +228,7 @@ public void channelsShutdownInParallelTest() throws InterruptedException { // and they share one deadline, so the last channel waits only for the rest of it Assert.assertEquals(3, awaitTimeouts.size()); - long fullTimeout = TimeUnit.MILLISECONDS.toNanos(GrpcChannel.WAIT_FOR_CLOSING_MS); + long fullTimeout = Duration.ofSeconds(5).toNanos(); long lastTimeout = awaitTimeouts.get(2); Assert.assertTrue("Unexpected timeout " + lastTimeout, lastTimeout <= fullTimeout - 2 * 300_000_000L); } diff --git a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java index 17287ecf8..58b1d05af 100644 --- a/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java +++ b/core/src/test/java/tech/ydb/core/metrics/OpenTelemetryMeterTest.java @@ -1,6 +1,7 @@ package tech.ydb.core.metrics; import java.io.IOException; +import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; @@ -74,6 +75,24 @@ public void histogramReportsValueAndAttributes() { Assert.assertEquals("my-pool", point.getAttributes().get(POOL)); } + @Test + public void histogramUsesLatencyBucketsByDefault() { + meter.createHistogram("ydb.test.latency", "s", "test latency").record(0.02d); + + HistogramPointData point = single("ydb.test.latency").getHistogramData().getPoints().iterator().next(); + Assert.assertEquals(Arrays.asList(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1d, 5d, 10d), point.getBoundaries()); + Assert.assertEquals(Arrays.asList(0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), point.getCounts()); + } + + @Test + public void histogramUsesExplicitBuckets() { + meter.createHistogram("ydb.test.buckets", "{attempt}", "test buckets", Arrays.asList(1d, 2d, 5d)).record(3d); + + HistogramPointData point = single("ydb.test.buckets").getHistogramData().getPoints().iterator().next(); + Assert.assertEquals(Arrays.asList(1d, 2d, 5d), point.getBoundaries()); + Assert.assertEquals(Arrays.asList(0L, 0L, 1L, 0L), point.getCounts()); + } + @Test public void gaugeInvokesCallbackOnCollect() { AtomicLong value = new AtomicLong(7L); diff --git a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java index 0f7474210..ce2b8bd18 100644 --- a/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java +++ b/topic/src/main/java/tech/ydb/topic/description/PartitionInfo.java @@ -6,6 +6,7 @@ import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; import tech.ydb.proto.topic.YdbTopic; @@ -18,6 +19,11 @@ public class PartitionInfo { private final List childPartitionIds; private final List parentPartitionIds; private final PartitionStats partitionStats; + private final boolean keyRange; + @Nullable + private final ByteString fromBound; + @Nullable + private final ByteString toBound; public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.partitionId = info.getPartitionId(); @@ -25,6 +31,10 @@ public PartitionInfo(YdbTopic.DescribeTopicResult.PartitionInfo info) { this.childPartitionIds = ImmutableList.copyOf(info.getChildPartitionIdsList()); this.parentPartitionIds = ImmutableList.copyOf(info.getParentPartitionIdsList()); this.partitionStats = info.hasPartitionStats() ? new PartitionStats(info.getPartitionStats()) : null; + this.keyRange = info.hasKeyRange(); + YdbTopic.PartitionKeyRange range = info.getKeyRange(); + this.fromBound = range.hasFromBound() ? range.getFromBound() : null; + this.toBound = range.hasToBound() ? range.getToBound() : null; } public long getPartitionId() { @@ -43,6 +53,38 @@ public List getParentPartitionIds() { return parentPartitionIds; } + /** + * Whether the server supplied a key range, including a range with both ends unbounded. + * @return true if key-range metadata is present + */ + public boolean hasKeyRange() { + return keyRange; + } + + public boolean hasFromBound() { + return fromBound != null; + } + + public boolean hasToBound() { + return toBound != null; + } + + /** + * Inclusive lower bound, compared as unsigned bytes. Empty means unbounded. + * @return a defensive copy of the bound + */ + public byte[] getFromBound() { + return fromBound == null ? new byte[0] : fromBound.toByteArray(); + } + + /** + * Exclusive upper bound, compared as unsigned bytes. Empty means unbounded. + * @return a defensive copy of the bound + */ + public byte[] getToBound() { + return toBound == null ? new byte[0] : toBound.toByteArray(); + } + @Nullable public PartitionStats getPartitionStats() { return partitionStats; @@ -61,11 +103,15 @@ public boolean equals(Object o) { active == that.active && Objects.equals(childPartitionIds, that.childPartitionIds) && Objects.equals(parentPartitionIds, that.parentPartitionIds) && - Objects.equals(partitionStats, that.partitionStats); + Objects.equals(partitionStats, that.partitionStats) && + keyRange == that.keyRange && + Objects.equals(fromBound, that.fromBound) && + Objects.equals(toBound, that.toBound); } @Override public int hashCode() { - return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats); + return Objects.hash(partitionId, active, childPartitionIds, parentPartitionIds, partitionStats, + keyRange, fromBound, toBound); } } From b2e710e465051c199049c36d7e1d81606b846303 Mon Sep 17 00:00:00 2001 From: lebmax Date: Fri, 4 Dec 2026 15:34:52 +0300 Subject: [PATCH 29/29] Remove canceled session pool waiters promptly Propagate cancellation and timeouts in the Table and Query pools. Use an ordered concurrent map for key-based waiter removal and test immediate slot reuse during parallel cancellation and resize. --- .../java/tech/ydb/query/impl/SessionPool.java | 2 +- .../tech/ydb/query/impl/PoolMetricsTest.java | 22 ++ .../QueryClientSessionPoolWaiterTest.java | 189 +++++++++ .../tech/ydb/table/impl/pool/SessionPool.java | 4 + .../ydb/table/impl/pool/WaitingAcquires.java | 87 +++++ .../ydb/table/impl/pool/WaitingQueue.java | 66 ++-- .../ydb/table/impl/pool/SessionPoolTest.java | 50 +++ .../pool/WaitingQueueParallelChurnTest.java | 204 ++++++++++ .../ydb/table/impl/pool/WaitingQueueTest.java | 364 +++++++++++++++++- 9 files changed, 958 insertions(+), 30 deletions(-) create mode 100644 query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java create mode 100644 table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java create mode 100644 table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java diff --git a/query/src/main/java/tech/ydb/query/impl/SessionPool.java b/query/src/main/java/tech/ydb/query/impl/SessionPool.java index 5b0cf272c..ef93223e1 100644 --- a/query/src/main/java/tech/ydb/query/impl/SessionPool.java +++ b/query/src/main/java/tech/ydb/query/impl/SessionPool.java @@ -128,10 +128,10 @@ private boolean pollNext(CompletableFuture> future) { return tryComplete(future, nextSession.join()); } + future.whenComplete((result, error) -> nextSession.cancel(false)); nextSession.whenComplete((session, th) -> { if (th != null) { if (future.isDone()) { - logger.warn("can't get QuerySession, future is already canceled", th); return; } diff --git a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java index 7fb29f879..65d1a85d6 100644 --- a/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java +++ b/query/src/test/java/tech/ydb/query/impl/PoolMetricsTest.java @@ -139,6 +139,22 @@ public void sessionLifecycleRecordsCounters() { verify(counter("failed"), never()).add(anyLong(), any()); } + @Test + public void cancelledAcquireRemovesPendingRequest() { + try (SessionPool pool = createPool(0, 1)) { + QuerySession occupied = acquireReady(pool); + CompletableFuture> cancelled = pool.acquire(TIMEOUT); + + Assert.assertTrue(cancelled.cancel(false)); + Assert.assertTrue(cancelled.isCancelled()); + assertPendingRequests(0L); + + occupied.close(); + assertPendingRequests(0L); + verify(counter("acquired")).add(eq(1L), argThat(poolName)); + } + } + @Test public void failedCreateRecordsFailedCounter() { rpc.overloaded = true; @@ -429,6 +445,12 @@ private void verifyClosed(String reason) { verifyNoMoreInteractions(counter("closed")); } + private void assertPendingRequests(long expected) { + LongMeasurement pending = mock(LongMeasurement.class); + gauges.get(PREFIX + "pending_requests").accept(pending); + verify(pending).record(eq(expected), argThat(poolName)); + } + private static boolean attr(Attr attr, String shortKey, String value) { return attr.getKey().equals(PREFIX + shortKey) && attr.getValue().equals(value); } diff --git a/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java b/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java new file mode 100644 index 000000000..f1a035349 --- /dev/null +++ b/query/src/test/java/tech/ydb/query/impl/QueryClientSessionPoolWaiterTest.java @@ -0,0 +1,189 @@ +package tech.ydb.query.impl; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; +import org.junit.ClassRule; +import org.junit.Test; + +import tech.ydb.core.Result; +import tech.ydb.core.StatusCode; +import tech.ydb.query.QueryClient; +import tech.ydb.query.QuerySession; +import tech.ydb.table.SessionPoolStats; +import tech.ydb.test.junit4.GrpcTransportRule; + +public class QueryClientSessionPoolWaiterTest { + private static final Duration LONG_ACQUIRE_TIMEOUT = Duration.ofMinutes(1); + private static final Duration SHORT_ACQUIRE_TIMEOUT = Duration.ofSeconds(3); + private static final long ASYNC_ASSERTION_TIMEOUT_SECONDS = 10; + private static final int MAX_QUEUE_FILL_ATTEMPTS = 100; + + @ClassRule + public static final GrpcTransportRule YDB = new GrpcTransportRule(); + + @Test + public void cancelledPublicWaiterReleasesSaturatedQueueSlotAndPreservesFifo() throws Exception { + try (QueryClient client = newClient()) { + QuerySession held = awaitSession(client.createSession(LONG_ACQUIRE_TIMEOUT)); + List>> waiters = new ArrayList<>(); + fillWaitingQueue(client, waiters); + + int cancelledIndex = waiters.size() / 2; + CompletableFuture> cancelled = waiters.get(cancelledIndex); + Assert.assertTrue("The selected waiting acquire should be cancelable", cancelled.cancel(true)); + + CompletableFuture> replacement = + acquirePendingWhenQueueHasSlot(client, LONG_ACQUIRE_TIMEOUT); + List>> liveWaiters = without(waiters, cancelledIndex); + liveWaiters.add(replacement); + + assertOnlyHeldSession(client); + Assert.assertNotNull(replacement); + Assert.assertFalse("The replacement must wait while the only session is held", replacement.isDone()); + drainInFifoOrder(client, held, liveWaiters); + } + } + + @Test + public void timedOutPublicWaiterReleasesSaturatedQueueSlot() throws Exception { + try (QueryClient client = newClient()) { + List>> waiters = new ArrayList<>(); + CompletableFuture> replacement = null; + + try (QuerySession held = awaitSession(client.createSession(LONG_ACQUIRE_TIMEOUT))) { + try { + // Put the timeout acquire into the queue before filling the remaining slots. + waiters.add(client.createSession(LONG_ACQUIRE_TIMEOUT)); + CompletableFuture> timedOut = + client.createSession(SHORT_ACQUIRE_TIMEOUT); + waiters.add(timedOut); + + fillWaitingQueue(client, waiters); + Assert.assertFalse("The queue should be observed full before the timed acquire expires", timedOut.isDone()); + + Result timeoutResult = + timedOut.get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertEquals(StatusCode.CLIENT_DEADLINE_EXPIRED, timeoutResult.getStatus().getCode()); + + // The timeout completes the public future before its cancellation callback is + // necessarily observed by this thread. Retry only the expected full-queue rejection + // until the public API admits a new waiter. + replacement = acquirePendingWhenQueueHasSlot(client, LONG_ACQUIRE_TIMEOUT); + Assert.assertNotNull(replacement); + Assert.assertFalse("The replacement must wait while the only session is held", replacement.isDone()); + assertOnlyHeldSession(client); + } finally { + for (CompletableFuture> waiter : waiters) { + waiter.cancel(true); + } + if (replacement != null) { + replacement.cancel(true); + } + } + } + } + } + + private static QueryClient newClient() { + return QueryClient.newClient(YDB) + .sessionPoolMaxSize(1) + .build(); + } + + private static QuerySession awaitSession(CompletableFuture> future) throws Exception { + Result result = future.get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertTrue("Session creation should succeed: " + result.getStatus(), result.isSuccess()); + return result.getValue(); + } + + private static void fillWaitingQueue( + QueryClient client, List>> waiters) { + for (int attempt = 0; attempt < MAX_QUEUE_FILL_ATTEMPTS; attempt += 1) { + CompletableFuture> waiter = client.createSession(LONG_ACQUIRE_TIMEOUT); + if (!waiter.isDone()) { + waiters.add(waiter); + continue; + } + + Result overflow = waiter.join(); + Assert.assertEquals( + "The queue should reject the first acquire beyond its waiting limit", + StatusCode.CLIENT_RESOURCE_EXHAUSTED, + overflow.getStatus().getCode() + ); + Assert.assertFalse("The queue should admit at least one waiter", waiters.isEmpty()); + return; + } + + Assert.fail("The bounded session-pool waiting queue did not reject an overflow acquire"); + } + + private static CompletableFuture> acquirePendingWhenQueueHasSlot( + QueryClient client, Duration timeout) throws InterruptedException { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(ASYNC_ASSERTION_TIMEOUT_SECONDS); + while (System.nanoTime() < deadlineNanos) { + CompletableFuture> candidate = client.createSession(timeout); + if (!candidate.isDone()) { + return candidate; + } + + Result result = candidate.join(); + Assert.assertEquals( + "A saturated queue may reject only with CLIENT_RESOURCE_EXHAUSTED", + StatusCode.CLIENT_RESOURCE_EXHAUSTED, + result.getStatus().getCode() + ); + Thread.sleep(5); + } + + Assert.fail("No new acquire was admitted after a waiting acquire became terminal"); + return null; + } + + private static List>> without( + List>> futures, int excludedIndex) { + List>> result = new ArrayList<>(futures.size() - 1); + for (int i = 0; i < futures.size(); i += 1) { + if (i != excludedIndex) { + result.add(futures.get(i)); + } + } + return result; + } + + private static void assertOnlyHeldSession(QueryClient client) { + SessionPoolStats stats = client.getSessionPoolStats(); + Assert.assertEquals("The only session remains acquired", 1, stats.getAcquiredCount()); + Assert.assertEquals("No session should be idle while the held session is open", 0, stats.getIdleCount()); + } + + private static void drainInFifoOrder( + QueryClient client, + QuerySession held, + List>> waiters) throws Exception { + String heldId = held.getId(); + QuerySession current = held; + for (int i = 0; i < waiters.size(); i += 1) { + current.close(); + + Result result = waiters.get(i).get(ASYNC_ASSERTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertTrue("The next live waiter should receive the released session", result.isSuccess()); + QuerySession next = result.getValue(); + Assert.assertEquals("The pool should hand off the same session in FIFO order", heldId, next.getId()); + + for (int j = i + 1; j < waiters.size(); j += 1) { + Assert.assertFalse("A later waiter must remain pending", waiters.get(j).isDone()); + } + current = next; + } + + current.close(); + Assert.assertEquals(0, client.getSessionPoolStats().getAcquiredCount()); + Assert.assertEquals(1, client.getSessionPoolStats().getIdleCount()); + } +} diff --git a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java index 9a497d2a2..72239b43f 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/SessionPool.java @@ -120,8 +120,12 @@ private boolean pollNext(CompletableFuture> future) { return validateSession(nextSession.join(), future); } + future.whenComplete((result, error) -> nextSession.cancel(false)); nextSession.whenComplete((session, th) -> { if (th != null) { + if (future.isDone()) { + return; + } Throwable ex = FutureTools.unwrapCompletionException(th); Result fail = (ex instanceof UnexpectedResultException) ? Result.fail((UnexpectedResultException) ex) diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java new file mode 100644 index 000000000..7dffd44ed --- /dev/null +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingAcquires.java @@ -0,0 +1,87 @@ +package tech.ydb.table.impl.pool; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.BiConsumer; + +final class WaitingAcquires { + private final ConcurrentSkipListMap, Waiter> queue = new ConcurrentSkipListMap<>(); + private final AtomicLong sequence = new AtomicLong(); + private final AtomicInteger count = new AtomicInteger(); + + int count() { + return count.get(); + } + + boolean compareAndReserve(int expectedCount) { + return count.compareAndSet(expectedCount, expectedCount + 1); + } + + void releaseReservation(Waiter waiter) { + if (waiter.release()) { + count.decrementAndGet(); + } + } + + Waiter newWaiter(CompletableFuture acquire) { + return new Waiter<>(this, acquire, sequence.getAndIncrement()); + } + + void offer(Waiter waiter) { + // The waiter is also the key, so enqueue does not need to box the sequence number. + queue.put(waiter, waiter); + } + + Waiter pollFirst() { + Map.Entry, Waiter> entry = queue.pollFirstEntry(); + return entry == null ? null : entry.getValue(); + } + + boolean remove(Waiter waiter) { + if (!queue.remove(waiter, waiter)) { + return false; + } + releaseReservation(waiter); + return true; + } + + static final class Waiter implements Comparable>, BiConsumer { + @SuppressWarnings("rawtypes") + private static final AtomicIntegerFieldUpdater RELEASED = + AtomicIntegerFieldUpdater.newUpdater(Waiter.class, "released"); + + private final WaitingAcquires owner; + final CompletableFuture acquire; + private final long order; + private volatile int released; + + private Waiter(WaitingAcquires owner, CompletableFuture acquire, long order) { + this.owner = owner; + this.acquire = acquire; + this.order = order; + } + + private boolean release() { + return released == 0 && RELEASED.compareAndSet(this, 0, 1); + } + + @Override + public int compareTo(Waiter other) { + return Long.compareUnsigned(order, other.order); + } + + @Override + public void accept(T object, Throwable error) { + if (released == 0) { + // A resize can temporarily detach this waiter. Completion still frees its slot. + if (!owner.remove(this)) { + owner.releaseReservation(this); + } + } + } + } +} diff --git a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java index a82572118..76700b056 100644 --- a/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java +++ b/table/src/main/java/tech/ydb/table/impl/pool/WaitingQueue.java @@ -55,10 +55,7 @@ default void destroy(T object, PoolMetrics.Reason reason) { /** Summary size of queue = idle.size() + used.size() + pendingRequests.size() */ private final AtomicInteger queueSize = new AtomicInteger(); - /** Queue of waiting acquire requests */ - private final ConcurrentLinkedDeque> waitingAcquires = new ConcurrentLinkedDeque<>(); - /** Size of waiting acquires queue */ - private final AtomicInteger waitingAcqueireCount = new AtomicInteger(); + private final WaitingAcquires waitingAcquires = new WaitingAcquires<>(); private final ThreadLocal localGuard = new ThreadLocal<>(); @@ -178,7 +175,7 @@ public int getPendingCount() { } public int getWaitingCount() { - return waitingAcqueireCount.get(); + return waitingAcquires.count(); } public int getTotalLimit() { @@ -240,14 +237,21 @@ private boolean tryToCreateNewPending(CompletableFuture acquire) { } private boolean tryToCreateNewWaiting(CompletableFuture acquire) { - int waitingsCount = waitingAcqueireCount.get(); + int waitingsCount = waitingAcquires.count(); while (waitingsCount < limits.waitingsLimit) { - if (!waitingAcqueireCount.compareAndSet(waitingsCount, waitingsCount + 1)) { - waitingsCount = waitingAcqueireCount.get(); + if (!waitingAcquires.compareAndReserve(waitingsCount)) { + waitingsCount = waitingAcquires.count(); continue; } - waitingAcquires.offer(acquire); // ConcurrentLinkedQueue always return true + WaitingAcquires.Waiter waiter = waitingAcquires.newWaiter(acquire); + waitingAcquires.offer(waiter); + acquire.whenComplete(waiter); + // close() can run after the count is reserved but before this offer. + // In that case clear() cannot see the new entry, so clean it here. + if (stopped && waitingAcquires.remove(waiter)) { + acquire.completeExceptionally(new CancellationException("Queue is already closed")); + } return true; } @@ -260,15 +264,15 @@ private boolean tryToCompleteWaiting(T object) { } try (WaitingGuard guard = new WaitingGuard(object)) { - CompletableFuture next = waitingAcquires.poll(); - while (next != null) { + WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); + while (waiter != null) { guard.init(); - waitingAcqueireCount.decrementAndGet(); - if (safeAcquireObject(next, object) && !guard.isBroken()) { + waitingAcquires.releaseReservation(waiter); + if (safeAcquireObject(waiter.acquire, object) && !guard.isBroken()) { return true; } - next = waitingAcquires.poll(); + waiter = waitingAcquires.pollFirst(); } return false; @@ -280,17 +284,28 @@ private void checkNextWaitingAcquire() { return; } - CompletableFuture next = waitingAcquires.poll(); - while (next != null && next.isDone()) { - waitingAcqueireCount.decrementAndGet(); - next = waitingAcquires.poll(); + WaitingAcquires.Waiter waiter = waitingAcquires.pollFirst(); + while (waiter != null && waiter.acquire.isDone()) { + waitingAcquires.releaseReservation(waiter); + waiter = waitingAcquires.pollFirst(); } - if (next != null) { - if (tryToCreateNewPending(next)) { - waitingAcqueireCount.decrementAndGet(); + if (waiter != null) { + if (tryToCreateNewPending(waiter.acquire)) { + waitingAcquires.releaseReservation(waiter); + } else if (waiter.acquire.isDone()) { + waitingAcquires.releaseReservation(waiter); } else { - waitingAcquires.offerFirst(next); + // Keep the original order when returning an older waiter after a resize. + waitingAcquires.offer(waiter); + // The future might have completed while it was temporarily removed. + // Its completion handler cannot remove it in that interval. + if (waiter.acquire.isDone()) { + waitingAcquires.remove(waiter); + } + if (stopped && waitingAcquires.remove(waiter)) { + waiter.acquire.completeExceptionally(new CancellationException("Queue is already closed")); + } } } } @@ -302,10 +317,11 @@ private void clear() { } } - CompletableFuture waiting = waitingAcquires.poll(); + WaitingAcquires.Waiter waiting = waitingAcquires.pollFirst(); while (waiting != null) { - waiting.completeExceptionally(new CancellationException("Queue is already closed")); - waiting = waitingAcquires.poll(); + waitingAcquires.releaseReservation(waiting); + waiting.acquire.completeExceptionally(new CancellationException("Queue is already closed")); + waiting = waitingAcquires.pollFirst(); } T nextIdle = idle.poll(); diff --git a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java index b47f14cda..d8730e621 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/SessionPoolTest.java @@ -445,6 +445,56 @@ public void canceledSessionsTest() { tableRpc.completeSessionDeleteRequests(); } + @Test + public void timedOutWaitingAcquireReleasesQueueSlot() { + SessionPool pool = new SessionPool(clock, tableRpc, true, + SessionPoolOptions.DEFAULT.withSize(0, 1)); + + CompletableFuture> first = pendingFuture(pool.acquire(TIMEOUT)); + tableRpc.nextCreateSession().completeSuccess(); + Session held = futureIsReady(first).getValue(); + + CompletableFuture> timedOut = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + scheduler.runTasksTo(clock.instant().plus(TIMEOUT)); + resultIsWrong(timedOut, StatusCode.CLIENT_DEADLINE_EXPIRED); + check(pool).pending(0); + + CompletableFuture> next = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + held.close(); + Session acquired = futureIsReady(next).getValue(); + check(pool).pending(0).acquired(1); + + acquired.close(); + pool.close(); + tableRpc.completeSessionDeleteRequests(); + } + + @Test + public void cancelledWaitingAcquireReleasesQueueSlot() { + SessionPool pool = new SessionPool(clock, tableRpc, true, + SessionPoolOptions.DEFAULT.withSize(0, 1)); + + CompletableFuture> first = pendingFuture(pool.acquire(TIMEOUT)); + tableRpc.nextCreateSession().completeSuccess(); + Session held = futureIsReady(first).getValue(); + + CompletableFuture> cancelled = pendingFuture(pool.acquire(TIMEOUT)); + check(pool).pending(1); + Assert.assertTrue(cancelled.cancel(true)); + check(pool).pending(0); + + CompletableFuture> next = pendingFuture(pool.acquire(TIMEOUT)); + held.close(); + Session acquired = futureIsReady(next).getValue(); + check(pool).pending(0).acquired(1); + + acquired.close(); + pool.close(); + tableRpc.completeSessionDeleteRequests(); + } + @Test public void sessionDataQueryErrorsTest() { SessionPool pool = new SessionPool(clock, tableRpc, true, diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java new file mode 100644 index 000000000..7f30412dc --- /dev/null +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueParallelChurnTest.java @@ -0,0 +1,204 @@ +package tech.ydb.table.impl.pool; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReferenceArray; + +import org.junit.Assert; +import org.junit.Test; + +public class WaitingQueueParallelChurnTest { + private static final int TIMEOUT_SECONDS = 10; + private static final int PREFIX_WAITERS = 3; + private static final int WORKER_COUNT = 8; + private static final int CHURN_ITERATIONS = 128; + private static final int WAITING_LIMIT = PREFIX_WAITERS + WORKER_COUNT; + + @Test + public void admitsParallelCancelAndReplaceChurnAndPreservesFifo() throws Exception { + CompletableFuture resourceCreation = new CompletableFuture<>(); + WaitingQueue.Handler handler = new WaitingQueue.Handler() { + @Override + public CompletableFuture create() { + return resourceCreation; + } + + @Override + public void destroy(Object object) { + // The queue owns one resource for this test. + } + }; + + WaitingQueue queue = new WaitingQueue<>(handler, 1, WAITING_LIMIT); + ExecutorService workers = Executors.newFixedThreadPool(WORKER_COUNT); + CountDownLatch workersReady = new CountDownLatch(WORKER_COUNT); + CountDownLatch startWorkers = new CountDownLatch(1); + AtomicReferenceArray> workerWaiters = + new AtomicReferenceArray<>(WORKER_COUNT); + AtomicInteger maximumObservedWaitingCount = new AtomicInteger(); + Future[] workerTasks = new Future[WORKER_COUNT]; + Object resource = new Object(); + + try { + CompletableFuture heldAcquire = new CompletableFuture<>(); + queue.acquire(heldAcquire); + Assert.assertTrue("Resource creation should complete", resourceCreation.complete(resource)); + Assert.assertSame("The only resource remains checked out", resource, + heldAcquire.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + List> prefix = new ArrayList<>(); + for (int i = 0; i < PREFIX_WAITERS; i++) { + CompletableFuture waiter = enqueue(queue); + assertWaiting(waiter, "Prefix waiter should be admitted"); + prefix.add(waiter); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + } + + for (int workerId = 0; workerId < WORKER_COUNT; workerId++) { + CompletableFuture initialWaiter = enqueue(queue); + assertWaiting(initialWaiter, "Worker's initial waiter should be admitted"); + workerWaiters.set(workerId, initialWaiter); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + + final int id = workerId; + workerTasks[workerId] = workers.submit(() -> { + workersReady.countDown(); + if (!startWorkers.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("Timed out waiting for the churn start latch"); + } + + CompletableFuture current = workerWaiters.get(id); + for (int i = 0; i < CHURN_ITERATIONS; i++) { + Assert.assertTrue("Canceling the worker's active waiter should succeed", + current.cancel(false)); + + CompletableFuture replacement = new CompletableFuture<>(); + queue.acquire(replacement); + assertWaiting(replacement, "Replacement waiter should be admitted"); + recordBoundedWaitingCount(queue, maximumObservedWaitingCount); + + current = replacement; + workerWaiters.set(id, current); + } + return null; + }); + } + + Assert.assertEquals("The prefix and workers should fill all waiting slots", + WAITING_LIMIT, queue.getWaitingCount()); + Assert.assertTrue("Workers did not reach the start latch", + workersReady.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + startWorkers.countDown(); + awaitAll(workerTasks); + + Assert.assertEquals("Every worker should retain one final active waiter", + WAITING_LIMIT, queue.getWaitingCount()); + Assert.assertEquals("The observed waiting count should reach but not exceed the limit", + WAITING_LIMIT, maximumObservedWaitingCount.get()); + + List> replacements = new ArrayList<>(); + for (int i = 0; i < WORKER_COUNT; i++) { + CompletableFuture replacement = workerWaiters.get(i); + assertWaiting(replacement, "Final replacement should remain queued"); + replacements.add(replacement); + } + + Object currentResource = resource; + for (int i = 0; i < prefix.size(); i++) { + queue.release(currentResource); + currentResource = prefix.get(i).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertSame("Untouched prefix waiters should receive the resource FIFO", + resource, currentResource); + + for (int later = i + 1; later < prefix.size(); later++) { + Assert.assertFalse("Later prefix waiter must not overtake the current waiter", + prefix.get(later).isDone()); + } + for (CompletableFuture replacement : replacements) { + Assert.assertFalse("Worker replacements must remain behind the untouched prefix", + replacement.isDone()); + } + } + + boolean[] served = new boolean[replacements.size()]; + for (int count = 0; count < replacements.size(); count++) { + queue.release(currentResource); + + int newlyServed = -1; + for (int i = 0; i < replacements.size(); i++) { + if (!served[i] && replacements.get(i).isDone()) { + Assert.assertEquals("One release should serve one replacement", -1, newlyServed); + newlyServed = i; + } + } + + Assert.assertNotEquals("Each release should serve a worker replacement", -1, newlyServed); + currentResource = replacements.get(newlyServed).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + Assert.assertSame("Each replacement should receive the released resource", + resource, currentResource); + served[newlyServed] = true; + } + Assert.assertEquals("All worker replacements should have received the resource", + WORKER_COUNT, countServed(served)); + } finally { + startWorkers.countDown(); + for (Future workerTask : workerTasks) { + if (workerTask != null && !workerTask.isDone()) { + workerTask.cancel(true); + } + } + workers.shutdownNow(); + boolean workersTerminated = workers.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + queue.close(); + if (queue.getUsedCount() > 0) { + queue.release(resource); + } + Assert.assertTrue("Churn workers did not terminate", workersTerminated); + } + } + + private static CompletableFuture enqueue(WaitingQueue queue) { + CompletableFuture acquire = new CompletableFuture<>(); + queue.acquire(acquire); + return acquire; + } + + private static void assertWaiting(CompletableFuture future, String message) { + Assert.assertFalse(message + ": result completed exceptionally", future.isCompletedExceptionally()); + Assert.assertFalse(message + ": result completed before a resource was released", future.isDone()); + } + + private static void recordBoundedWaitingCount(WaitingQueue queue, AtomicInteger maximumObserved) { + int waitingCount = queue.getWaitingCount(); + Assert.assertTrue("Waiting count should stay between zero and the configured limit", + waitingCount >= 0 && waitingCount <= WAITING_LIMIT); + maximumObserved.accumulateAndGet(waitingCount, Math::max); + } + + private static void awaitAll(Future[] tasks) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); + for (Future task : tasks) { + long remaining = deadline - System.nanoTime(); + Assert.assertTrue("Timed out while joining churn workers", remaining > 0); + task.get(remaining, TimeUnit.NANOSECONDS); + } + } + + private static int countServed(boolean[] served) { + int count = 0; + for (boolean value : served) { + if (value) { + count++; + } + } + return count; + } +} diff --git a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java index 9616ebf2e..d0ecfd985 100644 --- a/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java +++ b/table/src/test/java/tech/ydb/table/impl/pool/WaitingQueueTest.java @@ -1,14 +1,22 @@ package tech.ydb.table.impl.pool; import java.util.ArrayDeque; +import java.util.ArrayList; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.junit.Assert; @@ -527,6 +535,7 @@ public void simpleWaitingRequests() { // After release resource must be moved to next waiting future queue.release(next); CompletableFuture waiting = waitings.poll(); + Assert.assertNotNull(waiting); next = pendingIsReady(waiting); Assert.assertEquals("All waitings got single resource ", r1, next); @@ -562,11 +571,11 @@ public void canceledWaitingTest() { Resource r2 = pendingIsReady(w1); Assert.assertEquals("Next waiting got same resource ", r1, r2); - // Cancellation of waiting doesn't affect to queue - w2.cancel(true); - check(queue).queueSize(1).idleSize(0).waitingsCount(2); + // Cancellation immediately removes the waiter and frees a waiting slot. + Assert.assertTrue(w2.cancel(true)); + check(queue).queueSize(1).idleSize(0).waitingsCount(1); - // Canceled waiting must be deleted when queue process next released resource + // The next released resource goes directly to the remaining waiter. queue.release(r2); check(queue).queueSize(1).idleSize(0).waitingsCount(0); @@ -580,6 +589,353 @@ public void canceledWaitingTest() { check(rs).requestsCount(0).activeCount(0); } + @Test + public void cancelledWaitingFreesFullQueueSlotTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + CompletableFuture cancelled = pendingFuture(acquire(queue)); + CompletableFuture remaining = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + + Assert.assertTrue(cancelled.cancel(true)); + check(queue).waitingsCount(1); + CompletableFuture replacement = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + + queue.release(resource); + Resource next = pendingIsReady(remaining); + Assert.assertSame(resource, next); + queue.release(next); + Resource last = pendingIsReady(replacement); + Assert.assertSame(resource, last); + + queue.delete(last); + queue.close(); + check(queue).queueSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + + @Test + public void cancelDuplicatedWaitingAcquireRemovesBothReservationsTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + CompletableFuture duplicated = new CompletableFuture<>(); + queue.acquire(duplicated); + queue.acquire(duplicated); + check(queue).waitingsCount(2); + + Assert.assertTrue(duplicated.cancel(true)); + check(queue).queueSize(1).idleSize(0).waitingsCount(0); + + queue.release(resource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + + @Test + public void completedWaitingIsRemovedImmediatelyTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + waiting.completeExceptionally(new RuntimeException("caller stopped waiting")); + check(queue).waitingsCount(0); + + rs.completeNext(); + Resource resource = pendingIsReady(first); + queue.release(resource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + } + + @Test + public void canceledWaitingAfterRequeueDoesNotConsumeReleasedResourceTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 2, 1); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture second = pendingFuture(acquire(queue)); + rs.completeNext().completeNext(); + Resource firstResource = pendingIsReady(first); + Resource secondResource = pendingIsReady(second); + + CompletableFuture waiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(1); + + // Reducing the limit polls and requeues the waiter because both resources are in use. + queue.updateLimits(1, 1); + check(queue).waitingsCount(1); + + waiting.cancel(true); + check(queue).waitingsCount(0); + + queue.release(firstResource); + queue.release(secondResource); + check(queue).queueSize(1).idleSize(1).waitingsCount(0); + + queue.close(); + } + + @Test + public void cancellationWhileResizeHasDequeuedWaiterFreesSlot() throws Exception { + ResourceHandler rs = new ResourceHandler(); + ExecutorService worker = Executors.newSingleThreadExecutor(); + try (WaitingQueue queue = new WaitingQueue<>(rs, 1, 1)) { + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource held = pendingIsReady(first); + + AtomicReference resizeThread = new AtomicReference<>(); + CompletableFuture detached = new CompletableFuture<>(); + CountDownLatch resumeResize = new CountDownLatch(1); + CompletableFuture waiting = new CompletableFuture() { + @Override + public boolean isDone() { + // This is the first check after updateLimits has detached the oldest waiter. + if (Thread.currentThread() == resizeThread.get() && detached.complete(null)) { + try { + Assert.assertTrue("Resize did not resume", resumeResize.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new AssertionError(ex); + } + } + return super.isDone(); + } + }; + queue.acquire(waiting); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + + Future resize = worker.submit(() -> { + resizeThread.set(Thread.currentThread()); + queue.updateLimits(1, 1); + }); + CompletableFuture replacement; + try { + detached.get(5, TimeUnit.SECONDS); + Assert.assertTrue(waiting.cancel(false)); + replacement = new CompletableFuture<>(); + queue.acquire(replacement); + Assert.assertFalse("The replacement should wait for the checked-out resource: " + replacement, + replacement.isDone()); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + } finally { + resumeResize.countDown(); + } + resize.get(5, TimeUnit.SECONDS); + + queue.release(held); + Assert.assertSame(held, pendingIsReady(replacement)); + check(queue).waitingsCount(0); + queue.delete(held); + } finally { + worker.shutdownNow(); + } + } + + @Test + public void updateLimitsDequeuesOldestWaiterAtFrontTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 2, 2); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture second = pendingFuture(acquire(queue)); + rs.completeNext().completeNext(); + Resource firstResource = pendingIsReady(first); + Resource secondResource = pendingIsReady(second); + + CompletableFuture oldestWaiting = pendingFuture(acquire(queue)); + CompletableFuture laterWaiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(2); + + // With both resources in use, the oldest waiter cannot reserve a new resource. + // It must remain ahead of the later waiter when it is returned to the queue. + queue.updateLimits(1, 2); + check(queue).waitingsCount(2); + + queue.release(firstResource); + Assert.assertSame(firstResource, pendingIsReady(oldestWaiting)); + futureIsPending(laterWaiting); + + queue.release(secondResource); + Assert.assertSame(secondResource, pendingIsReady(laterWaiting)); + + queue.delete(firstResource); + queue.delete(secondResource); + queue.close(); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + + @Test + public void closeRemovesWaitingCountImmediatelyTest() { + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, 3); + + CompletableFuture first = pendingFuture(acquire(queue)); + CompletableFuture firstWaiting = pendingFuture(acquire(queue)); + CompletableFuture middleWaiting = pendingFuture(acquire(queue)); + CompletableFuture lastWaiting = pendingFuture(acquire(queue)); + check(queue).waitingsCount(3); + + queue.close(); + futureIsCanceled(firstWaiting, QUEUE_IS_CLOSED); + futureIsCanceled(middleWaiting, QUEUE_IS_CLOSED); + futureIsCanceled(lastWaiting, QUEUE_IS_CLOSED); + check(queue).queueSize(0).waitingsCount(0); + + rs.completeNext(); + futureIsCanceled(first, QUEUE_IS_CLOSED); + check(rs).requestsCount(0).activeCount(0); + } + + @Test + public void concurrentCancelAndCloseRemovesAllWaitingAcquiresTest() throws InterruptedException { + final int waitingCount = 64; + ResourceHandler rs = new ResourceHandler(); + WaitingQueue queue = new WaitingQueue<>(rs, 1, waitingCount); + + CompletableFuture first = pendingFuture(acquire(queue)); + rs.completeNext(); + Resource resource = pendingIsReady(first); + + List> waitings = new ArrayList<>(); + for (int idx = 0; idx < waitingCount; idx++) { + CompletableFuture waiting = new CompletableFuture<>(); + queue.acquire(waiting); + waitings.add(waiting); + } + check(queue).waitingsCount(waitingCount); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + AtomicReference workerFailure = new AtomicReference<>(); + + Thread cancellation = new Thread(() -> { + ready.countDown(); + try { + Assert.assertTrue("Cancellation worker did not start", start.await(5, TimeUnit.SECONDS)); + for (CompletableFuture waiting : waitings) { + waiting.cancel(true); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + workerFailure.compareAndSet(null, ex); + } catch (Throwable th) { + workerFailure.compareAndSet(null, th); + } + }, "waiting-queue-cancellation-test"); + Thread closing = new Thread(() -> { + ready.countDown(); + try { + Assert.assertTrue("Close worker did not start", start.await(5, TimeUnit.SECONDS)); + queue.close(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + workerFailure.compareAndSet(null, ex); + } catch (Throwable th) { + workerFailure.compareAndSet(null, th); + } + }, "waiting-queue-close-test"); + cancellation.setDaemon(true); + closing.setDaemon(true); + cancellation.start(); + closing.start(); + + boolean workersReady = ready.await(5, TimeUnit.SECONDS); + start.countDown(); + cancellation.join(5000); + closing.join(5000); + + Assert.assertTrue("Workers did not become ready", workersReady); + Assert.assertFalse("Cancellation worker did not finish", cancellation.isAlive()); + Assert.assertFalse("Close worker did not finish", closing.isAlive()); + Assert.assertNull("Concurrent worker failed", workerFailure.get()); + check(queue).queueSize(1).idleSize(0).waitingsCount(0); + for (CompletableFuture waiting : waitings) { + Assert.assertTrue("Waiting future is terminal", waiting.isDone()); + } + + queue.release(resource); + check(queue).queueSize(0).idleSize(0).waitingsCount(0); + check(rs).requestsCount(0).activeCount(0); + } + + @Test + public void cancellationRacingWithReleasePreservesWaitingCapacity() throws Exception { + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + for (int attempt = 0; attempt < 32; attempt++) { + checkCancellationRacingWithRelease(workers); + } + } finally { + workers.shutdownNow(); + } + } + + private void checkCancellationRacingWithRelease(ExecutorService workers) throws Exception { + ResourceHandler handler = new ResourceHandler(); + try (WaitingQueue queue = new WaitingQueue<>(handler, 1, 2)) { + CompletableFuture first = pendingFuture(acquire(queue)); + handler.completeNext(); + Resource held = pendingIsReady(first); + CompletableFuture contested = pendingFuture(acquire(queue)); + CompletableFuture surviving = pendingFuture(acquire(queue)); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + Future cancelled = workers.submit(() -> { + ready.countDown(); + Assert.assertTrue(start.await(5, TimeUnit.SECONDS)); + return contested.cancel(false); + }); + Future released = workers.submit(() -> { + ready.countDown(); + Assert.assertTrue(start.await(5, TimeUnit.SECONDS)); + queue.release(held); + return null; + }); + boolean bothReady = ready.await(5, TimeUnit.SECONDS); + start.countDown(); + Assert.assertTrue("Both workers should be ready", bothReady); + released.get(5, TimeUnit.SECONDS); + if (cancelled.get(5, TimeUnit.SECONDS)) { + Assert.assertTrue(contested.isCancelled()); + } else { + Assert.assertSame(held, pendingIsReady(contested)); + queue.release(held); + } + Assert.assertSame(held, pendingIsReady(surviving)); + + CompletableFuture next = pendingFuture(acquire(queue)); + CompletableFuture last = pendingFuture(acquire(queue)); + exceptionallyFuture(acquire(queue), LIMIT_EXCEEDED); + queue.release(held); + Assert.assertSame(held, pendingIsReady(next)); + queue.release(held); + Assert.assertSame(held, pendingIsReady(last)); + queue.release(held); + } + } + @Test public void immediatellyCompletedWaitingsTest() { ResourceHandler rs = new ResourceHandler();