This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new ddac2330c81a CAMEL-28055: camel-docling: enforce batch deadlines and
fail promptly (#31266)
ddac2330c81a is described below
commit ddac2330c81a350e5681499aa281975652318e53
Author: Andrea Cosentino <[email protected]>
AuthorDate: Fri Dec 4 07:26:58 2026 +0100
CAMEL-28055: camel-docling: enforce batch deadlines and fail promptly
(#31266)
Use a shared coordinator for conversion and structured extraction. Observe
results in completion order, preserve input order in the returned batch, and
interrupt outstanding local tasks on timeout or the first failure.
AI-generated by Codex via OSS Helper on behalf of oscerd.
Co-authored-by: Codex <[email protected]>
Signed-off-by: Andrea Cosentino <[email protected]>
---
.../camel/component/docling/DoclingProducer.java | 376 ++++++---------------
.../docling/DoclingBatchCancellationTest.java | 159 +++++++++
2 files changed, 265 insertions(+), 270 deletions(-)
diff --git
a/components/camel-ai/camel-docling/src/main/java/org/apache/camel/component/docling/DoclingProducer.java
b/components/camel-ai/camel-docling/src/main/java/org/apache/camel/component/docling/DoclingProducer.java
index 8e55e401a6f1..c18bf260d881 100644
---
a/components/camel-ai/camel-docling/src/main/java/org/apache/camel/component/docling/DoclingProducer.java
+++
b/components/camel-ai/camel-docling/src/main/java/org/apache/camel/component/docling/DoclingProducer.java
@@ -44,11 +44,11 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@@ -87,11 +87,13 @@ import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.StreamCache;
import org.apache.camel.WrappedFile;
+import org.apache.camel.spi.ThreadPoolProfile;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.support.OAuthHelper;
import org.apache.camel.support.SynchronizationAdapter;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.concurrent.ThreadPoolRejectedPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.jackson.databind.JsonNode;
@@ -953,156 +955,126 @@ public class DoclingProducer extends DefaultProducer {
List<String> inputSources, String outputFormat, int batchSize, int
parallelism,
boolean failOnFirstError, boolean useAsync, long batchTimeout,
OcrSettings ocrSettings) {
- LOG.info(
- "Starting batch conversion of {} documents with batchSize={},
parallelism={}, failOnFirstError={}, timeout={}ms",
- inputSources.size(), batchSize, parallelism, failOnFirstError,
batchTimeout);
-
- BatchProcessingResults results = new BatchProcessingResults();
- results.setStartTimeMs(System.currentTimeMillis());
-
- ExecutorService executor =
getEndpoint().getCamelContext().getExecutorServiceManager()
- .newFixedThreadPool(this, "DoclingBatch", parallelism);
- AtomicInteger index = new AtomicInteger(0);
- AtomicBoolean shouldCancel = new AtomicBoolean(false);
-
- try {
- // Partition documents into sub-batches of batchSize
- for (int batchStart = 0; batchStart < inputSources.size();
batchStart += batchSize) {
- if (failOnFirstError && shouldCancel.get()) {
- break;
- }
-
- int batchEnd = Math.min(batchStart + batchSize,
inputSources.size());
- List<String> subBatch = inputSources.subList(batchStart,
batchEnd);
-
- LOG.debug("Processing sub-batch [{}-{}] of {} total documents",
- batchStart, batchEnd - 1, inputSources.size());
-
- List<CompletableFuture<BatchConversionResult>> futures = new
ArrayList<>();
-
- for (String inputSource : subBatch) {
- final int currentIndex = index.getAndIncrement();
- final String documentId = "doc-" + currentIndex;
-
- CompletableFuture<BatchConversionResult> future =
CompletableFuture.supplyAsync(() -> {
- // Check if we should skip this task due to early
termination
- if (failOnFirstError && shouldCancel.get()) {
- BatchConversionResult cancelledResult = new
BatchConversionResult(documentId, inputSource);
- cancelledResult.setBatchIndex(currentIndex);
- cancelledResult.setSuccess(false);
- cancelledResult.setErrorMessage("Cancelled due to
previous failure");
- return cancelledResult;
- }
-
- BatchConversionResult result = new
BatchConversionResult(documentId, inputSource);
- result.setBatchIndex(currentIndex);
- long startTime = System.currentTimeMillis();
-
- try {
- LOG.debug("Processing document {} (index {}): {}",
documentId, currentIndex, inputSource);
-
- String converted;
- if (useAsync) {
- converted =
convertDocumentAsyncAndWait(inputSource, outputFormat, ocrSettings);
- } else {
- converted = convertDocumentSync(inputSource,
outputFormat, ocrSettings);
- }
-
- result.setResult(converted);
- result.setSuccess(true);
-
result.setProcessingTimeMs(System.currentTimeMillis() - startTime);
+ return processBatch(inputSources, batchSize, parallelism,
failOnFirstError, batchTimeout, "Batch processing",
+ inputSource -> useAsync
+ ? convertDocumentAsyncAndWait(inputSource,
outputFormat, ocrSettings)
+ : convertDocumentSync(inputSource, outputFormat,
ocrSettings));
+ }
- LOG.debug("Successfully processed document {} in
{}ms", documentId,
- result.getProcessingTimeMs());
+ private BatchProcessingResults processBatch(
+ List<String> inputSources, int batchSize, int parallelism, boolean
failOnFirstError, long batchTimeout,
+ String operation, BatchDocumentConverter converter) {
+ LOG.info("Starting {} of {} documents with batchSize={},
parallelism={}, failOnFirstError={}, timeout={}ms",
+ operation, inputSources.size(), batchSize, parallelism,
failOnFirstError, batchTimeout);
- } catch (Exception e) {
- result.setSuccess(false);
- result.setErrorMessage(e.getMessage());
-
result.setProcessingTimeMs(System.currentTimeMillis() - startTime);
+ if (batchSize <= 0) {
+ throw new IllegalArgumentException("batchSize must be positive");
+ }
- LOG.error("Failed to process document {} (index
{}): {}", documentId, currentIndex,
- e.getMessage(), e);
+ if (parallelism <= 0) {
+ throw new IllegalArgumentException("batchParallelism must be
positive");
+ }
- // Signal other tasks to cancel if
failOnFirstError is enabled
- if (failOnFirstError) {
- shouldCancel.set(true);
- }
- }
+ long startNanos = System.nanoTime();
+ long timeoutNanos = TimeUnit.MILLISECONDS.toNanos(batchTimeout);
+ BatchProcessingResults results = new BatchProcessingResults();
+ results.setStartTimeMs(System.currentTimeMillis());
- return result;
- }, executor);
+ var executorManager =
getEndpoint().getCamelContext().getExecutorServiceManager();
+ ThreadPoolProfile profile = new ThreadPoolProfile("DoclingBatch");
+ profile.setPoolSize(parallelism);
+ profile.setMaxPoolSize(parallelism);
+ // A completion can be observed before its worker is available for the
next task.
+ profile.setMaxQueueSize(parallelism);
+ profile.setAllowCoreThreadTimeOut(false);
+ profile.setRejectedPolicy(ThreadPoolRejectedPolicy.Abort);
+ ExecutorService executor = executorManager.newThreadPool(this,
profile.getId(), profile);
+ var completionService = new
ExecutorCompletionService<BatchConversionResult>(executor);
+ List<Future<BatchConversionResult>> pending = new ArrayList<>();
- futures.add(future);
+ try {
+ for (int batchStart = 0; batchStart < inputSources.size();) {
+ if (System.nanoTime() - startNanos >= timeoutNanos) {
+ throw new TimeoutException();
}
-
- // Wait for sub-batch to complete with remaining timeout
- long elapsed = System.currentTimeMillis() -
results.getStartTimeMs();
- long remainingTimeout = batchTimeout - elapsed;
- if (remainingTimeout <= 0) {
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException("Batch processing timed out
after " + batchTimeout + "ms");
+ int size = Math.min(batchSize, inputSources.size() -
batchStart);
+ int batchEnd = batchStart + size;
+ // Keep output in input order even though failures must be
observed in completion order.
+ BatchConversionResult[] ordered = new
BatchConversionResult[size];
+ int next = batchStart;
+
+ while (next < batchEnd && pending.size() < parallelism) {
+ int index = next++;
+ pending.add(
+ completionService.submit(() ->
convertBatchDocument(inputSources.get(index), index, converter)));
}
- CompletableFuture<Void> allOf =
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
+ for (int completed = 0; completed < size; completed++) {
+ long remaining = timeoutNanos - (System.nanoTime() -
startNanos);
+ Future<BatchConversionResult> finished
+ = remaining > 0 ?
completionService.poll(remaining, TimeUnit.NANOSECONDS) : null;
+ if (finished == null) {
+ throw new TimeoutException();
+ }
+ pending.remove(finished);
+ BatchConversionResult result = finished.get();
+ if (failOnFirstError && !result.isSuccess()) {
+ throw new RuntimeException(
+ operation + " failed for document: " +
result.getOriginalPath()
+ + " - " +
result.getErrorMessage());
+ }
+ ordered[result.getBatchIndex() - batchStart] = result;
- try {
- allOf.get(remainingTimeout, TimeUnit.MILLISECONDS);
- } catch (TimeoutException e) {
- LOG.error("Batch processing timed out after {}ms",
batchTimeout);
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException("Batch processing timed out
after " + batchTimeout + "ms", e);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- LOG.error("Batch processing interrupted", e);
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException("Batch processing interrupted",
e);
- } catch (Exception e) {
- LOG.error("Batch processing failed", e);
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException("Batch processing failed", e);
+ if (next < batchEnd && System.nanoTime() - startNanos <
timeoutNanos) {
+ int index = next++;
+ pending.add(completionService
+ .submit(() ->
convertBatchDocument(inputSources.get(index), index, converter)));
+ }
}
- // Collect results from this sub-batch
- for (CompletableFuture<BatchConversionResult> future :
futures) {
- try {
- BatchConversionResult result = future.getNow(null);
- if (result != null) {
- results.addResult(result);
-
- if (failOnFirstError && !result.isSuccess()) {
- LOG.warn("Failing batch due to error in
document {}: {}", result.getDocumentId(),
- result.getErrorMessage());
- break;
- }
- }
- } catch (Exception e) {
- LOG.error("Error retrieving result", e);
- }
+ for (BatchConversionResult result : ordered) {
+ results.addResult(result);
}
+ batchStart = batchEnd;
}
-
+ } catch (TimeoutException e) {
+ throw new RuntimeException(operation + " timed out after " +
batchTimeout + "ms", e);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(operation + " interrupted", e);
+ } catch (ExecutionException e) {
+ throw new RuntimeException(operation + " failed", e.getCause());
} finally {
-
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownGraceful(executor);
+ pending.forEach(future -> future.cancel(true));
+ // Do not wait for graceful termination after the batch deadline
or first failure.
+ executorManager.shutdown(executor);
}
results.setEndTimeMs(System.currentTimeMillis());
+ return results;
+ }
- LOG.info("Batch conversion completed: total={}, success={}, failed={},
time={}ms",
- results.getTotalDocuments(), results.getSuccessCount(),
results.getFailureCount(),
- results.getTotalProcessingTimeMs());
-
- // If failOnFirstError is true and we have failures, throw exception
- if (failOnFirstError && results.hasAnyFailures()) {
- BatchConversionResult firstFailure = results.getFailed().get(0);
- throw new RuntimeException(
- "Batch processing failed for document: " +
firstFailure.getOriginalPath() + " - "
- + firstFailure.getErrorMessage());
+ private BatchConversionResult convertBatchDocument(String inputSource, int
index, BatchDocumentConverter converter) {
+ BatchConversionResult result = new BatchConversionResult("doc-" +
index, inputSource);
+ result.setBatchIndex(index);
+ long start = System.nanoTime();
+ try {
+ result.setResult(converter.convert(inputSource));
+ result.setSuccess(true);
+ } catch (Exception e) {
+ result.setSuccess(false);
+ result.setErrorMessage(e.getMessage());
+ LOG.error("Failed to process document {} (index {}): {}",
result.getDocumentId(), index, e.getMessage(), e);
}
+
result.setProcessingTimeMs(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() -
start));
+ return result;
+ }
- return results;
+ @FunctionalInterface
+ private interface BatchDocumentConverter {
+ String convert(String inputSource) throws Exception;
}
- @SuppressWarnings("unchecked")
private List<String> extractDocumentList(Exchange exchange) throws
IOException {
return containBatchPaths(extractDocumentPaths(exchange));
}
@@ -1366,147 +1338,11 @@ public class DoclingProducer extends DefaultProducer {
List<String> inputSources, int batchSize, int parallelism,
boolean failOnFirstError, boolean useAsync, long batchTimeout,
OcrSettings ocrSettings) {
- LOG.info(
- "Starting batch structured data extraction of {} documents
with batchSize={}, parallelism={}, failOnFirstError={}, timeout={}ms",
- inputSources.size(), batchSize, parallelism, failOnFirstError,
batchTimeout);
-
- BatchProcessingResults results = new BatchProcessingResults();
- results.setStartTimeMs(System.currentTimeMillis());
-
- ExecutorService executor =
getEndpoint().getCamelContext().getExecutorServiceManager()
- .newFixedThreadPool(this, "DoclingBatchStructuredData",
parallelism);
- AtomicInteger index = new AtomicInteger(0);
- AtomicBoolean shouldCancel = new AtomicBoolean(false);
-
- try {
- // Partition documents into sub-batches of batchSize
- for (int batchStart = 0; batchStart < inputSources.size();
batchStart += batchSize) {
- if (failOnFirstError && shouldCancel.get()) {
- break;
- }
-
- int batchEnd = Math.min(batchStart + batchSize,
inputSources.size());
- List<String> subBatch = inputSources.subList(batchStart,
batchEnd);
-
- LOG.debug("Processing sub-batch [{}-{}] of {} total documents",
- batchStart, batchEnd - 1, inputSources.size());
-
- List<CompletableFuture<BatchConversionResult>> futures = new
ArrayList<>();
-
- for (String inputSource : subBatch) {
- final int currentIndex = index.getAndIncrement();
- final String documentId = "doc-" + currentIndex;
-
- CompletableFuture<BatchConversionResult> future =
CompletableFuture.supplyAsync(() -> {
- if (failOnFirstError && shouldCancel.get()) {
- BatchConversionResult cancelledResult = new
BatchConversionResult(documentId, inputSource);
- cancelledResult.setBatchIndex(currentIndex);
- cancelledResult.setSuccess(false);
- cancelledResult.setErrorMessage("Cancelled due to
previous failure");
- return cancelledResult;
- }
-
- BatchConversionResult result = new
BatchConversionResult(documentId, inputSource);
- result.setBatchIndex(currentIndex);
- long startTime = System.currentTimeMillis();
-
- try {
- LOG.debug("Extracting structured data from
document {} (index {}): {}", documentId,
- currentIndex, inputSource);
-
- ConvertDocumentRequest request =
buildStructuredDataRequest(inputSource, ocrSettings);
- String converted;
- if (useAsync) {
- converted =
convertDocumentAsyncAndWait(request);
- } else {
- converted = convertDocumentSync(request);
- }
-
- result.setResult(converted);
- result.setSuccess(true);
-
result.setProcessingTimeMs(System.currentTimeMillis() - startTime);
-
- } catch (Exception e) {
- result.setSuccess(false);
- result.setErrorMessage(e.getMessage());
-
result.setProcessingTimeMs(System.currentTimeMillis() - startTime);
-
- LOG.error("Failed to extract structured data from
document {} (index {}): {}", documentId,
- currentIndex, e.getMessage(), e);
-
- if (failOnFirstError) {
- shouldCancel.set(true);
- }
- }
-
- return result;
- }, executor);
-
- futures.add(future);
- }
-
- // Wait for sub-batch to complete with remaining timeout
- long elapsed = System.currentTimeMillis() -
results.getStartTimeMs();
- long remainingTimeout = batchTimeout - elapsed;
- if (remainingTimeout <= 0) {
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException(
- "Batch structured data extraction timed out after
" + batchTimeout + "ms");
- }
-
- CompletableFuture<Void> allOf =
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
-
- try {
- allOf.get(remainingTimeout, TimeUnit.MILLISECONDS);
- } catch (TimeoutException e) {
- LOG.error("Batch structured data extraction timed out
after {}ms", batchTimeout);
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException(
- "Batch structured data extraction timed out after
" + batchTimeout + "ms", e);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- LOG.error("Batch structured data extraction interrupted",
e);
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException("Batch structured data
extraction interrupted", e);
- } catch (Exception e) {
- LOG.error("Batch structured data extraction failed", e);
- futures.forEach(f -> f.cancel(true));
- throw new RuntimeException("Batch structured data
extraction failed", e);
- }
-
- // Collect results from this sub-batch
- for (CompletableFuture<BatchConversionResult> future :
futures) {
- try {
- BatchConversionResult result = future.getNow(null);
- if (result != null) {
- results.addResult(result);
-
- if (failOnFirstError && !result.isSuccess()) {
- LOG.warn("Failing batch due to error in
document {}: {}", result.getDocumentId(),
- result.getErrorMessage());
- break;
- }
- }
- } catch (Exception e) {
- LOG.error("Error retrieving result", e);
- }
- }
- }
-
- } finally {
-
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownGraceful(executor);
- }
-
- results.setEndTimeMs(System.currentTimeMillis());
-
- if (failOnFirstError && results.hasAnyFailures()) {
- BatchConversionResult firstFailure = results.getFailed().get(0);
- throw new RuntimeException(
- "Batch structured data extraction failed for document: " +
firstFailure.getOriginalPath() + " - "
- + firstFailure.getErrorMessage());
- }
-
- return results;
+ return processBatch(inputSources, batchSize, parallelism,
failOnFirstError, batchTimeout,
+ "Batch structured data extraction", inputSource -> {
+ ConvertDocumentRequest request =
buildStructuredDataRequest(inputSource, ocrSettings);
+ return useAsync ? convertDocumentAsyncAndWait(request) :
convertDocumentSync(request);
+ });
}
/**
diff --git
a/components/camel-ai/camel-docling/src/test/java/org/apache/camel/component/docling/DoclingBatchCancellationTest.java
b/components/camel-ai/camel-docling/src/test/java/org/apache/camel/component/docling/DoclingBatchCancellationTest.java
new file mode 100644
index 000000000000..4cbcefd8e29b
--- /dev/null
+++
b/components/camel-ai/camel-docling/src/test/java/org/apache/camel/component/docling/DoclingBatchCancellationTest.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.docling;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Proxy;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import ai.docling.serve.api.DoclingServeApi;
+import ai.docling.serve.api.convert.request.ConvertDocumentRequest;
+import ai.docling.serve.api.convert.request.source.HttpSource;
+import org.apache.camel.Exchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class DoclingBatchCancellationTest extends CamelTestSupport {
+
+ @ParameterizedTest
+ @EnumSource(value = DoclingOperations.class, names = {
"BATCH_CONVERT_TO_MARKDOWN", "BATCH_EXTRACT_STRUCTURED_DATA" })
+ void reportsFirstErrorAndInterruptsTheOtherWorker(DoclingOperations
operation) throws Exception {
+ CountDownLatch blocked = new CountDownLatch(1);
+ CountDownLatch interrupted = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicInteger calls = new AtomicInteger();
+ DoclingProducer producer = producer(operation, 20000, request -> {
+ if (calls.getAndIncrement() == 0) {
+ waitForRelease(blocked, interrupted, release);
+ } else if (blocked.await(10, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("document conversion failed");
+ }
+ throw new IllegalStateException("test synchronization failed");
+ });
+ try {
+ assertThatThrownBy(() -> producer.process(batch(producer, 3)))
+ .hasMessageContaining("failed for document:")
+ .hasMessageContaining("document conversion failed");
+ assertThat(interrupted.await(10, TimeUnit.SECONDS)).isTrue();
+ assertThat(calls.get()).isEqualTo(2);
+ } finally {
+ release.countDown();
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = DoclingOperations.class, names = {
"BATCH_CONVERT_TO_MARKDOWN", "BATCH_EXTRACT_STRUCTURED_DATA" })
+ @Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
+ void interruptsRunningWorkWhenTheBatchTimesOut(DoclingOperations
operation) throws Exception {
+ CountDownLatch blocked = new CountDownLatch(1);
+ CountDownLatch interrupted = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ DoclingProducer producer = producer(operation, 5000, request ->
waitForRelease(blocked, interrupted, release));
+ var executorManager = context.getExecutorServiceManager();
+ long originalShutdownWait =
executorManager.getShutdownAwaitTermination();
+ executorManager.setShutdownAwaitTermination(60000);
+ try {
+ assertThatThrownBy(() -> producer.process(batch(producer, 1)))
+ .hasMessageContaining("timed out after 5000ms")
+ .hasCauseInstanceOf(TimeoutException.class);
+ assertThat(blocked.getCount()).isZero();
+ assertThat(interrupted.await(10, TimeUnit.SECONDS)).isTrue();
+ } finally {
+ release.countDown();
+ executorManager.setShutdownAwaitTermination(originalShutdownWait);
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = DoclingOperations.class, names = {
"BATCH_CONVERT_TO_MARKDOWN", "BATCH_EXTRACT_STRUCTURED_DATA" })
+ void keepsInputOrderWhenContinuingAfterAnError(DoclingOperations
operation) throws Exception {
+ CountDownLatch thirdStarted = new CountDownLatch(1);
+ DoclingProducer producer = producer(operation, 30000, request -> {
+ HttpSource source = (HttpSource) request.getSources().getFirst();
+ String path = source.getUrl().getPath();
+ if ("/one.pdf".equals(path) && !thirdStarted.await(10,
TimeUnit.SECONDS)) {
+ throw new AssertionError("The third conversion did not start");
+ }
+ if ("/three.pdf".equals(path)) {
+ thirdStarted.countDown();
+ }
+ throw new IllegalStateException("Conversion failed: " + path);
+ });
+ Exchange exchange = batch(producer, 3);
+ exchange.getIn().setHeader(DoclingHeaders.BATCH_FAIL_ON_FIRST_ERROR,
false);
+
+ producer.process(exchange);
+
+ BatchProcessingResults results =
exchange.getMessage().getBody(BatchProcessingResults.class);
+
assertThat(results.getResults()).extracting(BatchConversionResult::getBatchIndex).containsExactly(0,
1, 2);
+ assertThat(results.getFailureCount()).isEqualTo(3);
+ }
+
+ private DoclingProducer producer(DoclingOperations operation, long
timeout, StubConversion conversion) throws Exception {
+ DoclingEndpoint endpoint =
context.getEndpoint("docling:convert?useDoclingServe=true&allowUrlSource=true"
+ +
"&batchParallelism=2&batchTimeout=" + timeout
+ + "&operation=" +
operation,
+ DoclingEndpoint.class);
+ DoclingProducer producer = (DoclingProducer) endpoint.createProducer();
+ DoclingServeApi client = (DoclingServeApi) Proxy.newProxyInstance(
+ DoclingServeApi.class.getClassLoader(), new Class<?>[] {
DoclingServeApi.class },
+ (proxy, method, args) -> {
+ if (!"convertSource".equals(method.getName())) {
+ throw new
UnsupportedOperationException(method.getName());
+ }
+ conversion.execute((ConvertDocumentRequest) args[0]);
+ throw new AssertionError("The stub conversion unexpectedly
completed");
+ });
+ Field field =
DoclingProducer.class.getDeclaredField("doclingServeApi");
+ field.setAccessible(true);
+ field.set(producer, client);
+ return producer;
+ }
+
+ private static Exchange batch(DoclingProducer producer, int size) {
+ Exchange exchange = producer.getEndpoint().createExchange();
+ exchange.getIn().setBody(List.of(
+ "https://example.com/one.pdf", "https://example.com/two.pdf",
"https://example.com/three.pdf")
+ .subList(0, size));
+ return exchange;
+ }
+
+ private static void waitForRelease(CountDownLatch blocked, CountDownLatch
interrupted, CountDownLatch release)
+ throws InterruptedException {
+ blocked.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ interrupted.countDown();
+ throw e;
+ }
+ }
+
+ @FunctionalInterface
+ private interface StubConversion {
+ void execute(ConvertDocumentRequest request) throws Exception;
+ }
+}