This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 6872876be9a5 CAMEL-27777: camel-core - BacklogTracer message history 
stops updating when exchanges from multiple routes interleave (#31128)
6872876be9a5 is described below

commit 6872876be9a58474c52de3d0d23a4e98b0d82238
Author: James Netherton <[email protected]>
AuthorDate: Mon Nov 30 15:59:01 2026 +0000

    CAMEL-27777: camel-core - BacklogTracer message history stops updating when 
exchanges from multiple routes interleave (#31128)
    
    The first event that reached an empty provisional history queue claimed
    it for its exchange, whatever kind of event it was. When that was the
    last event of an exchange already in flight, the exchange was never
    completed and every other exchange was discarded, so the latest message
    history stayed on that exchange forever. A middle event claiming the
    queue gave a history missing the start of the exchange.
    
    Only the start of an exchange may now begin a new history: the first
    event of the route the exchange came from, not the input of a sub-route.
    When the route an exchange came from is not traced (a rest or template
    route the tracer skips, or a route excluded by the trace pattern), the
    first traced event is the input of the next route, and such an event may
    now begin a new history. Breadcrumb append mode is unchanged.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../apache/camel/impl/debugger/BacklogTracer.java  |  39 ++++++++
 .../debugger/DefaultBacklogTracerEventMessage.java |  13 +++
 .../camel/impl/engine/CamelInternalProcessor.java  |   6 ++
 ...BacklogTracerMessageHistoryInterleavedTest.java | 102 +++++++++++++++++++
 ...cklogTracerMessageHistoryUntracedRouteTest.java | 111 +++++++++++++++++++++
 5 files changed, 271 insertions(+)

diff --git 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/BacklogTracer.java
 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/BacklogTracer.java
index c492306469e8..447c6b46a6ce 100644
--- 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/BacklogTracer.java
+++ 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/BacklogTracer.java
@@ -31,6 +31,7 @@ import org.apache.camel.Endpoint;
 import org.apache.camel.Exchange;
 import org.apache.camel.ExchangePropertyKey;
 import org.apache.camel.NamedNode;
+import org.apache.camel.NamedRoute;
 import org.apache.camel.NoSuchLanguageException;
 import org.apache.camel.Predicate;
 import org.apache.camel.Route;
@@ -256,6 +257,12 @@ public class BacklogTracer extends ServiceSupport 
implements org.apache.camel.sp
                         && 
head.getBreadcrumbId().equals(lastCompletedBreadcrumbId)) {
                     appendMode = true;
                 }
+                // only the start of an exchange (not the input of a 
sub-route) may begin a new history: an exchange
+                // already in flight cannot be captured from its start, and if 
its last event claimed the queue then
+                // nothing would ever complete it, so the history would stop 
updating
+                if (head == null && !appendMode && !isExchangeStart(event)) {
+                    match = false;
+                }
                 if (match || appendMode) {
                     boolean added = provisionalHistoryQueue.offer(event);
                     boolean original
@@ -307,6 +314,38 @@ public class BacklogTracer extends ServiceSupport 
implements org.apache.camel.sp
         }
     }
 
