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 b0e081740802 CAMEL-27590: camel-redis - RedisAggregationRepository 
with optimistic=true compares the group with what get() read (#30905)
b0e081740802 is described below

commit b0e081740802e5af54276655b053ab14a50c88d8
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 13:43:25 2026 +0530

    CAMEL-27590: camel-redis - RedisAggregationRepository with optimistic=true 
compares the group with what get() read (#30905)
    
    With optimistic=true, add(key, old, new) and remove(key, exchange)
    compared the value in Redis with the exchange they were given,
    serialized again. In the Aggregate EIP that never matched when a group
    was completed: AggregateProcessor sets CamelAggregatedCorrelationKey on
    the group it read before remove(key, original), and the stored group
    does not have it. So no stored group was ever completed: the completing
    message failed with "Exhausted optimistic locking retry attempts"
    (retried forever with the default retry policy, so the sender hung),
    and a group completed by its completion timeout stayed in Redis and was
    never sent (the failed remove was taken as a timeout that another
    instance handled). An aggregation strategy that changes the old
    exchange and returns it also failed every add after the first message,
    as the old exchange was serialized after the strategy changed it. And
    equal exchanges could serialize differently, as Java serialization
    writes a String instance shared by a header and a property once.
    
    get() now keeps, in optimistic mode, the bytes it read from Redis for
    each group it returns, with the key, in a weak map keyed by the
    exchange it returns (a WeakHashMap: the exchange does not override
    equals(), so an entry is found only for that instance). add and remove
    compare the stored value with those bytes when the exchange is one that
    get() returned for the same key, and with the exchange serialized again
    otherwise (as before). A group changed by another aggregator since it
    was read still fails the compare. As the exchange is not serialized
    again for the compare, the back-reference case is fixed too. With the
    codec option (for example Kryo5Codec, to read the groups stored by
    4.23), get() reads the group as bytes through a second view of the same
    hash (the codec for the fields, ByteArrayCodec for the values, so both
    views address the same field), keeps the bytes, and builds the exchange
    from the value that the codec decodes from them, which nothing else
    references, so a strategy may change the body in place. A codec does
    not always encode a decoded value to the same bytes: Kryo5Codec reads
    a HashSet or HashMap back with another capacity, which changes the
    order of its elements once it has about a dozen of them, and
    SerializationCodec writes the capacity of a HashMap, which the decoded
    map does not keep. add, remove and the script are given the bytes kept,
    so they no longer depend on that. The stored format and the thread-safe
    mode do not change.
    
    The Lua script of the optimistic remove with recovery now writes the
    given exchange to the completed hash, as the thread-safe mode does,
    instead of the stored group, which lacks the correlation key that the
    recover task reads and, for a strategy that changes the old exchange,
    the last message.
    
    Upgrade guide 4.24 entry: groups left in Redis by the bug complete
    after the upgrade (the groups of 4.23 or older with the codec option
    only), and the completed entry is the removed exchange. With a strategy
    that returns the new exchange and useRecovery, the groups now complete,
    and the recover task sends the group without its last message once
    more, as with optimistic=false: the completed entry is kept under the
    id of the group read while the Aggregate EIP confirms the id of the new
    exchange. That needs a change in the Aggregate EIP.
    
    RedisAggregationRepositoryOptimisticTest runs the repository through the
    Aggregate EIP with an in-memory stand-in for the Redis hashes and the
    script, which stores the values encoded by the codec of the hash and
    compares them by their bytes: completion size with both strategy styles,
    with and without recovery, with Kryo5Codec and a strategy that adds to a
    List body in place, with Kryo5Codec and a HashSet body of 20 messages,
    with SerializationCodec, completion timeout, two repositories on the
    same hashes, and at repository level the completed entry, equal values
    that serialize differently, and stale reads that still fail.
    
    Review:
    - comments on the Redisson codec State and on the shared-hashes test
    - remove() serializes the group only for the recoverable storage
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../aggregate/RedisAggregationRepository.java      | 113 +++-
 .../RedisAggregationRepositoryOptimisticTest.java  | 636 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  27 +
 3 files changed, 758 insertions(+), 18 deletions(-)

diff --git 
a/components/camel-redis/src/main/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepository.java
 
b/components/camel-redis/src/main/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepository.java
index 0ddd0d71af1f..1293494c8bc4 100644
--- 
a/components/camel-redis/src/main/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepository.java
+++ 
b/components/camel-redis/src/main/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepository.java
@@ -26,10 +26,12 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.WeakHashMap;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
 
 import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
 import org.apache.camel.CamelContext;
 import org.apache.camel.Exchange;
 import org.apache.camel.RuntimeCamelException;
@@ -52,6 +54,7 @@ import org.redisson.api.TransactionOptions;
 import org.redisson.client.codec.ByteArrayCodec;
 import org.redisson.client.codec.Codec;
 import org.redisson.client.codec.StringCodec;
+import org.redisson.client.handler.State;
 import org.redisson.client.protocol.Encoder;
 import org.redisson.codec.CompositeCodec;
 import org.redisson.config.Config;
@@ -88,6 +91,8 @@ public class RedisAggregationRepository extends ServiceSupport
     private static final int SCAN_COUNT = 100;
 
     private RMap<String, Object> cache;
+    /** The active hash with the values as the bytes stored in Redis, for the 
optimistic compares. */
+    private RMap<String, Object> rawCache;
     private RMap<String, Object> persistedCache;
     private Codec mapCodec;
     /**
@@ -95,21 +100,29 @@ public class RedisAggregationRepository extends 
ServiceSupport
      */
     private final Set<String> unreadableExchangeIds = 
ConcurrentHashMap.newKeySet();
     private boolean shutdownRedisson;
+    /**
+     * Optimistic locking: the groups that {@link #get(CamelContext, String)} 
returned, each with its key and the value
+     * that was read from Redis, to compare the stored group with. A {@link 
WeakHashMap} compares its keys with
+     * {@code equals()}: the keys are the {@link DefaultExchange} instances 
that {@code get} creates, which do not
+     * override it, so an entry is found only for the same exchange instance. 
Weak, so a group that is never updated or
+     * removed does not stay.
+     */
+    private final Map<Exchange, ReadGroup> readGroups = 
Collections.synchronizedMap(new WeakHashMap<>());
+
+    private record ReadGroup(String key, byte[] value) {
+    }
 
     /**
      * Atomic Lua script for optimistic removal with recovery.
      *
      * <p>
-     * Implements compare-and-swap by comparing the current serialized 
exchange in the active map with the expected
-     * serialized holder. If they match, the script writes the holder to the 
recovery map and removes it from the active
-     * map atomically.
+     * Implements compare-and-swap by comparing the current value in the 
active map with the expected value, which is
+     * the value that {@link #get(CamelContext, String)} read. If they match, 
the script writes the given exchange (with
+     * the last aggregated message and the properties the aggregator set) to 
the recovery map and removes the group from
+     * the active map atomically.
      *
      * <p>
-     * Returns 1 on success and 0 if the active exchange does not match the 
expected holder.
-     *
-     * <p>
-     * The comparison uses serialized bytes. Therefore, the serialization must 
produce identical bytes for the same
-     * holder when storing and comparing it.
+     * Returns 1 on success and 0 if the active exchange does not match the 
expected value.
      *
      * <p>
      * The {@code HSET} into the recovery map is intentionally placed before 
the {@code HDEL} from the active map. Redis
@@ -124,7 +137,7 @@ public class RedisAggregationRepository extends 
ServiceSupport
                 return 0
             end
 
-            redis.call('HSET', KEYS[2], ARGV[3], current)
+            redis.call('HSET', KEYS[2], ARGV[3], ARGV[4])
             redis.call('HDEL', KEYS[1], ARGV[1])
 
             return 1
@@ -222,9 +235,9 @@ public class RedisAggregationRepository extends 
ServiceSupport
                 throw new OptimisticLockingException();
             }
         } else {
-            Object oldHolder = marshallHolder(oldExchange);
-            Object newHolder = marshallHolder(newExchange);
-            if (!cache.replace(key, oldHolder, newHolder)) {
+            byte[] oldValue = readValue(key, oldExchange);
+            byte[] newValue = encodeValue(marshallHolder(newExchange));
+            if (!rawCache.replace(key, oldValue, newValue)) {
                 LOG.warn(
                         "Optimistic locking failed for exchange with key {}: 
RMap#replace returned no Exchanges, while it's expected to replace one",
                         key);
@@ -383,9 +396,51 @@ public class RedisAggregationRepository extends 
ServiceSupport
         return maximumRedeliveries;
     }
 
+    /**
+     * Gets the group of the correlation key.
+     * <p>
+     * With optimistic locking, {@link #add(CamelContext, String, Exchange, 
Exchange)} and
+     * {@link #remove(CamelContext, String, Exchange)} compare the stored 
group with the bytes that this method read
+     * from Redis, not with the exchange they are given serialized again: the 
Aggregate EIP sets properties on the group
+     * before it removes it, and an aggregation strategy may change the group 
and return it. With a
+     * {@link #setCodec(Codec) codec} too, the bytes are read as they are 
stored and kept for the compare, and the
+     * exchange is made of the value that the codec decodes from them: a codec 
does not always encode a decoded value to
+     * the same bytes (the order of a {@code HashSet} body can change, for 
example).
+     */
     @Override
     public Exchange get(CamelContext camelContext, String key) {
-        return unmarshallExchange(camelContext, mapName, key, cache.get(key));
+        if (!optimistic) {
+            return unmarshallExchange(camelContext, mapName, key, 
cache.get(key));
+        }
+        // the bytes stored in Redis, to compare with as they are; the 
exchange is made of an object decoded from them,
+        // which nothing else references, so an aggregation strategy may 
change it in place
+        byte[] read = (byte[]) rawCache.get(key);
+        Object value = codec != null && read != null ? decode(read) : read;
+        Exchange exchange = unmarshallExchange(camelContext, mapName, key, 
value);
+        if (exchange != null) {
+            readGroups.put(exchange, new ReadGroup(key, read));
+        }
+        return exchange;
+    }
+
+    /**
+     * The value to compare the stored group with, for an optimistic update or 
remove of the group that the exchange
+     * stands for: the bytes that {@link #get(CamelContext, String)} read for 
this key, or else the exchange as it is
+     * now, encoded as it is stored.
+     */
+    private byte[] readValue(String key, Exchange exchange) {
+        ReadGroup read = readGroups.remove(exchange);
+        if (read != null && read.key().equals(key)) {
+            return read.value();
+        }
+        return encodeValue(marshallHolder(exchange));
+    }
+
+    /**
+     * The value that {@link #marshallHolder(Exchange)} made, as the bytes 
stored in Redis.
+     */
+    private byte[] encodeValue(Object holder) {
+        return codec != null ? encode(mapCodec.getMapValueEncoder(), holder) : 
(byte[]) holder;
     }
 
     /**
@@ -440,8 +495,8 @@ public class RedisAggregationRepository extends 
ServiceSupport
 
     @Override
     public void remove(CamelContext camelContext, String key, Exchange 
exchange) {
-        Object holder = marshallHolder(exchange);
-
+        // the given exchange is serialized only to be stored in the 
recoverable storage: the optimistic compare uses
+        // the bytes that get() read
         if (optimistic) {
             LOG.trace("Removing an exchange with ID {} for key {} in an 
optimistic manner.",
                     exchange.getExchangeId(), key);
@@ -450,6 +505,7 @@ public class RedisAggregationRepository extends 
ServiceSupport
                 LOG.trace("Atomically moving exchange with ID {} for key {} 
into recoverable storage.",
                         exchange.getExchangeId(), key);
 
+                Object holder = marshallHolder(exchange);
                 // the arguments are passed as bytes, encoded as the fields 
and values of the hashes
                 RScript script = redisson.getScript(ByteArrayCodec.INSTANCE);
 
@@ -459,8 +515,9 @@ public class RedisAggregationRepository extends 
ServiceSupport
                         RScript.ReturnType.LONG,
                         List.of(mapName, persistenceMapName),
                         encode(mapCodec.getMapKeyEncoder(), key),
-                        encode(mapCodec.getMapValueEncoder(), holder),
-                        encode(mapCodec.getMapKeyEncoder(), 
exchange.getExchangeId()));
+                        readValue(key, exchange),
+                        encode(mapCodec.getMapKeyEncoder(), 
exchange.getExchangeId()),
+                        encode(mapCodec.getMapValueEncoder(), holder));
 
                 if (result == null || result.longValue() != 1L) {
                     LOG.warn(
@@ -474,7 +531,7 @@ public class RedisAggregationRepository extends 
ServiceSupport
                         exchange.getExchangeId(), key);
 
             } else {
-                if (!cache.remove(key, holder)) {
+                if (!rawCache.remove(key, readValue(key, exchange))) {
                     LOG.warn(
                             "Optimistic locking failed for exchange with key 
{}: RMap#remove removed no Exchanges, while it's expected to remove one.",
                             key);
@@ -488,6 +545,7 @@ public class RedisAggregationRepository extends 
ServiceSupport
         } else {
             if (useRecovery) {
                 LOG.trace("Removing an exchange with ID {} for key {} in a 
thread-safe manner.", exchange.getExchangeId(), key);
+                Object holder = marshallHolder(exchange);
                 TransactionOptions tOpts = TransactionOptions.defaults();
                 RTransaction transaction = redisson.createTransaction(tOpts);
 
@@ -586,6 +644,9 @@ public class RedisAggregationRepository extends 
ServiceSupport
         unreadableExchangeIds.clear();
         mapCodec = codec != null ? codec : CODEC;
         cache = redisson.getMap(mapName, mapCodec);
+        rawCache = codec != null
+                ? redisson.getMap(mapName, new CompositeCodec(codec, 
ByteArrayCodec.INSTANCE, ByteArrayCodec.INSTANCE))
+                : cache;
         if (codec == null) {
             warnUnreadableEntries(cache, mapName);
         }
@@ -655,8 +716,24 @@ public class RedisAggregationRepository extends 
ServiceSupport
         }
     }
 
+    /**
+     * Decodes the value with the decoder of the codec of the hashes, as it is 
read from Redis.
+     */
+    private Object decode(byte[] bytes) {
+        ByteBuf buf = Unpooled.wrappedBuffer(bytes);
+        try {
+            // State is a parameter of the Decoder.decode(ByteBuf, State) 
codec contract of Redisson
+            return mapCodec.getMapValueDecoder().decode(buf, new State());
+        } catch (IOException e) {
+            throw new RuntimeCamelException("Cannot decode the value read from 
Redis", e);
+        } finally {
+            buf.release();
+        }
+    }
+
     @Override
     protected void doStop() throws Exception {
+        readGroups.clear();
         if (redisson != null && shutdownRedisson) {
             redisson.shutdown();
             redisson = null;
diff --git 
a/components/camel-redis/src/test/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepositoryOptimisticTest.java
 
b/components/camel-redis/src/test/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepositoryOptimisticTest.java
new file mode 100644
index 000000000000..9d9c483ceab2
--- /dev/null
+++ 
b/components/camel-redis/src/test/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepositoryOptimisticTest.java
@@ -0,0 +1,636 @@
+/*
+ * 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.component.redis.processor.aggregate;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import org.apache.camel.AggregationStrategy;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.processor.aggregate.OptimisticLockRetryPolicy;
+import 
org.apache.camel.spi.OptimisticLockingAggregationRepository.OptimisticLockingException;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.redisson.api.RMap;
+import org.redisson.api.RScript;
+import org.redisson.api.RedissonClient;
+import org.redisson.client.codec.ByteArrayCodec;
+import org.redisson.client.codec.Codec;
+import org.redisson.client.handler.State;
+import org.redisson.codec.Kryo5Codec;
+import org.redisson.codec.SerializationCodec;
+import org.redisson.config.Config;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The repository with optimistic locking through the Aggregate EIP, with an 
in-memory stand-in for the Redis hashes
+ * that stores the values encoded by the codec of the hash and compares them 
by their bytes, as Redis does.
+ */
+public class RedisAggregationRepositoryOptimisticTest extends CamelTestSupport 
{
+
+    /** Changes the old exchange and returns it, as the Aggregate EIP 
documentation shows. */
+    private static final AggregationStrategy CHANGE_OLD = (oldExchange, 
newExchange) -> {
+        if (oldExchange == null) {
+            return newExchange;
+        }
+        oldExchange.getIn().setBody(join(oldExchange, newExchange));
+        return oldExchange;
+    };
+
+    /** Leaves the old exchange as it is and returns the new exchange. */
+    private static final AggregationStrategy RETURN_NEW = (oldExchange, 
newExchange) -> {
+        if (oldExchange != null) {
+            newExchange.getIn().setBody(join(oldExchange, newExchange));
+        }
+        return newExchange;
+    };
+
+    /** Keeps a list body and adds the new message to it in place. */
+    @SuppressWarnings("unchecked")
+    private static final AggregationStrategy ADD_TO_LIST = (oldExchange, 
newExchange) -> {
+        if (oldExchange == null) {
+            List<String> list = new ArrayList<>();
+            list.add(newExchange.getIn().getBody(String.class));
+            newExchange.getIn().setBody(list);
+            return newExchange;
+        }
+        
oldExchange.getIn().getBody(List.class).add(newExchange.getIn().getBody(String.class));
+        return oldExchange;
+    };
+
+    /** Keeps a HashSet body and adds the new message to it in place. */
+    @SuppressWarnings("unchecked")
+    private static final AggregationStrategy ADD_TO_SET = (oldExchange, 
newExchange) -> {
+        if (oldExchange == null) {
+            Set<String> set = new HashSet<>();
+            set.add(newExchange.getIn().getBody(String.class));
+            newExchange.getIn().setBody(set);
+            return newExchange;
+        }
+        
oldExchange.getIn().getBody(Set.class).add(newExchange.getIn().getBody(String.class));
+        return oldExchange;
+    };
+
+    // the Redis hashes, guarded by themselves as Redis runs one command or 
script at a time
+    private final Map<String, Map<String, Object>> redis = new HashMap<>();
+    // the codec of each hash, to read the fields that the script is given
+    private final Map<String, Codec> codecs = new HashMap<>();
+    private RedissonClient redisson;
+    private final List<RedisAggregationRepository> repositories = new 
ArrayList<>();
+
+    @BeforeEach
+    void createRedis() {
+        redisson = mock(RedissonClient.class);
+        when(redisson.<String, Object> getMap(anyString(), any(Codec.class)))
+                .thenAnswer(i -> {
+                    synchronized (redis) {
+                        codecs.put(i.getArgument(0), i.getArgument(1));
+                    }
+                    return inMemoryMap(hash(i.getArgument(0)), 
i.getArgument(1));
+                });
+        Config config = mock(Config.class);
+        when(redisson.getConfig()).thenReturn(config);
+        RScript script = mock(RScript.class);
+        when(redisson.getScript(ByteArrayCodec.INSTANCE)).thenReturn(script);
+        when(script.eval(any(RScript.Mode.class), anyString(), 
any(RScript.ReturnType.class), anyList(),
+                any(Object[].class)))
+                .thenAnswer(i -> {
+                    Object[] args = i.getArguments();
+                    Object[] values = args.length == 5 && args[4] instanceof 
Object[] array
+                            ? array : Arrays.copyOfRange(args, 4, args.length);
+                    return optimisticRemoveScript(i.getArgument(1), 
i.getArgument(3), values);
+                });
+    }
+
+    @AfterEach
+    void stopRepositories() {
+        repositories.forEach(RedisAggregationRepository::stop);
+    }
+
+    @Test
+    void testCompletionSizeWithStrategyThatChangesOldExchange() throws 
Exception {
+        assertGroupsComplete("changeOld", CHANGE_OLD, true);
+    }
+
+    @Test
+    void testCompletionSizeWithStrategyThatChangesOldExchangeWithoutRecovery() 
throws Exception {
+        assertGroupsComplete("changeOldNoRecovery", CHANGE_OLD, false);
+    }
+
+    @Test
+    void testCompletionSizeWithStrategyThatReturnsNewExchangeWithoutRecovery() 
throws Exception {
+        assertGroupsComplete("returnNewNoRecovery", RETURN_NEW, false);
+    }
+
+    @Test
+    void testCompletionSizeWithCodecAndStrategyThatChangesTheBodyInPlace() 
throws Exception {
+        // the exchange that get() returns must not share the body with the 
value it read and compares with
+        String name = "codecInPlace";
+        RedisAggregationRepository repository = repository(name, true, new 
Kryo5Codec());
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:" + name)
+                        .aggregate(header("id"), 
ADD_TO_LIST).aggregationRepository(repository)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        .completionSize(3)
+                        .to("mock:" + name);
+            }
+        });
+        MockEndpoint mock = getMockEndpoint("mock:" + name);
+        mock.expectedBodiesReceivedInAnyOrder(List.of("a", "b", "c"), 
List.of("d", "e", "f"));
+
+        for (String body : List.of("a", "d", "b", "e", "c", "f")) {
+            template.sendBodyAndHeader("direct:" + name, body, "id", 
"abc".contains(body) ? "K1" : "K2");
+        }
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        assertTrue(hash(name).isEmpty(), "groups left: " + 
hash(name).keySet());
+        await().atMost(10, TimeUnit.SECONDS).until(() -> hash(name + 
"-completed").isEmpty());
+    }
+
+    @Test
+    void testCompletionSizeWithKryoCodecAndHashSetBody() throws Exception {
+        // Kryo reads a HashSet back with another capacity, so the decoded 
group encoded again has its elements in
+        // another order once the set has a dozen of them: the compare must 
use the bytes that were read
+        completeOneGroupWithCodec("kryoHashSet", new Kryo5Codec(), ADD_TO_SET, 
20);
+    }
+
+    @Test
+    void testCompletionSizeWithSerializationCodec() throws Exception {
+        // Java serialization of a HashMap writes its capacity, which the 
decoded group does not keep, so the decoded
+        // group encoded again differs from the stored bytes from the second 
message on
+        completeOneGroupWithCodec("serializationCodec", new 
SerializationCodec(), ADD_TO_LIST, 3);
+    }
+
+    @Test
+    void testCompletionTimeout() throws Exception {
+        RedisAggregationRepository repository = repository("timeout", true);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:timeout")
+                        .aggregate(header("id"), 
CHANGE_OLD).aggregationRepository(repository)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        
.completionTimeout(200).completionTimeoutCheckerInterval(50)
+                        .to("mock:timeout");
+            }
+        });
+        MockEndpoint mock = getMockEndpoint("mock:timeout");
+        mock.expectedBodiesReceivedInAnyOrder("a", "b+c");
+
+        template.sendBodyAndHeader("direct:timeout", "a", "id", "K1");
+        template.sendBodyAndHeader("direct:timeout", "b", "id", "K2");
+        template.sendBodyAndHeader("direct:timeout", "c", "id", "K2");
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        assertTrue(hash("timeout").isEmpty(), "groups left: " + 
hash("timeout").keySet());
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
hash("timeout-completed").isEmpty());
+    }
+
+    /**
+     * Two aggregators with their own repository on the same hashes, as two 
Camel instances on the same Redis: 20 keys
+     * sent from 4 threads, so that the two repositories update the same 
groups at the same time.
+     */
+    @Test
+    void testTwoRepositoriesSharingTheHashes() throws Exception {
+        RedisAggregationRepository first = repository("shared", true);
+        RedisAggregationRepository second = repository("shared", true);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:first")
+                        .aggregate(header("id"), 
CHANGE_OLD).aggregationRepository(first)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        .completionSize(2).to("mock:shared");
+                from("direct:second")
+                        .aggregate(header("id"), 
CHANGE_OLD).aggregationRepository(second)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        .completionSize(2).to("mock:shared");
+            }
+        });
+        int groups = 20;
+        MockEndpoint mock = getMockEndpoint("mock:shared");
+        mock.expectedMessageCount(groups);
+
+        ExecutorService executor = Executors.newFixedThreadPool(4);
+        try {
+            List<Future<?>> sends = new ArrayList<>();
+            for (int i = 0; i < groups; i++) {
+                String key = "K" + i;
+                sends.add(executor.submit(() -> 
template.sendBodyAndHeader("direct:first", "a", "id", key)));
+                sends.add(executor.submit(() -> 
template.sendBodyAndHeader("direct:second", "b", "id", key)));
+            }
+            for (Future<?> send : sends) {
+                send.get(30, TimeUnit.SECONDS);
+            }
+        } finally {
+            executor.shutdownNow();
+        }
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        Set<String> bodies = new HashSet<>();
+        for (Exchange exchange : mock.getReceivedExchanges()) {
+            String body = exchange.getIn().getBody(String.class);
+            assertTrue(body.equals("a+b") || body.equals("b+a"), body);
+            bodies.add(exchange.getIn().getHeader("id", String.class));
+        }
+        assertEquals(groups, bodies.size());
+        assertTrue(hash("shared").isEmpty(), "groups left: " + 
hash("shared").keySet());
+    }
+
+    @Test
+    void testRemoveOfGroupWithCorrelationKeySetByAggregator() {
+        RedisAggregationRepository repository = repository("removeRead", true);
+        repository.add(context, "K", null, exchange("a", "K"));
+
+        Exchange group = repository.get(context, "K");
+        // as the Aggregate EIP does before it removes a completed group
+        group.setProperty(Exchange.AGGREGATED_CORRELATION_KEY, "K");
+        repository.remove(context, "K", group);
+
+        assertTrue(hash("removeRead").isEmpty());
+        assertEquals(Set.of(group.getExchangeId()), 
hash("removeRead-completed").keySet());
+    }
+
+    @Test
+    void testCompletedEntryIsTheGivenExchange() throws Exception {
+        RedisAggregationRepository repository = repository("completedEntry", 
true);
+        repository.add(context, "K", null, exchange("a", "K"));
+
+        Exchange group = repository.get(context, "K");
+        group.getIn().setBody("a+b");
+        group.setProperty(Exchange.AGGREGATED_CORRELATION_KEY, "K");
+        repository.remove(context, "K", group);
+
+        // the completed entry, which the recovery sends after a crash, has 
the last message and the correlation key
+        Exchange recovered = repository.recover(context, 
group.getExchangeId());
+        assertEquals("a+b", recovered.getIn().getBody());
+        assertEquals("K", 
recovered.getProperty(Exchange.AGGREGATED_CORRELATION_KEY));
+    }
+
+    @Test
+    void testRemoveWhenEqualValuesSerializeDifferently() {
+        RedisAggregationRepository repository = repository("sameValue", false);
+        // the header and the property are the same String instance, which 
Java serialization writes once
+        String key = "K";
+        Exchange first = exchange("a", key);
+        first.setProperty(Exchange.AGGREGATED_CORRELATION_KEY, key);
+        repository.add(context, key, null, first);
+
+        Exchange group = repository.get(context, key);
+        // an equal value, but another instance than the header
+        group.setProperty(Exchange.AGGREGATED_CORRELATION_KEY, new 
String(key));
+        repository.remove(context, key, group);
+
+        assertTrue(hash("sameValue").isEmpty());
+    }
+
+    @Test
+    void testRemoveWithoutRecoveryDoesNotSerializeTheGroup() {
+        AtomicInteger marshalled = new AtomicInteger();
+        RedisAggregationRepository repository = new 
RedisAggregationRepository() {
+            @Override
+            protected Object marshallHolder(Exchange exchange) {
+                marshalled.incrementAndGet();
+                return super.marshallHolder(exchange);
+            }
+        };
+        repository.setRedisson(redisson);
+        repository.setMapName("noSerialize");
+        repository.setOptimistic(true);
+        repository.setUseRecovery(false);
+        repository.start();
+        repositories.add(repository);
+        repository.add(context, "K", null, exchange("a", "K"));
+
+        Exchange group = repository.get(context, "K");
+        group.setProperty(Exchange.AGGREGATED_CORRELATION_KEY, "K");
+        marshalled.set(0);
+        repository.remove(context, "K", group);
+
+        // the remove compares with the bytes that get() read, and there is no 
recoverable storage to write to
+        assertEquals(0, marshalled.get(), "the group was serialized by the 
remove");
+        assertTrue(hash("noSerialize").isEmpty());
+    }
+
+    @Test
+    void testStaleReadFailsToUpdateOrRemove() {
+        RedisAggregationRepository repository = repository("stale", true);
+        repository.add(context, "K", null, exchange("a", "K"));
+
+        Exchange stale = repository.get(context, "K");
+        Exchange staleForRemove = repository.get(context, "K");
+        Exchange current = repository.get(context, "K");
+        current.getIn().setBody("a+b");
+        repository.add(context, "K", current, current);
+
+        Exchange update = exchange("a+c", "K");
+        assertThrows(OptimisticLockingException.class, () -> 
repository.add(context, "K", stale, update));
+        assertThrows(OptimisticLockingException.class, () -> 
repository.remove(context, "K", staleForRemove));
+        assertEquals("a+b", repository.get(context, "K").getIn().getBody());
+        assertTrue(hash("stale-completed").isEmpty());
+    }
+
+    @Test
+    void testExchangeNotReadByGetIsComparedAsItIs() {
+        RedisAggregationRepository repository = repository("notRead", false);
+        Exchange first = exchange("a", "K");
+        repository.add(context, "K", null, first);
+
+        // an exchange that the repository did not return, compared as it is 
now (as before)
+        repository.add(context, "K", first, exchange("a+b", "K"));
+        assertEquals("a+b", repository.get(context, "K").getIn().getBody());
+        Exchange changed = exchange("a+c", "K");
+        assertThrows(OptimisticLockingException.class, () -> 
repository.add(context, "K", changed, changed));
+    }
+
+    private void assertGroupsComplete(String name, AggregationStrategy 
strategy, boolean useRecovery)
+            throws Exception {
+        RedisAggregationRepository repository = repository(name, useRecovery);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:" + name)
+                        .aggregate(header("id"), 
strategy).aggregationRepository(repository)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        .completionSize(2)
+                        .to("mock:" + name);
+            }
+        });
+        MockEndpoint mock = getMockEndpoint("mock:" + name);
+        mock.expectedBodiesReceivedInAnyOrder("a+b", "c+d");
+
+        template.sendBodyAndHeader("direct:" + name, "a", "id", "K1");
+        template.sendBodyAndHeader("direct:" + name, "c", "id", "K2");
+        template.sendBodyAndHeader("direct:" + name, "b", "id", "K1");
+        template.sendBodyAndHeader("direct:" + name, "d", "id", "K2");
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        assertTrue(hash(name).isEmpty(), "groups left: " + 
hash(name).keySet());
+        if (useRecovery) {
+            // the completed exchanges are confirmed once they are done
+            await().atMost(10, TimeUnit.SECONDS).until(() -> hash(name + 
"-completed").isEmpty());
+        }
+    }
+
+    private RedisAggregationRepository repository(String mapName, boolean 
useRecovery) {
+        return repository(mapName, useRecovery, null);
+    }
+
+    private RedisAggregationRepository repository(String mapName, boolean 
useRecovery, Codec codec) {
+        RedisAggregationRepository repository = new 
RedisAggregationRepository();
+        repository.setRedisson(redisson);
+        repository.setCodec(codec);
+        repository.setMapName(mapName);
+        repository.setOptimistic(true);
+        repository.setUseRecovery(useRecovery);
+        repository.setRecoveryInterval(60_000);
+        repository.start();
+        repositories.add(repository);
+        return repository;
+    }
+
+    /**
+     * Aggregates one group of the given size with the codec, and checks that 
it completes with all the messages.
+     */
+    private void completeOneGroupWithCodec(String name, Codec codec, 
AggregationStrategy strategy, int size)
+            throws Exception {
+        RedisAggregationRepository repository = repository(name, true, codec);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:" + name)
+                        .aggregate(header("id"), 
strategy).aggregationRepository(repository)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        .completionSize(size)
+                        .to("mock:" + name);
+            }
+        });
+        MockEndpoint mock = getMockEndpoint("mock:" + name);
+        mock.expectedMessageCount(1);
+
+        Set<String> messages = new HashSet<>();
+        for (int i = 0; i < size; i++) {
+            // spread hash codes, so that the elements of a HashSet are 
ordered by the capacity of the set
+            String body = "message-" + i + "-" + Integer.toHexString(i * 
0x9E3779B1);
+            messages.add(body);
+            template.sendBodyAndHeader("direct:" + name, body, "id", "K");
+        }
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        Collection<?> body = 
mock.getReceivedExchanges().get(0).getIn().getBody(Collection.class);
+        assertEquals(size, body.size());
+        assertEquals(messages, new HashSet<>(body));
+        assertTrue(hash(name).isEmpty(), "groups left: " + 
hash(name).keySet());
+        await().atMost(10, TimeUnit.SECONDS).until(() -> hash(name + 
"-completed").isEmpty());
+    }
+
+    private static OptimisticLockRetryPolicy retryPolicy() {
+        // bounded, so a compare that never matches fails the exchange instead 
of retrying forever
+        OptimisticLockRetryPolicy policy = new OptimisticLockRetryPolicy();
+        policy.setMaximumRetries(20);
+        policy.setRetryDelay(1);
+        policy.setMaximumRetryDelay(10);
+        return policy;
+    }
+
+    private Exchange exchange(String body, String key) {
+        Exchange exchange = new DefaultExchange(context);
+        exchange.getIn().setBody(body);
+        exchange.getIn().setHeader("id", key);
+        return exchange;
+    }
+
+    private static String join(Exchange oldExchange, Exchange newExchange) {
+        return oldExchange.getIn().getBody(String.class) + "+" + 
newExchange.getIn().getBody(String.class);
+    }
+
+    private Map<String, Object> hash(String name) {
+        synchronized (redis) {
+            return redis.computeIfAbsent(name, n -> new HashMap<>());
+        }
+    }
+
+    /**
+     * The script of the repository: compares the value of the field in the 
first hash with the expected value, and if
+     * they are equal, sets the value that the script names (the stored value 
or an argument) under the exchange id in
+     * the second hash, and deletes the field.
+     */
+    private Long optimisticRemoveScript(String script, List<Object> keys, 
Object[] values) {
+        Matcher set = Pattern.compile("HSET', KEYS\\[2\\], ARGV\\[3\\], 
(current|ARGV\\[(\\d)\\])").matcher(script);
+        assertTrue(set.find(), script);
+        Map<String, Object> active = hash((String) keys.get(0));
+        Map<String, Object> completed = hash((String) keys.get(1));
+        synchronized (redis) {
+            String field = (String) decodeField(codecs.get((String) 
keys.get(0)), values[0]);
+            Object current = active.get(field);
+            if (!same(current, values[1])) {
+                return 0L;
+            }
+            Object value = set.group(2) == null ? current : 
values[Integer.parseInt(set.group(2)) - 1];
+            completed.put((String) decodeField(codecs.get((String) 
keys.get(1)), values[2]), value);
+            active.remove(field);
+            return 1L;
+        }
+    }
+
+    /**
+     * A hash that stores the values encoded by the value encoder of the 
codec, and gives back the values decoded, as
+     * Redisson and Redis do.
+     */
+    @SuppressWarnings("unchecked")
+    private RMap<String, Object> inMemoryMap(Map<String, Object> store, Codec 
codec) {
+        RMap<String, Object> map = mock(RMap.class);
+        when(map.get(any())).thenAnswer(i -> {
+            synchronized (redis) {
+                return decode(codec, store.get(i.<String> getArgument(0)));
+            }
+        });
+        when(map.put(anyString(), any())).thenAnswer(i -> {
+            synchronized (redis) {
+                return decode(codec, store.put(i.getArgument(0), encode(codec, 
i.getArgument(1))));
+            }
+        });
+        when(map.putIfAbsent(anyString(), any())).thenAnswer(i -> {
+            synchronized (redis) {
+                return decode(codec, store.putIfAbsent(i.getArgument(0), 
encode(codec, i.getArgument(1))));
+            }
+        });
+        when(map.replace(anyString(), any(), any())).thenAnswer(i -> {
+            synchronized (redis) {
+                if (!same(store.get(i.<String> getArgument(0)), encode(codec, 
i.getArgument(1)))) {
+                    return false;
+                }
+                store.put(i.getArgument(0), encode(codec, i.getArgument(2)));
+                return true;
+            }
+        });
+        when(map.remove(anyString(), any())).thenAnswer(i -> {
+            synchronized (redis) {
+                if (!same(store.get(i.<String> getArgument(0)), encode(codec, 
i.getArgument(1)))) {
+                    return false;
+                }
+                store.remove(i.<String> getArgument(0));
+                return true;
+            }
+        });
+        when(map.remove(anyString())).thenAnswer(i -> {
+            synchronized (redis) {
+                return decode(codec, store.remove(i.<String> getArgument(0)));
+            }
+        });
+        when(map.keySet()).thenAnswer(i -> {
+            synchronized (redis) {
+                return Set.copyOf(store.keySet());
+            }
+        });
+        when(map.entrySet(anyInt())).thenAnswer(i -> {
+            synchronized (redis) {
+                Map<String, Object> decoded = new HashMap<>();
+                store.forEach((field, value) -> decoded.put(field, 
decode(codec, value)));
+                return Set.copyOf(decoded.entrySet());
+            }
+        });
+        when(map.size()).thenAnswer(i -> {
+            synchronized (redis) {
+                return store.size();
+            }
+        });
+        return map;
+    }
+
+    /**
+     * Whether the stored value and the expected value are equal, as Redis 
compares them: by their bytes.
+     */
+    private static boolean same(Object stored, Object expected) {
+        return stored instanceof byte[] a && expected instanceof byte[] b && 
Arrays.equals(a, b);
+    }
+
+    private static byte[] encode(Codec codec, Object value) {
+        ByteBuf buf = null;
+        try {
+            buf = codec.getMapValueEncoder().encode(value);
+            byte[] bytes = new byte[buf.readableBytes()];
+            buf.getBytes(buf.readerIndex(), bytes);
+            return bytes;
+        } catch (IOException e) {
+            throw new UncheckedIOException(e);
+        } finally {
+            if (buf != null) {
+                buf.release();
+            }
+        }
+    }
+
+    private static Object decodeField(Codec codec, Object field) {
+        ByteBuf buf = Unpooled.wrappedBuffer((byte[]) field);
+        try {
+            return codec.getMapKeyDecoder().decode(buf, new State());
+        } catch (IOException e) {
+            throw new UncheckedIOException(e);
+        } finally {
+            buf.release();
+        }
+    }
+
+    private static Object decode(Codec codec, Object stored) {
+        if (stored == null) {
+            return null;
+        }
+        ByteBuf buf = Unpooled.wrappedBuffer((byte[]) stored);
+        try {
+            return codec.getMapValueDecoder().decode(buf, new State());
+        } catch (IOException e) {
+            throw new UncheckedIOException(e);
+        } finally {
+            buf.release();
+        }
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 05f97dfc39a2..6920d3b417a6 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -9746,6 +9746,33 @@ older versions, and the `deserializationFilter` option 
and the WARN at startup d
 stored by the older version have completed and been recovered, remove the 
`codec` option to switch to the Java
 serialization read through the deserialization filter.
 
+=== camel-redis - RedisAggregationRepository with optimistic=true completes 
the groups
+
+With `optimistic=true` (and `optimisticLocking` on the Aggregate EIP), 
`RedisAggregationRepository` now compares the
+group stored in Redis with the bytes it read from Redis (with the `codec` 
option too), instead of with the exchange
+serialized again. Before, the remove that completes a group never matched, 
because the Aggregate EIP sets the
+correlation key property on the group before it removes it: the message that 
completed a group failed with "Exhausted
+optimistic locking retry attempts" (or was tried again forever with the 
default retry policy), and a group completed
+by its completion timeout stayed in Redis without being sent. An aggregation 
strategy that changes the old exchange
+and returns it could not add a second message to a group either.
+
+Groups that Camel 4.23 or older left in Redis this way are read only with the 
`codec` option set to the codec they
+were stored with, by default `new org.redisson.codec.Kryo5Codec()` (see the 
previous section). They are then completed
+after the upgrade by the next message of their correlation key, or, when the 
group records its completion timeout, by
+the completion timeout once the route has started again.
+
+With `useRecovery` (the default), the completed exchange that the repository 
keeps until it is confirmed is now the
+exchange that the Aggregate EIP removes, with the correlation key, as with 
`optimistic=false`. With an aggregation
+strategy that returns the old exchange, it has the last message. Before, it 
was the group as stored before the last
+message, without the correlation key. This fix does not change the format in 
which the exchanges are stored (the
+change of format in 4.24 is the one of the previous section).
+
+With an aggregation strategy that returns the new exchange and `useRecovery`, 
the groups now complete, and the recover
+task then sends each group once more, without its last message and marked as 
redelivered, as with `optimistic=false`:
+the completed exchange is kept under the exchange id of the group as read from 
Redis, while the Aggregate EIP confirms
+the exchange id of the new exchange. The Aggregate EIP logs a WARN for such a 
strategy with a recoverable repository.
+Use a strategy that returns the old exchange. Fixing this needs a change in 
the Aggregate EIP.
+
 === camel-spring-ws - the reply of a consumer, and File and stream bodies of 
the producer
 
 A `spring-ws` consumer route that sets the body to `null` in a processor, such 
as with

Reply via email to