diff --git a/CHANGELOG.md b/CHANGELOG.md index 3093ec16fc..27cdfa46c2 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 ([#2256](https://github.com/opensearch-project/opensearch-java/pull/2256)) - Fix a race in `JsonpDeserializer.arrayDeserializer` and `arrayOrNullDeserializer` where a thread could see its accepted events before the item events were added, and reject a single value in place of a list ([#2254](https://github.com/opensearch-project/opensearch-java/pull/2254)) - Fix Jackson 3 `JacksonJsonpParserTest` importing Jackson 2 classes and document that a user-supplied Jackson 3 `ObjectMapper` needs `FAIL_ON_TRAILING_TOKENS` disabled ([#2237](https://github.com/opensearch-project/opensearch-java/pull/2237)) 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..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 @@ -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,18 @@ 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. 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; + }); + } } } @@ -415,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 @@ -482,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(); } } @@ -545,8 +561,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); } @@ -574,7 +590,7 @@ 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(); @@ -593,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(); @@ -655,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 @@ -671,6 +694,29 @@ public void close() { if (retryScheduler != null) { retryScheduler.shutdownNow(); } + + if (retryFlushScheduler != null && retryFlushScheduler != scheduler) { + retryFlushScheduler.shutdownNow(); + } + } + + 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(); + } } // ---------------------------------------------------------------------------------------------------- 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..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 @@ -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,87 @@ public void sizeLimitTest() throws Exception { assertEquals(5, ingester.requestCount()); } + @Test(timeout = 30_000) + public void retriesFillingTheBufferDoNotBlockTheirFlush() throws Exception { + retriesFillingTheBufferTest(200L, null); + } + + @Test(timeout = 30_000) + 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); + } + + @Test(timeout = 30_000) + public void closeDropsRetriesThatAreStillPending() throws Exception { + TestTransport transport = new TestTransport(); + 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(); + } + }; + + BulkIngester ingester = BulkIngester.of( + b -> b.client(new OpenSearchAsyncClient(transport)) + .maxOperations(10) + .maxConcurrentRequests(1) + .backoffPolicy(BackoffPolicy.constantBackoff(1L, 5)) + ); + + ingester.add(operation); + ingester.flush(); + retryWaiting.await(); + + // 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()); + + transport.close(); + + // The rejected operation was not sent again + assertEquals(1, transport.operations.get()); + } + + 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); + } + + ingester.close(); + transport.close(); + + // Retries still pending when closing are dropped, but every operation was sent at least once + assertTrue(transport.operations.get() >= numOperations); + } + /** * 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 +605,10 @@ 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(); + // 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(); @@ -542,7 +638,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<>(); @@ -558,6 +658,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(); }