+    /**
+     * Whether the event is the start of an exchange: the first event of the 
route the exchange came from, and not the
+     * input of a sub-route it was sent to, unless the tracer does not trace 
the route the exchange came from.
+     */
+    private static boolean isExchangeStart(BacklogTracerEventMessage event) {
+        if (!event.isFirst()) {
+            return false;
+        }
+        return event.getFromRouteId() == null || 
event.getFromRouteId().equals(event.getRouteId())
+                || (event instanceof DefaultBacklogTracerEventMessage dem && 
dem.isFromUntracedRoute());
+    }
+
+    /**
+     * Whether the tracer traces the route with the given id: not a rest or 
template route it skips, and matching the
+     * trace pattern. The trace filter is not checked: it only looks at the 
exchange, which already passed it to be
+     * traced in the current route. A route that cannot be found is considered 
not traced.
+     */
+    public boolean isRouteTraced(String routeId) {
+        Route route = camelContext.getRoute(routeId);
+        if (route == null || !(route.getRoute() instanceof NamedRoute 
definition)) {
+            return false;
+        }
+        if ((definition.isCreatedFromRest() && !traceRests) || 
(definition.isCreatedFromTemplate() && !traceTemplates)) {
+            return false;
+        }
+        if (definition.getInput() == null) {
+            return false;
+        }
+        TracePatternHolder ph = tracePatternHolder;
+        return ph == null || shouldTracePattern(definition.getInput(), 
ph.patterns());
+    }
+
     private void drain(boolean force) {
         if (force) {
             queue.poll();
diff --git 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/DefaultBacklogTracerEventMessage.java
 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/DefaultBacklogTracerEventMessage.java
index cb75685abb6d..eb671e7b15c5 100644
--- 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/DefaultBacklogTracerEventMessage.java
+++ 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/debugger/DefaultBacklogTracerEventMessage.java
@@ -59,6 +59,7 @@ public final class DefaultBacklogTracerEventMessage 
implements BacklogTracerEven
     private String endpointUri;
     private boolean remoteEndpoint;
     private boolean stubEndpoint;
+    private boolean fromUntracedRoute;
     private String endpointServiceUrl;
     private String endpointServiceProtocol;
     private Map<String, String> endpointServiceMetadata;
@@ -302,6 +303,18 @@ public final class DefaultBacklogTracerEventMessage 
implements BacklogTracerEven
         this.stubEndpoint = stubEndpoint;
     }
 
+    /**
+     * Whether the exchange came from a route that the tracer does not trace, 
so this event is the first one traced for
+     * the exchange.
+     */
+    public boolean isFromUntracedRoute() {
+        return fromUntracedRoute;
+    }
+
+    public void setFromUntracedRoute(boolean fromUntracedRoute) {
+        this.fromUntracedRoute = fromUntracedRoute;
+    }
+
     public void setEndpointUri(String endpointUri) {
         this.endpointUri = endpointUri;
         // dirty flag
diff --git 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/CamelInternalProcessor.java
 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/CamelInternalProcessor.java
index 5d224c7093aa..38d53aefdeb9 100644
--- 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/CamelInternalProcessor.java
+++ 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/CamelInternalProcessor.java
@@ -854,6 +854,12 @@ public class CamelInternalProcessor extends 
DelegateAsyncProcessor implements In
                     first.setEndpointServiceProtocol(esl.getServiceProtocol());
                     first.setEndpointServiceMetadata(esl.getServiceMetadata());
                 }
+                // only used by the message history, which begins at the first 
traced route of an exchange: this one
+                // when the route the exchange came from is not traced (such 
as a rest or template route it skips)
+                if (camelContext.isMessageHistory() && fromRouteId != null && 
!fromRouteId.equals(routeId)
+                        && !backlogTracer.isRouteTraced(fromRouteId)) {
+                    first.setFromUntracedRoute(true);
+                }
                 backlogTracer.traceEvent(first);
                 return first;
             }
diff --git 
a/core/camel-management/src/test/java/org/apache/camel/management/BacklogTracerMessageHistoryInterleavedTest.java
 
b/core/camel-management/src/test/java/org/apache/camel/management/BacklogTracerMessageHistoryInterleavedTest.java
new file mode 100644
index 000000000000..3657265d30ce
--- /dev/null
+++ 
b/core/camel-management/src/test/java/org/apache/camel/management/BacklogTracerMessageHistoryInterleavedTest.java
@@ -0,0 +1,102 @@
+/*
+ * 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.management;
+
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.spi.BacklogTracer;
+import org.apache.camel.spi.BacklogTracerEventMessage;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The latest message history must keep updating when exchanges interleave, 
including when an exchange that is already
+ * in flight reaches the end of its route just after another exchange 
completed its history.
+ */
+@DisabledOnOs(OS.AIX)
+public class BacklogTracerMessageHistoryInterleavedTest extends 
ManagementTestSupport {
+
+    private final CountDownLatch firstWaiting = new CountDownLatch(1);
+    private final CountDownLatch releaseFirst = new CountDownLatch(1);
+    private final CountDownLatch secondWaiting = new CountDownLatch(1);
+    private final CountDownLatch releaseSecond = new CountDownLatch(1);
+
+    @Test
+    public void testHistoryUpdatesAfterInterleavedExchanges() throws Exception 
{
+        // The first exchange begins the history, then waits in the middle of 
the route
+        Future<Exchange> first = template.asyncSend("direct:start", exchange 
-> exchange.getMessage().setBody("first"));
+        assertTrue(firstWaiting.await(10, TimeUnit.SECONDS));
+
+        // The second exchange starts while the history belongs to the first 
one, then waits at the end of the route
+        Future<Exchange> second = template.asyncSend("direct:start", exchange 
-> exchange.getMessage().setBody("second"));
+        assertTrue(secondWaiting.await(10, TimeUnit.SECONDS));
+
+        // The first exchange completes the history
+        releaseFirst.countDown();
+        first.get(10, TimeUnit.SECONDS);
+
+        // The next event is the last event of the second exchange, which must 
not begin a new history
+        releaseSecond.countDown();
+        second.get(10, TimeUnit.SECONDS);
+
+        Exchange third = template.send("direct:start", exchange -> 
exchange.getMessage().setBody("third"));
+
+        BacklogTracer tracer = 
context.getCamelContextExtension().getContextPlugin(BacklogTracer.class);
+        List<BacklogTracerEventMessage> events = 
tracer.dumpLatestMessageHistory();
+        assertFalse(events.isEmpty());
+        assertTrue(events.get(0).isFirst());
+        assertTrue(events.get(events.size() - 1).isLast());
+        events.forEach(event -> assertEquals(third.getExchangeId(), 
event.getExchangeId()));
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                context.setUseBreadcrumb(false);
+                context.setBacklogTracing(true);
+                context.setMessageHistory(true);
+
+                from("direct:start").routeId("myRoute")
+                        .process(exchange -> {
+                            if 
("first".equals(exchange.getMessage().getBody())) {
+                                firstWaiting.countDown();
+                                releaseFirst.await(10, TimeUnit.SECONDS);
+                            }
+                        }).id("waitFirst")
+                        .to("mock:result").id("result")
+                        .process(exchange -> {
+                            if 
("second".equals(exchange.getMessage().getBody())) {
+                                secondWaiting.countDown();
+                                releaseSecond.await(10, TimeUnit.SECONDS);
+                            }
+                        }).id("waitSecond");
+            }
+        };
+    }
+}
diff --git 
a/core/camel-management/src/test/java/org/apache/camel/management/BacklogTracerMessageHistoryUntracedRouteTest.java
 
