luigidemasi commented on code in PR #30711:
URL: https://github.com/apache/camel/pull/30711#discussion_r4684553459
##########
components/camel-ai/camel-semantic/src/main/java/org/apache/camel/semantic/SemanticEvaluateConsole.java:
##########
@@ -125,16 +164,71 @@ protected Map<String, Object> doCallJson(Map<String,
Object> options) {
SemanticAuditService.Request request
= audit.request(options.containsKey(OPERATION) ?
"direct_sample" : "definition_sample");
String failure;
+ AtomicBoolean claimed = new AtomicBoolean();
+ boolean acquired = false;
try {
long timeout = optionLong(options, TIMEOUT, 50000);
if (timeout < 1 || timeout > 50000) {
throw new IllegalArgumentException("Evaluation timeout must be
between 1 and 50000 milliseconds");
}
- task = executor().submit(() -> evaluate(options, request));
- return task.get(timeout, TimeUnit.MILLISECONDS);
+ long deadline = start + TimeUnit.MILLISECONDS.toNanos(timeout);
+ if (stopped || isStopping()) {
+ throw new IllegalStateException("Semantic evaluation console
is stopping or stopped");
+ }
+ if (!tryAcquire()) {
+ throw new RejectedExecutionException("Busy: semantic
evaluations are already running");
+ }
+ acquired = true;
+ ExecutorService exec = executor();
+ Callable<Map<String, Object>> callable = () -> {
+ if (!claimed.compareAndSet(false, true)) {
+ throw new CancellationException("Evaluation cancelled");
+ }
+ try {
+ if (System.nanoTime() > deadline) {
+ throw new TimeoutException("Evaluation timed out;
cancellation requested");
+ }
+ return evaluate(options, request);
+ } finally {
+ release();
+ }
+ };
+ while (true) {
+ try {
+ task = exec.submit(callable);
+ break;
+ } catch (RejectedExecutionException e) {
+ if (System.nanoTime() >= deadline) {
+ throw new TimeoutException("Evaluation timed out;
cancellation requested");
+ }
+ LockSupport.parkNanos(100_000);
Review Comment:
**P2 — End submission retries on interruption or shutdown.** With Camel’s
virtual-thread executor, an interrupted submitter gets
`RejectedExecutionException` with its interrupt flag restored. `parkNanos` then
returns immediately. My caller kept retrying for 998 ms of a 1-second timeout
and reported a timeout instead of cancellation.
Shutdown is also permanent for the captured `exec`. I stopped and restarted
the console with two callers retrying. Both retained their slots for the rest
of their 1.5-second deadlines, and the restarted console returned `Busy` to a
fresh call.
This change made both callers return promptly in my checks and preserved the
successful handoff. The existing `InterruptedException` handler restores the
flag and records cancellation. The `LockSupport` import can then be removed.
```suggestion
if (exec.isShutdown()) {
throw new CancellationException("Evaluation
cancelled");
}
TimeUnit.MICROSECONDS.sleep(100);
```
_Codex on behalf of @luigidemasi._
##########
components/camel-ai/camel-semantic/src/test/java/org/apache/camel/semantic/SemanticEvaluationTimeoutTest.java:
##########
@@ -95,6 +105,326 @@ void concurrentCallsHaveNoUnboundedQueue() throws
Exception {
}
}
+ @Test
+ void preStartCancellationReleasesConcurrencySlotAndPurgesQueue() throws
Exception {
+ try (var context = new DefaultCamelContext()) {
+ BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(2);
+ context.setExecutorServiceManager(new
DefaultExecutorServiceManager(context) {
+ @Override
+ public ExecutorService newThreadPool(Object source, String
name, ThreadPoolProfile profile) {
+ if ("SemanticEvaluation".equals(name)) {
+ return new ThreadPoolExecutor(1, 1, 0,
TimeUnit.MILLISECONDS, queue);
+ }
+ return super.newThreadPool(source, name, profile);
+ }
+ });
+ CountDownLatch task1Entered = new CountDownLatch(1);
+ CountDownLatch releaseTask1 = new CountDownLatch(1);
+ AtomicInteger expertCalls = new AtomicInteger();
+ context.getRegistry().bind("waiting", new
SemanticMetadataConsoleTest.Detector() {
+ @Override
+ public void validate(SemanticEvaluation evaluation) {
+ }
+
+ @Override
+ public SemanticResult evaluate(SemanticEvaluation evaluation,
Object state) {
+ expertCalls.incrementAndGet();
+ if (task1Entered.getCount() > 0) {
+ task1Entered.countDown();
+ try {
+ releaseTask1.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ return new SemanticResult(false, null, null, null, null);
+ }
+ });
+ context.start();
+ var console =
PluginHelper.getDevConsoleResolver(context).resolveDevConsole("semantic-evaluate");
+ FutureTask<Object> task1 = new FutureTask<>(() ->
console.call(DevConsole.MediaType.JSON, options(50000)));
+ Thread thread1 = new Thread(task1);
+ thread1.start();
+ try {
+ assertThat(task1Entered.await(5, TimeUnit.SECONDS)).isTrue();
+ // Task 2 is submitted while worker is busy with Task 1; Task
2 is queued before starting
+ JsonObject timeoutResult = (JsonObject)
console.call(DevConsole.MediaType.JSON, options(50));
+ assertThat(timeoutResult).containsEntry("status", "failed");
+ assertThat(timeoutResult.getString("error")).contains("timed
out", "cancellation requested");
+
+ // Verify that while Task 1 is still held, cancelled Task 2
has been purged from the queue
+ await().atMost(5, TimeUnit.SECONDS).until(queue::isEmpty);
+
+ // Pre-start cancellation must have released the slot and
purged queue, so Task 3 can be queued while Task 1 is still held
+ FutureTask<Object> task3 = new FutureTask<>(() ->
console.call(DevConsole.MediaType.JSON, options(50000)));
+ Thread thread3 = new Thread(task3);
+ thread3.start();
+ try {
+ // Task 3 is visibly queued while Task 1 is still held
+ await().atMost(5, TimeUnit.SECONDS).until(() ->
queue.size() == 1);
+
+ // Release task 1 so the worker becomes free to execute
task 3
+ releaseTask1.countDown();
+ JsonObject task3Result = (JsonObject) task3.get(5,
TimeUnit.SECONDS);
+ assertThat(task3Result).containsEntry("status", "success");
+ // Expert was called for task 1 and task 3, never for
cancelled task 2
+ assertThat(expertCalls).hasValue(2);
+ } finally {
+ task3.cancel(true);
+ thread3.join(5000);
+ }
+ } finally {
+ releaseTask1.countDown();
+ task1.cancel(true);
+ thread1.join(5000);
+ }
+ }
+ }
+
+ @Test
+ void virtualThreadSubmissionDoesNotBlockBeyondDeadline() throws Exception {
+ try (var context = new DefaultCamelContext()) {
+ CountDownLatch task1Entered = new CountDownLatch(1);
+ CountDownLatch releaseTask1 = new CountDownLatch(1);
+ context.setExecutorServiceManager(new
DefaultExecutorServiceManager(context) {
+ @Override
+ public ExecutorService newThreadPool(Object source, String
name, ThreadPoolProfile profile) {
+ if ("SemanticEvaluation".equals(name)) {
+ return new BoundedExecutorService(
+ Executors.newCachedThreadPool(),
+ 1, profile.getKeepAliveTime(),
profile.getTimeUnit(), false, profile.getRejectedPolicy());
+ }
+ return super.newThreadPool(source, name, profile);
+ }
+ });
+ context.getRegistry().bind("waiting", new
SemanticMetadataConsoleTest.Detector() {
+ @Override
+ public void validate(SemanticEvaluation evaluation) {
+ }
+
+ @Override
+ public SemanticResult evaluate(SemanticEvaluation evaluation,
Object state) {
+ task1Entered.countDown();
+ try {
+ releaseTask1.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ return new SemanticResult(false, null, null, null, null);
+ }
+ });
+ context.start();
+ var console =
PluginHelper.getDevConsoleResolver(context).resolveDevConsole("semantic-evaluate");
+ FutureTask<Object> task1 = new FutureTask<>(() ->
console.call(DevConsole.MediaType.JSON, options(50000)));
+ Thread thread1 = new Thread(task1);
+ thread1.start();
+ try {
+ assertThat(task1Entered.await(5, TimeUnit.SECONDS)).isTrue();
+ long callStart = System.nanoTime();
+ // Task 2 submitted with a 50ms timeout while Task 1 is held.
It must return promptly (not block for seconds).
+ JsonObject result = (JsonObject)
console.call(DevConsole.MediaType.JSON, options(50));
+ long durationMillis =
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - callStart);
+ assertThat(durationMillis).isLessThan(2000);
+ assertThat(result).containsEntry("status", "failed");
Review Comment:
**P2 — Cover a successful handoff after a transient rejection.** This
assertion accepts both an immediate `Busy` and the expected timeout. I removed
the submission retry and all 435 module tests still passed. Please assert the
timeout reason here and add a case that releases the permit before the new
caller’s deadline. Holding a completed `FutureTask` in `done()` until the next
submission sees a rejection makes that ordering deterministic. The next call
should succeed.
_Codex on behalf of @luigidemasi._
##########
components/camel-ai/camel-semantic/src/test/java/org/apache/camel/semantic/SemanticEvaluationTimeoutTest.java:
##########
@@ -95,6 +105,326 @@ void concurrentCallsHaveNoUnboundedQueue() throws
Exception {
}
}
+ @Test
+ void preStartCancellationReleasesConcurrencySlotAndPurgesQueue() throws
Exception {
+ try (var context = new DefaultCamelContext()) {
+ BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(2);
+ context.setExecutorServiceManager(new
DefaultExecutorServiceManager(context) {
+ @Override
+ public ExecutorService newThreadPool(Object source, String
name, ThreadPoolProfile profile) {
+ if ("SemanticEvaluation".equals(name)) {
+ return new ThreadPoolExecutor(1, 1, 0,
TimeUnit.MILLISECONDS, queue);
+ }
+ return super.newThreadPool(source, name, profile);
+ }
+ });
+ CountDownLatch task1Entered = new CountDownLatch(1);
+ CountDownLatch releaseTask1 = new CountDownLatch(1);
+ AtomicInteger expertCalls = new AtomicInteger();
+ context.getRegistry().bind("waiting", new
SemanticMetadataConsoleTest.Detector() {
+ @Override
+ public void validate(SemanticEvaluation evaluation) {
+ }
+
+ @Override
+ public SemanticResult evaluate(SemanticEvaluation evaluation,
Object state) {
+ expertCalls.incrementAndGet();
+ if (task1Entered.getCount() > 0) {
+ task1Entered.countDown();
+ try {
+ releaseTask1.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ return new SemanticResult(false, null, null, null, null);
+ }
+ });
+ context.start();
+ var console =
PluginHelper.getDevConsoleResolver(context).resolveDevConsole("semantic-evaluate");
+ FutureTask<Object> task1 = new FutureTask<>(() ->
console.call(DevConsole.MediaType.JSON, options(50000)));
+ Thread thread1 = new Thread(task1);
+ thread1.start();
+ try {
+ assertThat(task1Entered.await(5, TimeUnit.SECONDS)).isTrue();
+ // Task 2 is submitted while worker is busy with Task 1; Task
2 is queued before starting
+ JsonObject timeoutResult = (JsonObject)
console.call(DevConsole.MediaType.JSON, options(50));
+ assertThat(timeoutResult).containsEntry("status", "failed");
+ assertThat(timeoutResult.getString("error")).contains("timed
out", "cancellation requested");
+
+ // Verify that while Task 1 is still held, cancelled Task 2
has been purged from the queue
+ await().atMost(5, TimeUnit.SECONDS).until(queue::isEmpty);
+
+ // Pre-start cancellation must have released the slot and
purged queue, so Task 3 can be queued while Task 1 is still held
+ FutureTask<Object> task3 = new FutureTask<>(() ->
console.call(DevConsole.MediaType.JSON, options(50000)));
+ Thread thread3 = new Thread(task3);
+ thread3.start();
+ try {
+ // Task 3 is visibly queued while Task 1 is still held
+ await().atMost(5, TimeUnit.SECONDS).until(() ->
queue.size() == 1);
+
+ // Release task 1 so the worker becomes free to execute
task 3
+ releaseTask1.countDown();
+ JsonObject task3Result = (JsonObject) task3.get(5,
TimeUnit.SECONDS);
+ assertThat(task3Result).containsEntry("status", "success");
+ // Expert was called for task 1 and task 3, never for
cancelled task 2
+ assertThat(expertCalls).hasValue(2);
+ } finally {
+ task3.cancel(true);
+ thread3.join(5000);
+ }
+ } finally {
+ releaseTask1.countDown();
+ task1.cancel(true);
+ thread1.join(5000);
+ }
+ }
+ }
+
+ @Test
+ void virtualThreadSubmissionDoesNotBlockBeyondDeadline() throws Exception {
+ try (var context = new DefaultCamelContext()) {
+ CountDownLatch task1Entered = new CountDownLatch(1);
+ CountDownLatch releaseTask1 = new CountDownLatch(1);
+ context.setExecutorServiceManager(new
DefaultExecutorServiceManager(context) {
+ @Override
+ public ExecutorService newThreadPool(Object source, String
name, ThreadPoolProfile profile) {
+ if ("SemanticEvaluation".equals(name)) {
+ return new BoundedExecutorService(
+ Executors.newCachedThreadPool(),
+ 1, profile.getKeepAliveTime(),
profile.getTimeUnit(), false, profile.getRejectedPolicy());
+ }
+ return super.newThreadPool(source, name, profile);
+ }
+ });
+ context.getRegistry().bind("waiting", new
SemanticMetadataConsoleTest.Detector() {
+ @Override
+ public void validate(SemanticEvaluation evaluation) {
+ }
+
+ @Override
+ public SemanticResult evaluate(SemanticEvaluation evaluation,
Object state) {
+ task1Entered.countDown();
+ try {
+ releaseTask1.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ return new SemanticResult(false, null, null, null, null);
+ }
+ });
+ context.start();
+ var console =
PluginHelper.getDevConsoleResolver(context).resolveDevConsole("semantic-evaluate");
+ FutureTask<Object> task1 = new FutureTask<>(() ->
console.call(DevConsole.MediaType.JSON, options(50000)));
+ Thread thread1 = new Thread(task1);
+ thread1.start();
+ try {
+ assertThat(task1Entered.await(5, TimeUnit.SECONDS)).isTrue();
+ long callStart = System.nanoTime();
+ // Task 2 submitted with a 50ms timeout while Task 1 is held.
It must return promptly (not block for seconds).
+ JsonObject result = (JsonObject)
console.call(DevConsole.MediaType.JSON, options(50));
+ long durationMillis =
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - callStart);
+ assertThat(durationMillis).isLessThan(2000);
+ assertThat(result).containsEntry("status", "failed");
+ } finally {
+ releaseTask1.countDown();
+ task1.cancel(true);
+ thread1.join(5000);
+ }
+ }
+ }
+
+ @Test
+ void workerStartingAfterDeadlineReturnsTimeoutResponse() throws Exception {
+ try (var context = new DefaultCamelContext()) {
+ CountDownLatch workerProceed = new CountDownLatch(1);
+ AtomicInteger expertCalls = new AtomicInteger();
+ context.setExecutorServiceManager(new
DefaultExecutorServiceManager(context) {
+ @Override
+ public ExecutorService newThreadPool(Object source, String
name, ThreadPoolProfile profile) {
+ if ("SemanticEvaluation".equals(name)) {
+ return new ThreadPoolExecutor(
+ 1, 1, 0, TimeUnit.MILLISECONDS, new
LinkedBlockingQueue<>(2)) {
+ @Override
+ protected void beforeExecute(Thread t, Runnable r)
{
+ super.beforeExecute(t, r);
+ try {
+ workerProceed.await(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ };
+ }
+ return super.newThreadPool(source, name, profile);
+ }
+ });
+ context.getRegistry().bind("waiting", new
SemanticMetadataConsoleTest.Detector() {
+ @Override
+ public void validate(SemanticEvaluation evaluation) {
+ }
+
+ @Override
+ public SemanticResult evaluate(SemanticEvaluation evaluation,
Object state) {
+ expertCalls.incrementAndGet();
+ return new SemanticResult(false, null, null, null, null);
+ }
+ });
+ context.start();
+ var console =
PluginHelper.getDevConsoleResolver(context).resolveDevConsole("semantic-evaluate");
+ long submitTime = System.nanoTime();
+ FutureTask<Object> jsonTask = new FutureTask<>(() ->
console.call(DevConsole.MediaType.JSON, options(50)));
+ Thread jsonThread = new Thread(jsonTask);
+ jsonThread.start();
+ try {
+ // Await until task's 50ms deadline has passed while caller is
in timed get
+ await().atMost(5, TimeUnit.SECONDS)
+ .until(() ->
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - submitTime) >= 60);
Review Comment:
**P2 — Make the worker’s deadline check observable.** The clock starts
before `jsonThread.start()`. Reaching 60 ms does not establish that the caller
entered timed `get` or that the worker ran the callable. The caller can already
have timed out and cancelled the future. I removed the worker’s deadline check
entirely and all 435 module tests still passed.
A controlled future can signal entry into timed `get`, let the worker finish
after expiry, then let the caller observe completion. With that ordering, the
current code returns a timeout in JSON and text. Removing the guard produced
`status=success` and ran the expert. Please cover that ordering and keep the
zero-provider-calls assertion.
_Codex on behalf of @luigidemasi._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]