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


##########
core/camel-support/src/main/java/org/apache/camel/support/cluster/RebalancingCamelClusterService.java:
##########
@@ -47,11 +48,15 @@ public class RebalancingCamelClusterService extends 
ServiceSupport implements Ca
 
     private static final Logger LOG = 
LoggerFactory.getLogger(RebalancingCamelClusterService.class);
 
-    protected ScheduledExecutorService serializedExecutor;
+    // set to null by doStop: a pass that runs on an executor that is no 
longer this one does not schedule the next pass
+    protected volatile ScheduledExecutorService serializedExecutor;
     protected CamelPreemptiveClusterService delegate;
     protected CamelContext camelContext;
     protected final long periodMillis;
 
+    // whether the previous pass failed (only used by the passes, one at a 
time)
+    private boolean previousPassFailed;

Review Comment:
   ⚠️ **Data race on `previousPassFailed`**: this field is written by the 
`doStart()` caller thread (line `previousPassFailed = false` in `doStart`) and 
read/written by the executor thread in `reconcileAndReschedule`. Without 
`volatile`, the write in `doStart` may never be visible to the executor thread, 
leaving it seeing a stale `true` from a prior run.
   
   ```suggestion
       private volatile boolean previousPassFailed;
   ```



##########
core/camel-support/src/main/java/org/apache/camel/support/cluster/RebalancingCamelClusterService.java:
##########
@@ -104,13 +114,40 @@ public void setDelegate(CamelPreemptiveClusterService 
delegate) {
         this.delegate = delegate;
     }
 
+    /**
+     * Runs a rebalancing pass, and schedules the next one on the same 
executor while it is the executor of this
+     * service, also when the pass fails.
+     */
+    private void reconcileAndReschedule(ScheduledExecutorService executor) {
+        try {
+            reconcile();
+            previousPassFailed = false;
+        } catch (Throwable e) {

Review Comment:
   ⚠️ **`catch (Throwable e)` without rethrowing `Error`**: catching 
`Throwable` swallows `VirtualMachineError` subclasses (`OutOfMemoryError`, 
`StackOverflowError`) that the JVM cannot safely recover from. These should be 
rethrown immediately:
   
   ```suggestion
           } catch (Error e) {
               throw e;
           } catch (Throwable e) {
   ```
   
   Or alternatively rethrow inside the catch block when `e instanceof Error`.



##########
core/camel-support/src/main/java/org/apache/camel/support/cluster/RebalancingCamelClusterService.java:
##########
@@ -104,13 +114,40 @@ public void setDelegate(CamelPreemptiveClusterService 
delegate) {
         this.delegate = delegate;
     }
 
+    /**
+     * Runs a rebalancing pass, and schedules the next one on the same 
executor while it is the executor of this
+     * service, also when the pass fails.
+     */
+    private void reconcileAndReschedule(ScheduledExecutorService executor) {
+        try {
+            reconcile();
+            previousPassFailed = false;
+        } catch (Throwable e) {
+            if (previousPassFailed) {
+                LOG.debug("Error while rebalancing the partitions (will try 
again in {} ms)", periodMillis, e);
+            } else {
+                LOG.warn("Error while rebalancing the partitions (will try 
again in {} ms): {}", periodMillis,
+                        e.toString());

Review Comment:
   💡 **`e.toString()` loses the stack trace**: SLF4J only attaches the full 
stack trace when the last argument is a `Throwable` instance. Passing 
`e.toString()` converts it to a plain `String`, so WARN logs in production will 
only show the exception message — not where it was thrown. The `LOG.debug` on 
the next line captures the trace, but `DEBUG` is typically disabled in 
production.
   
   Consider using the standard pattern instead:
   
   ```suggestion
                           LOG.warn("Error while rebalancing the partitions 
(will try again in {} ms)", periodMillis, e);
   ```
   
   Then remove the redundant `LOG.debug` on the next line, since the stack 
trace will now appear in the WARN log directly.



##########
core/camel-core/src/test/java/org/apache/camel/cluster/RebalancingClusterServiceLoopTest.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.cluster;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.cluster.AbstractCamelClusterService;
+import org.apache.camel.support.cluster.AbstractCamelClusterView;
+import org.apache.camel.support.cluster.RebalancingCamelClusterService;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The passes of the rebalancing cluster service form one chain: a failing 
pass does not end it, and a stop and start of
+ * the service does not leave the chain of the previous start running next to 
the new one.
+ */
+class RebalancingClusterServiceLoopTest {
+
+    private static final long PERIOD_MILLIS = 200;
+
+    private CamelContext context;
+    private TestClusterService delegate;
+    private CountingRebalancingClusterService service;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        context = new DefaultCamelContext();
+        delegate = new TestClusterService("node-1");
+        service = new CountingRebalancingClusterService(delegate);
+        context.addService(service);
+    }
+
+    @AfterEach
+    void tearDown() {
+        context.stop();
+    }
+
+    @Test
+    void failingPassDoesNotEndRebalancing() throws Exception {
+        context.start();
+        delegate.getView("my-ns");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= 2);
+
+        delegate.failures.set(1);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
delegate.failures.get() == 0);
+        int passes = service.passes.get();
+
+        // the next passes run, and they still rebalance: a disabled partition 
of the only member is opened
+        TestClusterView view = delegate.view("my-ns");
+        view.setDisabled(true);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= passes + 3 && !view.isDisabled());
+    }
+
+    @Test
+    void restartDoesNotAddChainOfPasses() throws Exception {
+        context.start();
+        delegate.getView("my-ns");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> service.passes.get() 
>= 2);
+
+        for (int i = 0; i < 3; i++) {
+            service.stop();
+            Thread stopped = service.lastThread;
+            service.threads.clear();
+            service.start();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
service.threads.size() >= 3);
+            // no pass starts on the executor of the previous start once the 
service is stopped
+            assertTrue(service.threads.stream().noneMatch(t -> t == stopped),
+                    "A pass ran on the executor of the previous start after 
the stop");
+        }
+
+        // one chain: at most one pass per period (fewer on a busy machine), 
and a few more for the window edges
+        int before = service.passes.get();
+        long start = System.nanoTime();
+        await().during(2, TimeUnit.SECONDS).atMost(10, 
TimeUnit.SECONDS).until(() -> service.passes.get() - before
+                                                                               
      <= TimeUnit.NANOSECONDS.toMillis(
+                                                                               
              System.nanoTime() - start)
+                                                                               
         / PERIOD_MILLIS + 3);
+        assertEquals(1, service.maxConcurrent.get(), "Passes ran at the same 
time");

Review Comment:
   ⚠️ **Potentially flaky assertion**: `shutdownNow()` interrupts scheduled 
tasks but does not await termination of already-running ones. After 
`service.stop()` + `service.start()`, a reconcile task from the old executor 
may still be executing concurrently with the first reconcile from the new 
executor, causing `maxConcurrent` to transiently reach 2.
   
   Consider adding `awaitTermination` after `shutdownNow` in `doStop`, or 
accept that `maxConcurrent` may be 2 during the overlap window and weaken the 
assertion to `assertTrue(service.maxConcurrent.get() <= 2, ...)`.



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