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


##########
components/camel-ai/camel-semantic/src/main/java/org/apache/camel/semantic/SemanticEvaluateConsole.java:
##########
@@ -147,6 +193,9 @@ protected Map<String, Object> doCallJson(Map<String, 
Object> options) {
             if (task != null && !task.isDone()) {
                 task.cancel(true);
             }
+            if (acquired && claimed.compareAndSet(false, true)) {

Review Comment:
   **P2 — Reclaim the platform queue entry when cancelling pending work.** The 
claim handoff releases the console slot, but `Future.cancel(true)` can leave 
the cancelled future in the thread pool’s queue. With workers held before 
execution, I observed two cancelled futures filling the queue and zero expert 
invocations. A fresh request immediately returned `Busy`. Capacity recovers 
when a worker drains the entries. Please remove cancelled queued work as part 
of cancellation so that a request can use the slot that was just returned.
   
   _Codex on behalf of @luigidemasi._



##########
components/camel-ai/camel-semantic/src/main/java/org/apache/camel/semantic/SemanticEvaluateConsole.java:
##########
@@ -125,12 +152,31 @@ 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));
+            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();
+            task = exec.submit(() -> {

Review Comment:
   **P2 — Include executor admission in the evaluation deadline.** With virtual 
threads enabled, `maxQueueSize(2)` selects Camel’s `BoundedExecutorService`, 
whose `execute()` waits for a permit inside `submit()`. I held the workers 
before their callables started and let two requests time out. A fresh request 
with a 25 ms timeout was still waiting inside `submit()` at 500 ms. When I 
released the workers, it invoked the expert and returned success at 524 ms. The 
same request timed out on the base revision. Please ensure submission is 
non-blocking or bounded by the remaining request time, and prevent an expired 
request from starting provider work.
   
   _Codex on behalf of @luigidemasi._



##########
components/camel-ai/camel-semantic/src/test/java/org/apache/camel/semantic/SemanticEvaluationTimeoutTest.java:
##########
@@ -95,6 +95,103 @@ void concurrentCallsHaveNoUnboundedQueue() throws Exception 
{
         }
     }
 
+    @Test
+    void preStartCancellationReleasesConcurrencySlot() throws Exception {
+        try (var context = new DefaultCamelContext()) {
+            var expert = new WaitingExpert(1);
+            context.getRegistry().bind("waiting", expert);
+            context.start();
+            var console = 
PluginHelper.getDevConsoleResolver(context).resolveDevConsole("semantic-evaluate");
+            FutureTask<Object> running = new FutureTask<>(() -> 
console.call(DevConsole.MediaType.JSON, options(50000)));
+            Thread runningThread = new Thread(running);
+            runningThread.start();
+            try {
+                assertThat(expert.entered.await(5, TimeUnit.SECONDS)).isTrue();
+                // Second call times out quickly (before running) or runs and 
times out
+                JsonObject timeoutResult = (JsonObject) 
console.call(DevConsole.MediaType.JSON, options(50));

Review Comment:
   **P2 — Force pre-start cancellation and shutdown in the regression tests.** 
The second worker is free here, so the second evaluation can enter the provider 
before it times out. With pre-start slot release disabled, this test still 
passed on three consecutive reruns. Removing the cancellation of tasks drained 
by `shutdownNow()` also left all 14 console and timeout tests green. Please use 
latches to hold workers and confirm that a request is queued before triggering 
cancellation or shutdown. Then assert that a fresh evaluation succeeds after 
cancellation and that a caller wakes promptly on shutdown. The restart test did 
catch a reintroduced `active.set(0)`.
   
   _Codex on behalf of @luigidemasi._



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

Review Comment:
   **P3 — Make the lifecycle flag visible to concurrent callers.** `doStart()` 
and `doStop()` write `stopped` under the console monitor. The new early read in 
`doCallJson()` occurs outside that monitor and can reject a request before it 
reaches the synchronized check in `executor()`. Making the flag volatile keeps 
the early check and gives it the required visibility.
   
   ```suggestion
       private volatile boolean stopped;
   ```
   
   _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