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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ public class BulkIngester<Context> 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;

Expand Down Expand Up @@ -187,14 +188,26 @@ private BulkIngester(Builder<Context> 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);
t.setName("bulk-ingester-retry#" + ingesterId + "#" + t.getId());
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;
});
}
}
}

Expand Down Expand Up @@ -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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the failedRequestsCanRetry has to be empty when isClosed is set (not need to make do isClosed check here), that somewhat reflected by https://github.com/opensearch-project/opensearch-java/pull/2256/changes#r4659188876

// 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
Expand Down Expand Up @@ -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();
}
}

Expand Down Expand Up @@ -545,8 +561,8 @@ private void scheduleRetries(List<RetryableBulkOperation<Context>> 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);

}

Expand Down Expand Up @@ -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<Context> repeatableOp) {
// Sending the operation back in the queue using the retry scheduler
retriesInProgressCount.incrementAndGet();
Expand All @@ -593,6 +609,11 @@ private void innerAdd(RetryableBulkOperation<Context> repeatableOp) {
IngesterOperation<Context> ingestOp = IngesterOperation.of(repeatableOp, client._transport().jsonpMapper());

addCondition.whenReady(() -> {
if (isClosed && repeatableOp.retries() != null) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to check for repeatableOp.retries() here? I would assume isClosed is enough to signal and exit?

// The ingester was closed while this retry was waiting to be added back: drop it
addCondition.signalIfReady();
return;
}
operations.add(ingestOp);
currentSize += ingestOp.size();

Expand Down Expand Up @@ -655,6 +676,8 @@ public void close() {
}

isClosed = true;
// Drop the retries that are still pending
dropPendingRetries();

@reta reta Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think dropping is not the ideal option here (I probably miscommunicated the intent of clearing out retries, my apologies for that, let me explain): the flushing logic (flush() call below) would attempt to send all buffered operation, which do include retries, if I am not mistaken. If that is the case, we don't need to drop anything BUT we should make sure that flush() does not attempt to reschedule retries anymore (when isClosed is set), but just does a best effort, last attempt. Does it make sense or I am missing something? Thank you @emreekiziltoprak

// Flush buffered operations
flush();
// and wait for all requests to be completed
Expand All @@ -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<IngesterOperation<Context>> it = operations.iterator(); it.hasNext();) {
IngesterOperation<Context> 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();
}
}

// ----------------------------------------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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<Void> 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<Void> 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
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -542,7 +638,11 @@ public <RequestT, ResponseT, ErrorT> CompletableFuture<ResponseT> performRequest

List<BulkResponseItem> 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<BulkResponse> response = new CompletableFuture<>();
Expand All @@ -558,6 +658,11 @@ public <RequestT, ResponseT, ErrorT> CompletableFuture<ResponseT> 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();
}

Expand Down
Loading