luigidemasi commented on code in PR #30711:
URL: https://github.com/apache/camel/pull/30711#discussion_r4681697100


##########
components/camel-ai/camel-semantic/src/test/java/org/apache/camel/semantic/SemanticEvaluationTimeoutTest.java:
##########
@@ -95,6 +105,328 @@ 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(
+                                
java.util.concurrent.Executors.newCachedThreadPool(),
+                                1, 0, TimeUnit.MILLISECONDS, false, 
ThreadPoolRejectedPolicy.Abort);

Review Comment:
   **P2 — Exercise the console’s pool configuration in this test.** The fixture 
ignores the supplied `profile` and gives its own executor a zero permit wait. I 
changed the production wait back to 60 seconds and this test still passed. Use 
the profile from the console or run with Camel’s real virtual-thread factory. 
Hold the executor permits while a short-deadline caller submits, and verify it 
returns before those permits are released. Restoring the 60-second wait should 
fail the test.
   
   _Codex on behalf of @luigidemasi._



##########
components/camel-ai/camel-semantic/src/test/java/org/apache/camel/semantic/SemanticEvaluationTimeoutTest.java:
##########
@@ -95,6 +105,328 @@ 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(
+                                
java.util.concurrent.Executors.newCachedThreadPool(),
+                                1, 0, TimeUnit.MILLISECONDS, false, 
ThreadPoolRejectedPolicy.Abort);
+                    }
+                    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()) {
+            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));
+                    }
+                    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();
+                // Submit task 2 with 50ms timeout
+                FutureTask<Object> task2 = new FutureTask<>(() -> 
console.call(DevConsole.MediaType.JSON, options(50)));
+                Thread thread2 = new Thread(task2);
+                thread2.start();
+                // Wait for task 2's 50ms deadline to pass
+                Thread.sleep(100);

Review Comment:
   **P2 — Make the worker observe expiry before the caller processes its 
timeout.** During this 100 ms sleep, the 50 ms caller can time out, cancel task 
2, and remove it from the queue before the worker is released. I changed the 
worker’s expiry branch back to `return null` and this test still passed.
   
   Please replace the sleep with a controlled execution order. Let the caller 
enter timed `get`, let the worker complete after the deadline, then let the 
caller observe that completion. With that ordering, the current code returns a 
structured timeout in JSON and text, and restoring `return null` fails. This 
also follows the test guidance in `AGENTS.md`.
   
   _Codex on behalf of @luigidemasi._



##########
components/camel-ai/camel-semantic/src/main/java/org/apache/camel/semantic/SemanticEvaluateConsole.java:
##########
@@ -58,17 +64,41 @@ public class SemanticEvaluateConsole extends 
AbstractDevConsole {
               javaType = "java.lang.Long")
     public static final String TIMEOUT = "timeout";
 
+    private final AtomicInteger active = new AtomicInteger();
     private ExecutorService executor;
     // A resolver-created console may be called without starting it; only an 
explicit stop rejects calls.
-    private boolean stopped;
+    private volatile boolean stopped;
+
+    private boolean tryAcquire() {
+        while (true) {
+            int count = active.get();
+            if (count >= 2) {
+                return false;
+            }
+            if (active.compareAndSet(count, count + 1)) {
+                return true;
+            }
+        }
+    }
+
+    private void release() {
+        active.decrementAndGet();
+    }
 
     private synchronized ExecutorService executor() throws Exception {
         if (stopped || isStopping()) {
             throw new IllegalStateException("Semantic evaluation console is 
stopping or stopped");
         }
         if (executor == null) {
-            executor = new 
ThreadPoolBuilder(getCamelContext()).poolSize(2).maxPoolSize(2).maxQueueSize(0)
-                    
.rejectedPolicy(ThreadPoolRejectedPolicy.Abort).build(this, 
"SemanticEvaluation");
+            ThreadPoolProfile profile = new ThreadPoolProfile();
+            profile.setPoolSize(2);
+            profile.setMaxPoolSize(2);
+            profile.setMaxQueueSize(2);
+            profile.setAllowCoreThreadTimeOut(false);
+            profile.setKeepAliveTime(0L);

Review Comment:
   **P2 — A completed evaluation can still cause the next call to return 
`Busy`.** With virtual threads enabled, `BoundedExecutorService` releases its 
permit after `FutureTask.run()` returns. The caller can already have received 
the result and submitted its next request. With a zero wait here, that request 
can lose the race for the permit.
   
   Using the default Camel executor, I held one provider call open and made 
10,000 sequential calls from a second client, waiting for each result before 
submitting the next. I saw 258 false `Busy` responses on this head, 7 on a 
repeat, and 0 on `edf6d03a`. Pausing the completed `FutureTask` in `done()` 
also reproduces the rejection deterministically. Please let the next evaluation 
use the released slot while keeping submission within its request deadline.
   
   _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]

Reply via email to