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 c681ed95e910 CAMEL-27589: camel-core - Aggregate with optimistic
locking no longer sends a second aggregate for a closed key (#30906)
c681ed95e910 is described below
commit c681ed95e910bb9ea0eac7c6927bdf10f4f8305b
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 13:43:35 2026 +0530
CAMEL-27589: camel-core - Aggregate with optimistic locking no longer sends
a second aggregate for a closed key (#30906)
With closeCorrelationKeyOnCompletion and optimisticLocking, CAMEL-27297
covered an exchange that reads the repository
while a completion removes the group. Three other orders were still open.
An exchange that read "no group" could add
a new group after another exchange completed the key on its own (its group
never stored, so no repository call), or
after a group stored later was completed and removed (the key has no group
again). That group lived on for the closed
key and was sent later as a second aggregate. And two exchanges that both
read "no group" could both complete on their
own, and both be sent.
An exchange that added a new group now checks the closing marks and the
closed keys after the add. If the key is
closing or closed, it removes its group again while the group still holds
only its exchange (a recoverable repository
confirms it at once, as for a discarded group), and is tried again or
rejected. A completion of a group that was never
stored is done by one exchange of a key at a time, marks the key as closing
as well, and then checks that the key has
no group, no other closing completion, and is not closed; otherwise it is
tried again. Either the new group sees the
key closing, or the completion sees the new group. Nothing changes without
optimisticLocking or without
closeCorrelationKeyOnCompletion.
Tests: AggregateOptimisticLockingClosedKeyTest.
Review:
- log when the new group of a closed key cannot be removed, Javadoc on what
the check guarantees
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../processor/aggregate/AggregateProcessor.java | 96 ++++++-
.../AggregateOptimisticLockingClosedKeyTest.java | 280 +++++++++++++++++++++
2 files changed, 373 insertions(+), 3 deletions(-)
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
index abf6973c8835..3f595e2473b0 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
@@ -137,9 +137,12 @@ public class AggregateProcessor extends
BaseProcessorSupport
private ExceptionHandler exceptionHandler;
private AggregationRepository aggregationRepository;
private Map<String, String> closedCorrelationKeys;
- // with optimistic locking: the correlation keys of the groups that a
completion is removing from the repository,
- // and that are put in closedCorrelationKeys once removed (correlation key
-> number of such completions)
+ // with optimistic locking: the correlation keys that a completion is
closing (it removes the group from the
+ // repository, or checks that the key has no group), until they are put in
closedCorrelationKeys (correlation key ->
+ // number of such completions)
private final Map<String, Integer> closingCorrelationKeys = new
ConcurrentHashMap<>();
+ // with optimistic locking: the correlation keys that an exchange is
closing on its own (its group was never stored)
+ private final Set<String> closingAloneCorrelationKeys =
ConcurrentHashMap.newKeySet();
private final Set<String> batchConsumerCorrelationKeys = new
ConcurrentSkipListSet<>();
private final Set<String> inProgressCompleteExchanges =
ConcurrentHashMap.newKeySet();
private final WaitableInteger inProgressCount = new WaitableInteger();
@@ -643,9 +646,11 @@ public class AggregateProcessor extends
BaseProcessorSupport
newExchange.removeProperty(ExchangePropertyKey.AGGREGATED_CORRELATION_KEY);
}
+ boolean preCompleted = false;
if (preCompletion && complete != null) {
// need to pre complete the current group before we aggregate
doAggregationComplete(complete, list, key, originalExchange,
oldExchange, false);
+ preCompleted = true;
// as we complete the current group eager, we should indicate the
new group is not complete
complete = null;
// and clear old/original exchange as we start on a new group
@@ -721,6 +726,9 @@ public class AggregateProcessor extends BaseProcessorSupport
}
// only need to update aggregation repository if we are not
complete
doAggregationRepositoryAdd(newExchange.getContext(), key,
originalExchange, answer);
+ if (originalExchange == null && !preCompleted && optimisticLocking
&& closedCorrelationKeys != null) {
+ checkClosedCorrelationKeyAfterNewGroup(key, answer,
newExchange);
+ }
if (spooled != null && isKeepingReferences()) {
// the group keeps the references until it is completed (see
doOnCompletion)
groupSpooledStreamCaches.computeIfAbsent(key, k -> new
SpooledStreamCaches()).add(spooled.take());
@@ -763,6 +771,71 @@ public class AggregateProcessor extends
BaseProcessorSupport
}
}
+ /**
+ * With optimistic locking, checks the correlation key again after a new
group was added to the repository.
+ * <p>
+ * The read of the repository may be older than the add: another exchange
may have completed the key in between,
+ * either on its own (its group was never stored) or by removing a group
that was stored after the read. The add
+ * then succeeds, as the key has no group, and would start a group for the
closed key. A completion marks the key as
+ * closing before it removes the group, or before it checks that the key
has no group (see
+ * {@link #onCompletion(String, Exchange, Exchange, boolean, boolean)}),
so either this check sees the key as
+ * closing or closed, or that completion sees this group and does not
complete on its own. If the key is closing or
+ * closed, the new group is removed again and the exchange is tried again
or rejected. If the group can no longer be
+ * removed, it was changed or completed by another thread, with this
exchange in it, so the add stands.
+ * <p>
+ * This only guarantees at most one aggregate per closed key, not
progress: an exchange that completes on its own
+ * and an exchange that adds a new group can both back off in the same
round (each sees the other), and their next
+ * attempts sort it out by timing.
+ */
+ private void checkClosedCorrelationKeyAfterNewGroup(String key, Exchange
group, Exchange exchange)
+ throws ClosedCorrelationKeyException {
+ boolean closing = closingCorrelationKeys.containsKey(key);
+ if (!closing && !closedCorrelationKeys.containsKey(key)) {
+ return;
+ }
+ // read the group again, as a repository may need what it reads to
remove it (such as a version), and remove
+ // it only while it is still the group of only this exchange
+ Exchange current = aggregationRepository.get(exchange.getContext(),
key);
+ if (current == null ||
!current.getExchangeId().equals(group.getExchangeId())
+ || current.getProperty(ExchangePropertyKey.AGGREGATED_SIZE, 0,
Integer.class) != 1) {
+ return;
+ }
+ // as for a discarded group: a recoverable repository moves the
exchange to its completed store when it is
+ // removed, so it is marked as being completed until it is confirmed,
and the recover task does not send it
+ boolean recoverable = isRecoverableRepository();
+ String exchangeId = current.getExchangeId();
+ if (recoverable) {
+ markCompleting(exchangeId);
+ }
+ try {
+
current.setProperty(ExchangePropertyKey.AGGREGATED_CORRELATION_KEY, key);
+ try {
+ aggregationRepository.remove(exchange.getContext(), key,
current);
+ } catch
(OptimisticLockingAggregationRepository.OptimisticLockingException e) {
+ // usually another thread changed or completed the group, with
this exchange in it. A repository whose
+ // remove cannot match a group it read again fails here too,
and then this check does not protect the key
+ LOG.debug("The new group with correlation key: {} was added
while the key was closed or being closed,"
+ + " and cannot be removed again (the repository
reports it as changed): the add stands",
+ key);
+ return;
+ }
+ if (recoverable) {
+ confirmDiscarded(current);
+ } else {
+ aggregationRepository.confirm(exchange.getContext(),
exchangeId);
+ }
+ } finally {
+ if (recoverable) {
+ unmarkCompleting(exchangeId);
+ }
+ }
+ LOG.trace("The new group with correlation key: {} was added while the
key was closed or being closed", key);
+ if (closing) {
+ throw new
OptimisticLockingAggregationRepository.OptimisticLockingException();
+ }
+ throw new ClosedCorrelationKeyException(key, exchange);
+ }
+
protected void doAggregationComplete(
String complete, List<Exchange> list, String key,
Exchange originalExchange, Exchange answer, boolean
aggregateFailed) {
@@ -973,18 +1046,35 @@ public class AggregateProcessor extends
BaseProcessorSupport
// until the key is closed (or the remove failed), see
checkClosedCorrelationKey. The mark is kept apart from
// the closed keys, so a remove that fails (the group was changed or
completed by another thread) never reopens
// a key that another completion has closed, and a bounded (LRU)
closed keys cache cannot evict it.
- final boolean closing = original != null && optimisticLocking &&
closedCorrelationKeys != null;
+ final boolean closing = optimisticLocking && closedCorrelationKeys !=
null;
+ // a group that was never stored is completed by this exchange on its
own, with no repository call to fail if
+ // the key changed since the read, so at most one exchange of a key at
a time does this
+ final boolean alone = closing && original == null;
+ if (alone && !closingAloneCorrelationKeys.add(key)) {
+ throw new
OptimisticLockingAggregationRepository.OptimisticLockingException();
+ }
if (closing) {
closingCorrelationKeys.merge(key, 1, Integer::sum);
}
Exchange answer = null;
try {
+ if (alone && (aggregationRepository.get(aggregated.getContext(),
key) != null
+ || closingCorrelationKeys.getOrDefault(key, 0) > 1 ||
closedCorrelationKeys.containsKey(key))) {
+ // since this exchange read the repository, another exchange
has started a group for the key (see
+ // checkClosedCorrelationKeyAfterNewGroup), or another
completion is closing or has closed the key: try
+ // again, to aggregate with that group or to be rejected,
instead of closing the key on its own
+ LOG.trace("The correlation key: {} has changed since it was
read, will try again", key);
+ throw new
OptimisticLockingAggregationRepository.OptimisticLockingException();
+ }
answer = doOnCompletion(key, original, aggregated, fromTimeout,
aggregateFailed);
return answer;
} finally {
if (closing) {
closingCorrelationKeys.computeIfPresent(key, (k, count) ->
count > 1 ? count - 1 : null);
}
+ if (alone) {
+ closingAloneCorrelationKeys.remove(key);
+ }
if (completing && answer == null) {
// not removed, or not to be sent
unmarkCompleting(aggregated.getExchangeId());
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateOptimisticLockingClosedKeyTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateOptimisticLockingClosedKeyTest.java
index dab3a4a8ea5e..8ee684bb5d14 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateOptimisticLockingClosedKeyTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateOptimisticLockingClosedKeyTest.java
@@ -17,6 +17,7 @@
package org.apache.camel.processor.aggregator;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@@ -36,11 +37,13 @@ import
org.apache.camel.processor.aggregate.AggregateProcessor;
import org.apache.camel.processor.aggregate.ClosedCorrelationKeyException;
import org.apache.camel.processor.aggregate.MemoryAggregationRepository;
import org.apache.camel.processor.aggregate.OptimisticLockRetryPolicy;
+import org.apache.camel.spi.RecoverableAggregationRepository;
import org.apache.camel.support.DefaultExchange;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -57,6 +60,7 @@ class AggregateOptimisticLockingClosedKeyTest extends
ContextTestSupport {
private final Map<String, AtomicInteger> attempts = new
ConcurrentHashMap<>();
private volatile AggregateProcessor processor;
private volatile Thread producerC;
+ private volatile Runnable onAggregation;
private ExecutorService executorService;
@Override
@@ -256,6 +260,273 @@ class AggregateOptimisticLockingClosedKeyTest extends
ContextTestSupport {
ap.stop();
}
+ @Test
+ void testNewGroupAfterExchangeCompletedAloneIsRejected() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("B");
+ mock.setAssertPeriod(200);
+
+ MemoryAggregationRepository repository = new
MemoryAggregationRepository(true) {
+ @Override
+ public Exchange add(CamelContext camelContext, String key,
Exchange oldExchange, Exchange newExchange) {
+ if (firstCallOn("producer-D", "add")) {
+ // D has read no group and passed the closed correlation
key checks: B completes on its own (its
+ // group is never stored) and closes the key before D adds
its new group
+ latch("dBeforeAdd").countDown();
+ await(latch("bDone"));
+ }
+ return super.add(camelContext, key, oldExchange, newExchange);
+ }
+ };
+
+ AggregateProcessor ap = createProcessor(repository, true);
+ Exchange d = createExchange("D");
+ Thread producerD = new Thread(() -> process(ap, d), "producer-D");
+ producerD.start();
+ await(latch("dBeforeAdd"));
+ Exchange b = createExchange("B");
+ ap.process(b);
+ latch("bDone").countDown();
+ join(producerD);
+
+ assertNull(b.getException());
+ assertRejected(ap, d);
+ assertMockEndpointsSatisfied();
+ ap.stop();
+ }
+
+ @Test
+ void testNewGroupAfterStoredGroupWasCompletedIsRejected() throws Exception
{
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("A+B");
+ mock.setAssertPeriod(200);
+
+ MemoryAggregationRepository repository = new
MemoryAggregationRepository(true) {
+ @Override
+ public Exchange add(CamelContext camelContext, String key,
Exchange oldExchange, Exchange newExchange) {
+ if (firstCallOn("producer-D", "add")) {
+ // D has read no group and passed the closed correlation
key checks: the group [A] is stored and
+ // completed by B before D adds its new group, so the key
has no group again
+ latch("dBeforeAdd").countDown();
+ await(latch("bDone"));
+ }
+ return super.add(camelContext, key, oldExchange, newExchange);
+ }
+ };
+
+ AggregateProcessor ap = createProcessor(repository, false);
+ Exchange d = createExchange("D");
+ Thread producerD = new Thread(() -> process(ap, d), "producer-D");
+ producerD.start();
+ await(latch("dBeforeAdd"));
+ ap.process(createExchange("A"));
+ Exchange b = createExchange("B");
+ ap.process(b);
+ latch("bDone").countDown();
+ join(producerD);
+
+ assertNull(b.getException());
+ assertRejected(ap, d);
+ assertMockEndpointsSatisfied();
+ ap.stop();
+ }
+
+ @Test
+ void testNewGroupRemovedAgainIsConfirmedWithRecoverableRepository() throws
Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("B");
+ mock.setAssertPeriod(200);
+
+ RecoverableMemoryRepository repository = new
RecoverableMemoryRepository() {
+ @Override
+ public Exchange add(CamelContext camelContext, String key,
Exchange oldExchange, Exchange newExchange) {
+ if (firstCallOn("producer-D", "add")) {
+ latch("dBeforeAdd").countDown();
+ await(latch("bDone"));
+ }
+ return super.add(camelContext, key, oldExchange, newExchange);
+ }
+ };
+
+ AggregateProcessor ap = createProcessor(repository, true);
+ Exchange d = createExchange("D");
+ Thread producerD = new Thread(() -> process(ap, d), "producer-D");
+ producerD.start();
+ await(latch("dBeforeAdd"));
+ ap.process(createExchange("B"));
+ latch("bDone").countDown();
+ join(producerD);
+
+ assertRejected(ap, d);
+ // the group [D] went to the completed store when it was removed
again, and was confirmed, so the recover task
+ // has nothing to send
+ assertEquals(1, repository.removed.get());
+ assertTrue(repository.scan(context).isEmpty(), "Not confirmed: " +
repository.scan(context));
+ assertMockEndpointsSatisfied();
+ ap.stop();
+ }
+
+ @Test
+ void testExchangeThatWouldCompleteAloneAfterKeyClosedIsRejected() throws
Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("YB");
+ mock.setAssertPeriod(200);
+
+ onAggregation = () -> {
+ if (firstCallOn("producer-X", "aggregate")) {
+ // X has read no group and passed the closed correlation key
checks, and completes on its own: Y
+ // completes on its own and closes the key before X does
+ latch("xRead").countDown();
+ await(latch("yDone"));
+ }
+ };
+
+ AggregateProcessor ap = createProcessor(new
MemoryAggregationRepository(true), true);
+ Exchange x = createExchange("XB");
+ Thread producerX = new Thread(() -> process(ap, x), "producer-X");
+ producerX.start();
+ await(latch("xRead"));
+ Exchange y = createExchange("YB");
+ ap.process(y);
+ latch("yDone").countDown();
+ join(producerX);
+
+ assertNull(y.getException());
+ assertRejected(ap, x);
+ assertMockEndpointsSatisfied();
+ ap.stop();
+ }
+
+ @Test
+ void testExchangeThatWouldCompleteAloneJoinsNewGroup() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("D+B");
+ mock.setAssertPeriod(200);
+
+ MemoryAggregationRepository repository = new
MemoryAggregationRepository(true) {
+ @Override
+ public Exchange get(CamelContext camelContext, String key) {
+ Exchange answer = super.get(camelContext, key);
+ if (firstCallOn("producer-B", "get")) {
+ // B has read no group, and would complete on its own: D
adds a new group before B completes
+ latch("bRead").countDown();
+ await(latch("dAdded"));
+ }
+ return answer;
+ }
+
+ @Override
+ public Exchange add(CamelContext camelContext, String key,
Exchange oldExchange, Exchange newExchange) {
+ Exchange answer = super.add(camelContext, key, oldExchange,
newExchange);
+ if (firstCallOn("producer-D", "add")) {
+ latch("dAdded").countDown();
+ await(latch("bDone"));
+ }
+ return answer;
+ }
+ };
+
+ AggregateProcessor ap = createProcessor(repository, true);
+ Exchange b = createExchange("B");
+ Thread producerB = new Thread(() -> {
+ process(ap, b);
+ latch("bDone").countDown();
+ }, "producer-B");
+ producerB.start();
+ await(latch("bRead"));
+ Exchange d = createExchange("D");
+ Thread producerD = new Thread(() -> process(ap, d), "producer-D");
+ producerD.start();
+ join(producerB);
+ join(producerD);
+
+ // B sees the group [D] when it closes the key, and completes [D, B]
instead of [B] on its own
+ assertNull(b.getException());
+ assertNull(d.getException());
+ assertMockEndpointsSatisfied();
+ Exchange e = createExchange("E");
+ ap.process(e);
+ assertRejected(ap, e);
+ ap.stop();
+ }
+
+ /**
+ * A memory repository with optimistic locking that moves a removed
exchange to a completed store, as a recoverable
+ * repository does, until it is confirmed.
+ */
+ private static class RecoverableMemoryRepository extends
MemoryAggregationRepository
+ implements RecoverableAggregationRepository {
+
+ private final Map<String, Exchange> completed = new
ConcurrentHashMap<>();
+ private final AtomicInteger removed = new AtomicInteger();
+
+ RecoverableMemoryRepository() {
+ super(true);
+ }
+
+ @Override
+ public void remove(CamelContext camelContext, String key, Exchange
exchange) {
+ super.remove(camelContext, key, exchange);
+ completed.put(exchange.getExchangeId(), exchange);
+ removed.incrementAndGet();
+ }
+
+ @Override
+ public void confirm(CamelContext camelContext, String exchangeId) {
+ completed.remove(exchangeId);
+ }
+
+ @Override
+ public Set<String> scan(CamelContext camelContext) {
+ return Set.copyOf(completed.keySet());
+ }
+
+ @Override
+ public Exchange recover(CamelContext camelContext, String exchangeId) {
+ return completed.get(exchangeId);
+ }
+
+ @Override
+ public void setRecoveryInterval(long interval, TimeUnit timeUnit) {
+ }
+
+ @Override
+ public void setRecoveryInterval(long interval) {
+ }
+
+ @Override
+ public long getRecoveryInterval() {
+ return 60000;
+ }
+
+ @Override
+ public void setUseRecovery(boolean useRecovery) {
+ }
+
+ @Override
+ public boolean isUseRecovery() {
+ return true;
+ }
+
+ @Override
+ public void setDeadLetterUri(String deadLetterUri) {
+ }
+
+ @Override
+ public String getDeadLetterUri() {
+ return null;
+ }
+
+ @Override
+ public void setMaximumRedeliveries(int maximumRedeliveries) {
+ }
+
+ @Override
+ public int getMaximumRedeliveries() {
+ return 0;
+ }
+ }
+
private AggregateProcessor createProcessor(MemoryAggregationRepository
repository, boolean completeOnB)
throws Exception {
AsyncProcessor done = new
SendProcessor(context.getEndpoint("mock:result"));
@@ -280,6 +551,15 @@ class AggregateOptimisticLockingClosedKeyTest extends
ContextTestSupport {
}
return super.doProcess(exchange, key, callback, sync);
}
+
+ @Override
+ protected Exchange onAggregation(Exchange oldExchange, Exchange
newExchange) {
+ Runnable hook = onAggregation;
+ if (hook != null) {
+ hook.run();
+ }
+ return super.onAggregation(oldExchange, newExchange);
+ }
};
processor = ap;
if (completeOnB) {