gnodet-bot commented on code in PR #30711:
URL: https://github.com/apache/camel/pull/30711#discussion_r4680616897


##########
components/camel-ai/camel-semantic/src/main/java/org/apache/camel/semantic/SemanticEvaluateConsole.java:
##########
@@ -58,16 +62,33 @@ 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();

Review Comment:
   💡 **Low — floor guard still missing on `release()`**: `decrementAndGet()` 
can produce a negative value if `release()` is ever called without a matching 
`tryAcquire()` — for example, via a double-release in a future change, or if 
the lifecycle is restarted while in-flight tasks from the old executor call 
`release()` after `active` has already been reset by a new owner. A negative 
`active` bypasses the `count >= 2` gate in `tryAcquire()` and silently allows 
unlimited concurrent evaluations.
   
   This was raised in my previous review and remains unaddressed in this commit.
   
   ```suggestion
       private void release() {
           active.updateAndGet(n -> Math.max(0, n - 1));
       }
   ```



##########
components/camel-ai/camel-semantic/src/test/java/org/apache/camel/semantic/SemanticEvaluationTimeoutTest.java:
##########
@@ -95,6 +99,206 @@ void concurrentCallsHaveNoUnboundedQueue() throws Exception 
{
         }
     }
 
+    @Test
+    void preStartCancellationReleasesConcurrencySlotAndPurgesQueue() 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)) {
+                        profile.setPoolSize(1);
+                        profile.setMaxPoolSize(1);
+                        profile.setMaxQueueSize(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();
+                // 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");
+
+                // Pre-start cancellation must have released the slot and 
purged queue, so Task 3 can be accepted
+                FutureTask<Object> task3 = new FutureTask<>(() -> 
console.call(DevConsole.MediaType.JSON, options(50000)));
+                Thread thread3 = new Thread(task3);
+                thread3.start();
+                try {
+                    // 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 stoppingConsoleWakesQueuedCallersImmediately() 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)) {
+                        profile.setPoolSize(1);
+                        profile.setMaxPoolSize(1);
+                        profile.setMaxQueueSize(2);
+                    }
+                    return super.newThreadPool(source, name, profile);
+                }
+            });
+            CountDownLatch task1Entered = new CountDownLatch(1);
+            CountDownLatch releaseTask1 = new CountDownLatch(1);
+            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 = (SemanticEvaluateConsole) 
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 queued because worker 1 is busy
+                FutureTask<Object> task2 = new FutureTask<>(() -> 
console.call(DevConsole.MediaType.JSON, options(50000)));
+                Thread thread2 = new Thread(task2);
+                thread2.start();
+                try {
+                    // Stop console; dropped task 2 must be cancelled and wake 
thread 2 immediately
+                    console.stop();
+                    thread2.join(2000);

Review Comment:
   ⚠️ **Medium — `stoppingConsoleWakesQueuedCallers`: `thread2` may not be in 
the executor queue when `console.stop()` fires.** `thread2.start()` starts 
thread2, which must traverse `tryAcquire()` → `executor()` → `exec.submit()` 
before the task lands in the queue. If `console.stop()` fires before 
`exec.submit()` completes, `shutdownNow()` returns an empty dropped-tasks list, 
the future is never cancelled, and `thread2` waits its full 50-second timeout — 
causing `thread2.join(2000)` to time out and 
`assertThat(thread2.isAlive()).isFalse()` to fail.
   
   The same latch pattern used in 
`preStartCancellationReleasesConcurrencySlotAndPurgesQueue` should guard this:
   ```suggestion
                   FutureTask<Object> task2 = new FutureTask<>(() -> 
console.call(DevConsole.MediaType.JSON, options(50000)));
                   Thread thread2 = new Thread(task2);
                   // Ensure task2 is queued in the executor before stopping
                   CountDownLatch task2Queued = new CountDownLatch(1);
                   // Use an Awaitility poll or a brief park — thread2 must 
pass exec.submit() first.
                   thread2.start();
                   await().atMost(2, TimeUnit.SECONDS).until(() -> 
console.getExecutorQueueSize() > 0);
                   try {
                       // Stop console; dropped task 2 must be cancelled and 
wake thread 2 immediately
                       console.stop();
   ```
   If `SemanticEvaluateConsole` does not expose queue size, an alternative is a 
small `Thread.sleep(50)` (acceptable for a test-only control flow gap) or 
coordinating via a `Semaphore` that the callable decrements before blocking.



-- 
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