From 37205f975eabe91ccb1c765d1badbb762c07b8a6 Mon Sep 17 00:00:00 2001 From: emreekiziltoprak Date: Sat, 31 Oct 2026 18:45:03 +0300 Subject: [PATCH 1/5] Fix BulkIngester hanging when retries fill the buffer Retried operations go back into the buffer before their backoff delay has passed, and they are re-added on retryScheduler, which blocks in innerAdd() while the buffer is full. The flushes that drain the buffer were scheduled on the same executor, so once all its threads were blocked those flushes never ran and add() and close() hung. Schedule the retry flushes on their own executor. Also flush after a retry is re-added if it is already sendable, since its scheduled flushes may have run while it was waiting for space in the buffer. Signed-off-by: emreekiziltoprak --- CHANGELOG.md | 1 + .../_helpers/bulk/BulkIngester.java | 23 ++++++-- .../_helpers/bulk/BulkIngesterTest.java | 54 ++++++++++++++++++- 3 files changed, 74 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f5fe62cab..9177c77442 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Add missing `analyzer`, `search_analyzer` and other supported parameters to `MatchOnlyTextProperty` ([#2217](https://github.com/opensearch-project/opensearch-java/pull/2217)) - Fix `NullPointerException` in `_listAddAll` when server returns JSON `null` for a list field ([#2041](https://github.com/opensearch-project/opensearch-java/pull/2041)) - Fix code generation failing with a `NullPointerException` on an `allOf` with no `$ref` or composition member, such as `allOf: [{ properties }, { anyOf }]` (`SemanticProperty` in the normalized spec). `allOf` now always maps to its last, most specific member, which is what it already did whenever it did not fail ([#2238](https://github.com/opensearch-project/opensearch-java/pull/2238)) +- Fix `BulkIngester` hanging when retried operations fill the buffer before their backoff delay has passed ([#2248](https://github.com/opensearch-project/opensearch-java/issues/2248)) ### Security diff --git a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java index 7590585415..d16de65414 100644 --- a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java +++ b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java @@ -121,6 +121,7 @@ public class BulkIngester implements AutoCloseable { private @Nullable ScheduledFuture flushTask; private @Nullable ScheduledExecutorService scheduler; private @Nullable ScheduledExecutorService retryScheduler; + private @Nullable ScheduledExecutorService retryFlushScheduler; private boolean isExternalScheduler = false; private BackoffPolicy backoffPolicy; @@ -187,7 +188,7 @@ private BulkIngester(Builder builder) { if (backoffPolicy == null) { backoffPolicy = BackoffPolicy.noBackoff(); } - // preparing a scheduler that will trigger flushes to retry failed requests + // preparing the schedulers that will add failed requests back to the buffer and trigger flushes to retry them else { retryScheduler = Executors.newScheduledThreadPool(maxRequests + 1, (r) -> { Thread t = Executors.defaultThreadFactory().newThread(r); @@ -195,6 +196,14 @@ private BulkIngester(Builder builder) { t.setDaemon(true); return t; }); + // Separate from retryScheduler, whose threads can all be blocked waiting for space in the buffer + // that only these flushes can free + retryFlushScheduler = Executors.newSingleThreadScheduledExecutor((r) -> { + Thread t = Executors.defaultThreadFactory().newThread(r); + t.setName("bulk-ingester-retry-flush#" + ingesterId + "#" + t.getId()); + t.setDaemon(true); + return t; + }); } } @@ -545,8 +554,8 @@ private void scheduleRetries(List> retryableReq) .summaryStatistics(); // scheduling earlier and latest delay - retryScheduler.schedule(this::flush, statsDelays.getMin(), TimeUnit.MILLISECONDS); - retryScheduler.schedule(this::flush, statsDelays.getMax(), TimeUnit.MILLISECONDS); + retryFlushScheduler.schedule(this::flush, statsDelays.getMin(), TimeUnit.MILLISECONDS); + retryFlushScheduler.schedule(this::flush, statsDelays.getMax(), TimeUnit.MILLISECONDS); } @@ -581,6 +590,10 @@ private void addRetry(RetryableBulkOperation repeatableOp) { retryScheduler.submit(() -> { try { innerAdd(repeatableOp); + // The scheduled flushes may have run while this operation was waiting for space in the buffer + if (repeatableOp.isSendable()) { + flush(); + } } finally { if (retriesInProgressCount.decrementAndGet() == 0) { closeCondition.signalIfReady(); @@ -671,6 +684,10 @@ public void close() { if (retryScheduler != null) { retryScheduler.shutdownNow(); } + + if (retryFlushScheduler != null) { + retryFlushScheduler.shutdownNow(); + } } // ---------------------------------------------------------------------------------------------------- diff --git a/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java b/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java index c0c12d5414..09c95db3e1 100644 --- a/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java +++ b/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java @@ -57,6 +57,7 @@ import org.opensearch.client.opensearch.core.bulk.BulkOperation; import org.opensearch.client.opensearch.core.bulk.BulkResponseItem; import org.opensearch.client.opensearch.core.bulk.OperationType; +import org.opensearch.client.transport.BackoffPolicy; import org.opensearch.client.transport.Endpoint; import org.opensearch.client.transport.OpenSearchTransport; import org.opensearch.client.transport.TransportOptions; @@ -90,6 +91,16 @@ public void setMsg(String msg) { private static final BulkOperation operation = BulkOperation.of(op -> op.delete(d -> d.index("foo").id("bar"))); + private static BulkResponseItem rejectedItem(int position) { + return BulkResponseItem.of( + i -> i.index("foo") + .id(String.valueOf(position)) + .status(429) + .operationType(OperationType.Delete) + .error(e -> e.type("rejected_execution_exception").reason("rejected")) + ); + } + private void printStats(BulkIngester ingester) { System.out.printf( "Ingester - operations: %d (%d), requests: %d (%d)%n", @@ -223,6 +234,41 @@ public void sizeLimitTest() throws Exception { assertEquals(5, ingester.requestCount()); } + @Test(timeout = 30_000) + public void retriesFillingTheBufferDoNotBlockTheirFlush() throws Exception { + retriesFillingTheBufferTest(200L); + } + + @Test(timeout = 30_000) + public void retriesWithShortBackoffAreFlushedOnceAddedToTheBuffer() throws Exception { + // The scheduled flushes are likely to run while the retries are still waiting for space in the buffer + retriesFillingTheBufferTest(1L); + } + + private void retriesFillingTheBufferTest(long retryDelayMillis) throws Exception { + int numOperations = 10; + TestTransport transport = new TestTransport(); + transport.itemsToReject.set(6); + + // No flushInterval: nothing but the retry flushes can drain a buffer full of operations waiting for their backoff + BulkIngester ingester = BulkIngester.of( + b -> b.client(new OpenSearchAsyncClient(transport)) + .maxOperations(2) + .maxConcurrentRequests(1) + .backoffPolicy(BackoffPolicy.constantBackoff(retryDelayMillis, 5)) + ); + + for (int i = 0; i < numOperations; i++) { + ingester.add(operation); + } + + ingester.close(); + transport.close(); + + assertEquals(0, transport.itemsToReject.get()); + assertEquals(numOperations + 6, transport.operations.get()); + } + /** * Waits for the periodic flusher to have emitted {@code expected} requests. Tests that add operations * spaced apart in time cannot rely on sleeping longer than the flush interval: under load two operations @@ -513,6 +559,8 @@ private static class TestTransport implements OpenSearchTransport { public final AtomicInteger requestsStarted = new AtomicInteger(); public final AtomicInteger requestsCompleted = new AtomicInteger(); public final AtomicInteger operations = new AtomicInteger(); + // Number of operations that will still be answered with a 429 status + public final AtomicInteger itemsToReject = new AtomicInteger(); private final ExecutorService executor = Executors.newCachedThreadPool(); @@ -542,7 +590,11 @@ public CompletableFuture performRequest List items = new ArrayList<>(); for (int i = 0; i < bulk.operations().size(); i++) { - items.add(successItem); + if (itemsToReject.getAndUpdate(remaining -> Math.max(0, remaining - 1)) > 0) { + items.add(rejectedItem(i)); + } else { + items.add(successItem); + } } CompletableFuture response = new CompletableFuture<>(); From 6f3d6aebd32223d0e3bef4d9c7f0d297e1005e60 Mon Sep 17 00:00:00 2001 From: emreekiziltoprak Date: Sat, 31 Oct 2026 18:45:15 +0300 Subject: [PATCH 2/5] Reference the pull request in the changelog Signed-off-by: emreekiziltoprak --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9177c77442..801febb15d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Add missing `analyzer`, `search_analyzer` and other supported parameters to `MatchOnlyTextProperty` ([#2217](https://github.com/opensearch-project/opensearch-java/pull/2217)) - Fix `NullPointerException` in `_listAddAll` when server returns JSON `null` for a list field ([#2041](https://github.com/opensearch-project/opensearch-java/pull/2041)) - Fix code generation failing with a `NullPointerException` on an `allOf` with no `$ref` or composition member, such as `allOf: [{ properties }, { anyOf }]` (`SemanticProperty` in the normalized spec). `allOf` now always maps to its last, most specific member, which is what it already did whenever it did not fail ([#2238](https://github.com/opensearch-project/opensearch-java/pull/2238)) -- Fix `BulkIngester` hanging when retried operations fill the buffer before their backoff delay has passed ([#2248](https://github.com/opensearch-project/opensearch-java/issues/2248)) +- Fix `BulkIngester` hanging when retried operations fill the buffer before their backoff delay has passed ([#2256](https://github.com/opensearch-project/opensearch-java/pull/2256)) ### Security From 6dacc5ba5b6ba49ddc556f60fdbdfdb93e81538d Mon Sep 17 00:00:00 2001 From: emreekiziltoprak Date: Sat, 31 Oct 2026 20:36:41 +0300 Subject: [PATCH 3/5] Pass on the signal when a woken flush has nothing to send A completed request signals a single thread waiting to send one. If that thread found nothing to send it returned without passing the signal on, leaving other waiting threads parked with no request in flight to wake them, which hung add() and close(). Signed-off-by: emreekiziltoprak --- .../opensearch/client/opensearch/_helpers/bulk/FnCondition.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java index 5d6a35acaf..76743362f5 100644 --- a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java +++ b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java @@ -115,6 +115,8 @@ public T whenReadyIf(BooleanSupplier canRun, Supplier fn) { } if (canRun != null && !canRun.getAsBoolean()) { + // This thread may have used up a signal without doing anything with it: pass it on to the next one + condition.signal(); return null; } From 9f15c463db41b2fb2336aec87b36d81fe34af50e Mon Sep 17 00:00:00 2001 From: emreekiziltoprak Date: Fri, 13 Nov 2026 18:48:41 +0300 Subject: [PATCH 4/5] Address review feedback on the BulkIngester retry fix Wake up the next waiting flush from BulkIngester.flush() when a flush had nothing to send, instead of changing FnCondition, so the ingester keeps control over which threads are woken up. Run the retry flushes on the periodic flush scheduler when there is one, and only create a dedicated one otherwise. Replace the timing-based short backoff test with one that holds the retry back until its scheduled flushes have run, and cover the retry flushes running on the periodic flush scheduler. Signed-off-by: emreekiziltoprak --- .../_helpers/bulk/BulkIngester.java | 23 ++++-- .../opensearch/_helpers/bulk/FnCondition.java | 2 - .../_helpers/bulk/BulkIngesterTest.java | 81 ++++++++++++++++--- 3 files changed, 86 insertions(+), 20 deletions(-) diff --git a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java index d16de65414..15bcdf12ae 100644 --- a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java +++ b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java @@ -197,13 +197,17 @@ private BulkIngester(Builder builder) { return t; }); // Separate from retryScheduler, whose threads can all be blocked waiting for space in the buffer - // that only these flushes can free - retryFlushScheduler = Executors.newSingleThreadScheduledExecutor((r) -> { - Thread t = Executors.defaultThreadFactory().newThread(r); - t.setName("bulk-ingester-retry-flush#" + ingesterId + "#" + t.getId()); - t.setDaemon(true); - return t; - }); + // that only these flushes can free. The periodic flush scheduler already is. + if (flushIntervalMillis != null) { + retryFlushScheduler = scheduler; + } else { + retryFlushScheduler = Executors.newSingleThreadScheduledExecutor((r) -> { + Thread t = Executors.defaultThreadFactory().newThread(r); + t.setName("bulk-ingester-retry-flush#" + ingesterId + "#" + t.getId()); + t.setDaemon(true); + return t; + }); + } } } @@ -491,6 +495,9 @@ public void flush() { }); return null; }); + } else { + // A flush woken up by a completed request may have found nothing to send: wake up the next waiting one + sendRequestCondition.signalIfReady(); } } @@ -685,7 +692,7 @@ public void close() { retryScheduler.shutdownNow(); } - if (retryFlushScheduler != null) { + if (retryFlushScheduler != null && retryFlushScheduler != scheduler) { retryFlushScheduler.shutdownNow(); } } diff --git a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java index 76743362f5..5d6a35acaf 100644 --- a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java +++ b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/FnCondition.java @@ -115,8 +115,6 @@ public T whenReadyIf(BooleanSupplier canRun, Supplier fn) { } if (canRun != null && !canRun.getAsBoolean()) { - // This thread may have used up a signal without doing anything with it: pass it on to the next one - condition.signal(); return null; } diff --git a/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java b/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java index 09c95db3e1..1508bcbfb6 100644 --- a/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java +++ b/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java @@ -236,28 +236,82 @@ public void sizeLimitTest() throws Exception { @Test(timeout = 30_000) public void retriesFillingTheBufferDoNotBlockTheirFlush() throws Exception { - retriesFillingTheBufferTest(200L); + retriesFillingTheBufferTest(200L, null); } @Test(timeout = 30_000) - public void retriesWithShortBackoffAreFlushedOnceAddedToTheBuffer() throws Exception { - // The scheduled flushes are likely to run while the retries are still waiting for space in the buffer - retriesFillingTheBufferTest(1L); + public void retriesFillingTheBufferDoNotBlockTheirFlushOnTheFlushIntervalScheduler() throws Exception { + // The retry flushes then run on the periodic flush scheduler, and the period is too long to help them + retriesFillingTheBufferTest(200L, 1L); } - private void retriesFillingTheBufferTest(long retryDelayMillis) throws Exception { - int numOperations = 10; + @Test(timeout = 30_000) + public void retryAddedAfterItsScheduledFlushesIsSent() throws Exception { TestTransport transport = new TestTransport(); - transport.itemsToReject.set(6); + transport.itemsToReject.set(1); + CountDownLatch retryWaiting = new CountDownLatch(1); + CountDownLatch releaseRetry = new CountDownLatch(1); + transport.beforeRetryAdd = () -> { + retryWaiting.countDown(); + try { + releaseRetry.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }; - // No flushInterval: nothing but the retry flushes can drain a buffer full of operations waiting for their backoff + // No flushInterval and a buffer that never fills up: only a flush triggered by the retry itself can send it BulkIngester ingester = BulkIngester.of( b -> b.client(new OpenSearchAsyncClient(transport)) - .maxOperations(2) + .maxOperations(10) .maxConcurrentRequests(1) - .backoffPolicy(BackoffPolicy.constantBackoff(retryDelayMillis, 5)) + .backoffPolicy(BackoffPolicy.constantBackoff(1L, 5)) ); + ingester.add(operation); + ingester.flush(); + retryWaiting.await(); + + // The retry flushes are scheduled before the request is released, and run while the retry is held back + while (ingester.pendingRequests() > 0 || retryFlushThreadIsBusy()) { + Thread.sleep(5); + } + releaseRetry.countDown(); + + awaitRequestCount(ingester, 2); + + ingester.close(); + transport.close(); + + assertEquals(2, transport.operations.get()); + } + + private static boolean retryFlushThreadIsBusy() { + // Idle once both scheduled flushes have run: its queue is empty and it waits for a new task + return Thread.getAllStackTraces() + .keySet() + .stream() + .filter(t -> t.getName().startsWith("bulk-ingester-retry-flush#")) + .anyMatch(t -> t.getState() != Thread.State.WAITING); + } + + private void retriesFillingTheBufferTest(long retryDelayMillis, @Nullable Long flushIntervalHours) throws Exception { + int numOperations = 10; + TestTransport transport = new TestTransport(); + transport.itemsToReject.set(6); + + // Nothing but the retry flushes can drain a buffer full of operations waiting for their backoff + BulkIngester ingester = BulkIngester.of(b -> { + b.client(new OpenSearchAsyncClient(transport)) + .maxOperations(2) + .maxConcurrentRequests(1) + .backoffPolicy(BackoffPolicy.constantBackoff(retryDelayMillis, 5)); + if (flushIntervalHours != null) { + b.flushInterval(flushIntervalHours, TimeUnit.HOURS); + } + return b; + }); + for (int i = 0; i < numOperations; i++) { ingester.add(operation); } @@ -561,6 +615,8 @@ private static class TestTransport implements OpenSearchTransport { public final AtomicInteger operations = new AtomicInteger(); // Number of operations that will still be answered with a 429 status public final AtomicInteger itemsToReject = new AtomicInteger(); + // Runs on the retry thread before a retried operation is added back to the buffer + public volatile Runnable beforeRetryAdd; private final ExecutorService executor = Executors.newCachedThreadPool(); @@ -610,6 +666,11 @@ public CompletableFuture performRequest @Override public JsonpMapper jsonpMapper() { + Runnable beforeRetryAdd = this.beforeRetryAdd; + if (beforeRetryAdd != null && Thread.currentThread().getName().startsWith("bulk-ingester-retry#")) { + // The ingester gets the mapper to measure an operation just before adding it to the buffer + beforeRetryAdd.run(); + } return new JacksonJsonpMapper(); } From 521e4133b67639f1d4b8b93117edecb035dd12d5 Mon Sep 17 00:00:00 2001 From: emreekiziltoprak Date: Wed, 18 Nov 2026 17:08:44 +0300 Subject: [PATCH 5/5] Drop pending retries when closing the BulkIngester Instead of flushing a retry that is added back after its scheduled flushes have run, close() now drops the retries that are still pending: the ones waiting in the buffer, the ones waiting to be added back, and no new retries are scheduled for responses that come back after close(). Signed-off-by: emreekiziltoprak --- .../_helpers/bulk/BulkIngester.java | 36 +++++++++++++++---- .../_helpers/bulk/BulkIngesterTest.java | 30 ++++++---------- 2 files changed, 40 insertions(+), 26 deletions(-) diff --git a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java index 15bcdf12ae..e1e68f5ef3 100644 --- a/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java +++ b/java-client/src/main/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngester.java @@ -428,8 +428,8 @@ public void flush() { .filter(i -> i.error() != null && i.status() == 429) .collect(Collectors.toList()); - if (failedRequestsCanRetry.isEmpty() || backoffPolicy.equals(BackoffPolicy.noBackoff())) { - // Total success! ...or there's no retry policy implemented. Either way, can call + if (failedRequestsCanRetry.isEmpty() || backoffPolicy.equals(BackoffPolicy.noBackoff()) || isClosed) { + // Total success! ...or there's no retry policy implemented, or closing. Either way, can call listenerAfterBulkSuccess(resp, exec); } else { // Partial success, retrying failed requests if policy allows it @@ -590,17 +590,13 @@ public void add(BulkOperation operation, Context context) { innerAdd(repeatableOp); } - // Same as "add", but skips the closed check to allow retries to be added even after ingester closure + // Same as "add", but skips the closed check: innerAdd() drops the retry if the ingester was closed meanwhile private void addRetry(RetryableBulkOperation repeatableOp) { // Sending the operation back in the queue using the retry scheduler retriesInProgressCount.incrementAndGet(); retryScheduler.submit(() -> { try { innerAdd(repeatableOp); - // The scheduled flushes may have run while this operation was waiting for space in the buffer - if (repeatableOp.isSendable()) { - flush(); - } } finally { if (retriesInProgressCount.decrementAndGet() == 0) { closeCondition.signalIfReady(); @@ -613,6 +609,11 @@ private void innerAdd(RetryableBulkOperation repeatableOp) { IngesterOperation ingestOp = IngesterOperation.of(repeatableOp, client._transport().jsonpMapper()); addCondition.whenReady(() -> { + if (isClosed && repeatableOp.retries() != null) { + // The ingester was closed while this retry was waiting to be added back: drop it + addCondition.signalIfReady(); + return; + } operations.add(ingestOp); currentSize += ingestOp.size(); @@ -675,6 +676,8 @@ public void close() { } isClosed = true; + // Drop the retries that are still pending + dropPendingRetries(); // Flush buffered operations flush(); // and wait for all requests to be completed @@ -697,6 +700,25 @@ public void close() { } } + private void dropPendingRetries() { + lock.lock(); + try { + for (Iterator> it = operations.iterator(); it.hasNext();) { + IngesterOperation op = it.next(); + // Only retries have a retries iterator: operations added by the application are still sent by close() + if (op.retries() != null) { + currentSize -= op.size(); + it.remove(); + } + } + // Wake up the threads waiting for space: retries see the ingester is closed and are dropped, + // operations added before close() go into the buffer and are sent + addCondition.signalAllIfReady(); + } finally { + lock.unlock(); + } + } + // ---------------------------------------------------------------------------------------------------- public static BulkIngester of(Function, Builder> f) { diff --git a/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java b/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java index 1508bcbfb6..363fc462a9 100644 --- a/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java +++ b/java-client/src/test/java/org/opensearch/client/opensearch/_helpers/bulk/BulkIngesterTest.java @@ -246,7 +246,7 @@ public void retriesFillingTheBufferDoNotBlockTheirFlushOnTheFlushIntervalSchedul } @Test(timeout = 30_000) - public void retryAddedAfterItsScheduledFlushesIsSent() throws Exception { + public void closeDropsRetriesThatAreStillPending() throws Exception { TestTransport transport = new TestTransport(); transport.itemsToReject.set(1); CountDownLatch retryWaiting = new CountDownLatch(1); @@ -260,7 +260,6 @@ public void retryAddedAfterItsScheduledFlushesIsSent() throws Exception { } }; - // No flushInterval and a buffer that never fills up: only a flush triggered by the retry itself can send it BulkIngester ingester = BulkIngester.of( b -> b.client(new OpenSearchAsyncClient(transport)) .maxOperations(10) @@ -272,27 +271,20 @@ public void retryAddedAfterItsScheduledFlushesIsSent() throws Exception { ingester.flush(); retryWaiting.await(); - // The retry flushes are scheduled before the request is released, and run while the retry is held back - while (ingester.pendingRequests() > 0 || retryFlushThreadIsBusy()) { + // close() waits for the retry in progress, which is released once close() is waiting + Thread closer = new Thread(ingester::close); + closer.start(); + while (closer.getState() != Thread.State.WAITING) { Thread.sleep(5); } releaseRetry.countDown(); + closer.join(10_000); + assertFalse(closer.isAlive()); - awaitRequestCount(ingester, 2); - - ingester.close(); transport.close(); - assertEquals(2, transport.operations.get()); - } - - private static boolean retryFlushThreadIsBusy() { - // Idle once both scheduled flushes have run: its queue is empty and it waits for a new task - return Thread.getAllStackTraces() - .keySet() - .stream() - .filter(t -> t.getName().startsWith("bulk-ingester-retry-flush#")) - .anyMatch(t -> t.getState() != Thread.State.WAITING); + // The rejected operation was not sent again + assertEquals(1, transport.operations.get()); } private void retriesFillingTheBufferTest(long retryDelayMillis, @Nullable Long flushIntervalHours) throws Exception { @@ -319,8 +311,8 @@ private void retriesFillingTheBufferTest(long retryDelayMillis, @Nullable Long f ingester.close(); transport.close(); - assertEquals(0, transport.itemsToReject.get()); - assertEquals(numOperations + 6, transport.operations.get()); + // Retries still pending when closing are dropped, but every operation was sent at least once + assertTrue(transport.operations.get() >= numOperations); } /**