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


##########
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();

Review Comment:
   **P2 — Make the queue-removal assertion depend on removal.** I disabled 
`tpe.remove(r)` and this test still passed. One cancelled task occupies only 
one of the two queue entries, and this line releases the worker before the test 
has observed task 3 entering the queue. Keep the worker held and verify that 
the cancelled future has left the actual queue. To check slot release as well, 
wait until the fresh request is visibly queued before releasing task 1.
   
   _Codex on behalf of @luigidemasi._



##########
components/camel-ai/camel-semantic/src/main/java/org/apache/camel/semantic/SemanticEvaluateConsole.java:
##########
@@ -125,13 +153,37 @@ 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();
+            task = exec.submit(() -> {
+                if (System.nanoTime() > deadline || 
!claimed.compareAndSet(false, true)) {
+                    return null;

Review Comment:
   **P2 — Return a timeout response when the worker finds the deadline 
expired.** This `return null` completes the future normally. If the caller has 
already entered timed `get()` and observes completion before it processes its 
own timeout, JSON receives `null` and text mode throws `NullPointerException` 
in `doCallJson(options).toString()`. I delayed worker entry to the deadline for 
100 calls. I saw 24 null JSON responses and 20 text exceptions, with zero 
expert invocations. The same check produced neither failure on `44557543`. 
Please route worker-side expiry through the same timeout response and audit 
outcome as caller-side expiry. Both formats should return an evaluation failure.
   
   _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