b/core/camel-management/src/test/java/org/apache/camel/management/BacklogTracerMessageHistoryUntracedRouteTest.java
new file mode 100644
index 000000000000..8e1a814f6f9a
--- /dev/null
+++ 
b/core/camel-management/src/test/java/org/apache/camel/management/BacklogTracerMessageHistoryUntracedRouteTest.java
@@ -0,0 +1,111 @@
+/*
+ * 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.management;
+
+import java.util.List;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.rest.DummyRestConsumerFactory;
+import org.apache.camel.spi.BacklogTracer;
+import org.apache.camel.spi.BacklogTracerEventMessage;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The latest message history begins at the first traced route when the 
exchange came from a route that the tracer does
+ * not trace.
+ */
+@DisabledOnOs(OS.AIX)
+public class BacklogTracerMessageHistoryUntracedRouteTest extends 
ManagementTestSupport {
+
+    @Test
+    public void testFromRestRoute() {
+        template.requestBody("seda:get-say-hello", "Hello");
+
+        assertHistoryOfSubRoute();
+    }
+
+    @Test
+    public void testFromTemplateRoute() {
+        template.sendBody("direct:fromTemplate", "Hello");
+
+        assertHistoryOfSubRoute();
+    }
+
+    @Test
+    public void testFromRouteExcludedByPattern() {
+        getTracer().setTracePattern("sub*");
+
+        template.sendBody("direct:excluded", "Hello");
+
+        assertHistoryOfSubRoute();
+    }
+
+    private BacklogTracer getTracer() {
+        return 
context.getCamelContextExtension().getContextPlugin(BacklogTracer.class);
+    }
+
+    private void assertHistoryOfSubRoute() {
+        List<BacklogTracerEventMessage> events = 
getTracer().dumpLatestMessageHistory();
+        assertFalse(events.isEmpty());
+        assertTrue(events.get(0).isFirst());
+        assertEquals("sub", events.get(0).getRouteId());
+        assertTrue(events.get(events.size() - 1).isLast());
+        assertEquals("sub", events.get(events.size() - 1).getRouteId());
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        context.getRegistry().bind("dummy-test", new 
DummyRestConsumerFactory());
+        return context;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                context.setUseBreadcrumb(false);
+                context.setBacklogTracing(true);
+                context.setMessageHistory(true);
+                // rest routes are traced by default
+                context.setBacklogTracingRests(false);
+
+                restConfiguration().host("localhost").inlineRoutes(false);
+                rest("/say/hello").get().to("direct:sub");
+
+                routeTemplate("myTemplate")
+                        .from("direct:fromTemplate")
+                        .to("direct:sub");
+                templatedRoute("myTemplate").routeId("templated");
+
+                from("direct:excluded").routeId("excluded")
+                        .to("direct:sub");
+
+                from("direct:sub").routeId("sub")
+                        .to("mock:result");
+            }
+        };
+    }
+}

Reply via email to