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 b8e8ebbbf8c2 CAMEL-27317: camel-kafka - a lost or revoked partition no
longer leaves its offset in the OffsetCache (#30568)
b8e8ebbbf8c2 is described below
commit b8e8ebbbf8c298b48a131bdc8d678554a75aaf21
Author: allthingssecurity <[email protected]>
AuthorDate: Sun Nov 22 19:07:01 2026 +0530
CAMEL-27317: camel-kafka - a lost or revoked partition no longer leaves its
offset in the OffsetCache (#30568)
The Sync, Async and CommitToOffset commit managers keep the last processed
offset of a partition in an OffsetCache
until it is committed. The rebalance listeners did not override
onPartitionsLost, so Kafka's default called
onPartitionsRevoked and committed a partition that another member owned
already; that commit fails, and the entry
stayed (with an offsetRepository the stale offset was even written). A
revoke whose commit failed kept the entry too.
When the partition came back after another member had committed further,
and was revoked again (or breakOnFirstError
committed it) before a record updated the entry, the stale offset was
committed and the committed offset went back.
Also, the callback of an older async commit removed the entry whatever
offset it held by then.
New default method CommitManager.discardRecordedOffset forgets the recorded
offset of a partition. The Classic and
Resume rebalance listeners forget the offsets of lost partitions without
committing, and the offsets of revoked
partitions after their commit, whether it succeeded or not. OffsetCache
removes an entry after a commit only if the
committed offset covers it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../kafka/consumer/AsyncCommitManager.java | 6 +
.../component/kafka/consumer/CommitManager.java | 12 +
.../kafka/consumer/CommitToOffsetManager.java | 5 +
.../component/kafka/consumer/OffsetCache.java | 5 +-
.../kafka/consumer/SyncCommitManager.java | 5 +
.../support/classic/ClassicRebalanceListener.java | 26 ++-
.../support/resume/ResumeRebalanceListener.java | 26 ++-
.../kafka/consumer/CommitManagerRebalanceTest.java | 253 +++++++++++++++++++++
8 files changed, 327 insertions(+), 11 deletions(-)
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/AsyncCommitManager.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/AsyncCommitManager.java
index 109e16ec0045..77bfcbe87455 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/AsyncCommitManager.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/AsyncCommitManager.java
@@ -137,6 +137,12 @@ public class AsyncCommitManager extends
AbstractCommitManager {
offsetCache.recordOffset(partition, partitionLastOffset);
}
+ @Override
+ public void discardRecordedOffset(TopicPartition partition) {
+ requestedOffsets.remove(partition);
+ offsetCache.remove(partition);
+ }
+
private void postCommitCallback(Map<TopicPartition, OffsetAndMetadata>
committed, Exception exception) {
if (exception == null) {
if (offsetRepository != null) {
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitManager.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitManager.java
index af5017698282..e4d220ada6c7 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitManager.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitManager.java
@@ -53,6 +53,18 @@ public interface CommitManager {
*/
void recordOffset(TopicPartition partition, long partitionLastOffset);
+ /**
+ * Forgets the offset recorded for the given partition without committing
it. Called when the partition is revoked
+ * (after its commit, whether the commit succeeded or not) or lost: the
consumer no longer owns the partition, and
+ * an offset kept for it could be committed after the partition is
assigned to the consumer again, which would move
+ * back the offset that another consumer committed in the meantime.
+ *
+ * @param partition the partition that is no longer assigned to the
consumer
+ */
+ default void discardRecordedOffset(TopicPartition partition) {
+ // NO-OP
+ }
+
/**
* Records the last processed offset and commits it, for an asynchronous
manual commit. A commit manager that
* commits asynchronously leaves the commit to the consumer thread (see
{@link #commitRequestedOffsets()}), so this
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitToOffsetManager.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitToOffsetManager.java
index e9e663d54a30..1140c1b95c22 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitToOffsetManager.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/CommitToOffsetManager.java
@@ -63,4 +63,9 @@ public class CommitToOffsetManager extends
AbstractCommitManager {
offsetCache.recordOffset(partition, partitionLastOffset);
}
+
+ @Override
+ public void discardRecordedOffset(TopicPartition partition) {
+ offsetCache.remove(partition);
+ }
}
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/OffsetCache.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/OffsetCache.java
index e1efd2d26ab7..c267896de3f2 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/OffsetCache.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/OffsetCache.java
@@ -47,7 +47,10 @@ final class OffsetCache {
offsetAndMetadata.offset(),
topicPartition.topic(), topicPartition.partition());
- lastProcessedOffset.remove(topicPartition);
+ // an earlier commit can complete after a newer offset was recorded
(the callback of an async commit runs in a
+ // later poll): keep the newer offset, which is not committed yet
+ lastProcessedOffset.computeIfPresent(topicPartition,
+ (partition, lastOffset) -> lastOffset <
offsetAndMetadata.offset() ? null : lastOffset);
}
public void remove(TopicPartition partition) {
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/SyncCommitManager.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/SyncCommitManager.java
index 3d2e3d2a6e15..af9a624bba8a 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/SyncCommitManager.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/SyncCommitManager.java
@@ -85,4 +85,9 @@ public class SyncCommitManager extends AbstractCommitManager {
public void recordOffset(TopicPartition partition, long
partitionLastOffset) {
offsetCache.recordOffset(partition, partitionLastOffset);
}
+
+ @Override
+ public void discardRecordedOffset(TopicPartition partition) {
+ offsetCache.remove(partition);
+ }
}
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/classic/ClassicRebalanceListener.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/classic/ClassicRebalanceListener.java
index b73ef5bea83f..1782db9f9da4 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/classic/ClassicRebalanceListener.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/classic/ClassicRebalanceListener.java
@@ -47,13 +47,29 @@ public class ClassicRebalanceListener implements
ConsumerRebalanceListener {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
- for (TopicPartition partition : partitions) {
- LOG.debug("onPartitionsRevoked: {} from {}", threadId,
partition.topic());
+ try {
+ for (TopicPartition partition : partitions) {
+ LOG.debug("onPartitionsRevoked: {} from {}", threadId,
partition.topic());
- // only commit offsets if the component has control
- if (!configuration.isAutoCommitEnable()) {
- commitManager.commit(partition);
+ // only commit offsets if the component has control
+ if (!configuration.isAutoCommitEnable()) {
+ commitManager.commit(partition);
+ }
}
+ } finally {
+ // the partitions are no longer owned: an offset that was not
committed (the commit failed) must not be
+ // committed after a partition is assigned to this consumer again
+ partitions.forEach(commitManager::discardRecordedOffset);
+ }
+ }
+
+ @Override
+ public void onPartitionsLost(Collection<TopicPartition> partitions) {
+ // the partitions are owned by other consumers already: a commit would
fail (this consumer is no longer in the
+ // group generation) or move back what the new owner committed, so the
recorded offsets are only forgotten
+ for (TopicPartition partition : partitions) {
+ LOG.debug("onPartitionsLost: {} from {}", threadId,
partition.topic());
+ commitManager.discardRecordedOffset(partition);
}
}
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/resume/ResumeRebalanceListener.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/resume/ResumeRebalanceListener.java
index e32d6c5a2993..d06cf20ee905 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/resume/ResumeRebalanceListener.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/resume/ResumeRebalanceListener.java
@@ -48,13 +48,29 @@ public class ResumeRebalanceListener implements
ConsumerRebalanceListener {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
- for (TopicPartition partition : partitions) {
- LOG.debug("onPartitionsRevoked: {} from {}", threadId,
partition.topic());
+ try {
+ for (TopicPartition partition : partitions) {
+ LOG.debug("onPartitionsRevoked: {} from {}", threadId,
partition.topic());
- // only commit offsets if the component has control
- if (!configuration.isAutoCommitEnable()) {
- commitManager.commit(partition);
+ // only commit offsets if the component has control
+ if (!configuration.isAutoCommitEnable()) {
+ commitManager.commit(partition);
+ }
}
+ } finally {
+ // the partitions are no longer owned: an offset that was not
committed (the commit failed) must not be
+ // committed after a partition is assigned to this consumer again
+ partitions.forEach(commitManager::discardRecordedOffset);
+ }
+ }
+
+ @Override
+ public void onPartitionsLost(Collection<TopicPartition> partitions) {
+ // the partitions are owned by other consumers already: a commit would
fail (this consumer is no longer in the
+ // group generation) or move back what the new owner committed, so the
recorded offsets are only forgotten
+ for (TopicPartition partition : partitions) {
+ LOG.debug("onPartitionsLost: {} from {}", threadId,
partition.topic());
+ commitManager.discardRecordedOffset(partition);
}
}
diff --git
a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/CommitManagerRebalanceTest.java
b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/CommitManagerRebalanceTest.java
new file mode 100644
index 000000000000..abf48cf3d475
--- /dev/null
+++
b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/CommitManagerRebalanceTest.java
@@ -0,0 +1,253 @@
+/*
+ * 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.kafka.consumer;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.camel.component.kafka.KafkaConfiguration;
+import org.apache.camel.component.kafka.KafkaConsumer;
+import org.apache.camel.component.kafka.KafkaEndpoint;
+import
org.apache.camel.component.kafka.consumer.support.classic.ClassicRebalanceListener;
+import org.apache.camel.support.processor.state.MemoryStateRepository;
+import org.apache.kafka.clients.consumer.CommitFailedException;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.MockConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.consumer.OffsetCommitCallback;
+import org.apache.kafka.clients.consumer.RetriableCommitFailedException;
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The offsets that a commit manager records for a partition must not outlive
the ownership of the partition: an offset
+ * kept after the partition was lost, or after its commit failed on a revoke,
is committed when the partition comes back
+ * to the consumer, which moves back the offset that another consumer
committed in the meantime. An earlier commit must
+ * also not make the commit manager forget a newer offset.
+ */
+class CommitManagerRebalanceTest {
+
+ private static final TopicPartition P0 = new TopicPartition("orders", 0);
+
+ private final GroupMockConsumer consumer = new GroupMockConsumer();
+ private final KafkaConfiguration configuration = new KafkaConfiguration();
+ private final List<RuntimeException> pollErrors = new ArrayList<>();
+ private CommitManager commitManager;
+ private ClassicRebalanceListener listener;
+
+ @Test
+ void testLostPartitionIsNotCommittedSync() {
+ setup(false);
+ lostPartitionIsNotCommitted();
+ }
+
+ @Test
+ void testLostPartitionIsNotCommittedAsync() {
+ setup(true);
+ lostPartitionIsNotCommitted();
+ }
+
+ private void lostPartitionIsNotCommitted() {
+ // the records up to offset 4 are processed, and the consumer is then
evicted from the group (it exceeded
+ // max.poll.interval.ms): its next poll reports the partition as lost,
and its commits are refused
+ commitManager.recordOffset(P0, 4);
+ consumer.commitFailure = new CommitFailedException();
+ rebalance(() -> listener.onPartitionsLost(List.of(P0)));
+ consumer.commitFailure = null;
+
+ partitionComesBackAfterAnotherConsumerCommitted(10);
+ assertEquals(10L, consumer.groupOffsets.get(P0), "the offset committed
by the other consumer must be kept");
+ assertEquals(0, consumer.commitRequests, "a lost partition must not be
committed");
+ }
+
+ @Test
+ void testRevokeWithFailedCommitForgetsTheOffsetSync() {
+ setup(false);
+ revokeWithFailedCommitForgetsTheOffset(new TimeoutException("Simulated
commit timeout"));
+ }
+
+ @Test
+ void testRevokeWithFailedCommitForgetsTheOffsetAsync() {
+ setup(true);
+ revokeWithFailedCommitForgetsTheOffset(new
RetriableCommitFailedException("Simulated commit failure"));
+ }
+
+ private void revokeWithFailedCommitForgetsTheOffset(RuntimeException
failure) {
+ commitManager.recordOffset(P0, 4);
+ consumer.commitFailure = failure;
+ rebalance(() -> listener.onPartitionsRevoked(List.of(P0)));
+ consumer.commitFailure = null;
+ assertEquals(1, consumer.commitRequests);
+
+ partitionComesBackAfterAnotherConsumerCommitted(10);
+ assertEquals(10L, consumer.groupOffsets.get(P0), "the offset committed
by the other consumer must be kept");
+ }
+
+ @Test
+ void testEarlierCommitKeepsNewerOffsetAsync() {
+ setup(true);
+ // a batch up to offset 4 is committed, the callback runs in a later
call of the consumer
+ commitManager.recordOffset(P0, 4);
+ commitManager.commit(P0);
+ // the next batch up to offset 9: its commit runs the callback of the
first one, and then fails
+ commitManager.recordOffset(P0, 9);
+ consumer.commitFailure = new RetriableCommitFailedException("Simulated
commit failure");
+ commitManager.commit(P0);
+ consumer.commitFailure = null;
+ consumer.poll(Duration.ZERO);
+ assertEquals(5L, consumer.groupOffsets.get(P0));
+
+ // the revoke commits the offset that is not committed yet
+ rebalance(() -> listener.onPartitionsRevoked(List.of(P0)));
+ consumer.poll(Duration.ZERO);
+ assertEquals(10L, consumer.groupOffsets.get(P0), "the revoke must
commit the records up to offset 9");
+ }
+
+ @Test
+ void testRevokeCommitsTheRecordedOffset() {
+ setup(false);
+ commitManager.recordOffset(P0, 4);
+ rebalance(() -> listener.onPartitionsRevoked(List.of(P0)));
+ assertEquals(5L, consumer.groupOffsets.get(P0));
+ assertEquals(List.of(), pollErrors);
+
+ // nothing is committed again once the partition came back
+ partitionComesBackAfterAnotherConsumerCommitted(10);
+ assertEquals(10L, consumer.groupOffsets.get(P0));
+ }
+
+ @Test
+ void testLostPartitionIsNotSavedInTheOffsetRepository() {
+ MemoryStateRepository repository = new MemoryStateRepository();
+ configuration.setOffsetRepository(repository);
+ configuration.setAutoCommitEnable(false);
+ commitManager = new CommitToOffsetManager(consumer, kafkaConsumer(),
"t1", "orders");
+ listener = new ClassicRebalanceListener("t1", configuration,
commitManager, consumer);
+ consumer.assign(List.of(P0));
+
+ commitManager.recordOffset(P0, 4);
+ // the consumer was evicted, and the new owner of the partition went
on to offset 9
+ repository.setState("orders/0", "9");
+ rebalance(() -> listener.onPartitionsLost(List.of(P0)));
+
+ assertEquals("9", repository.getState("orders/0"), "the lost partition
must not be saved");
+ }
+
+ private void setup(boolean async) {
+ configuration.setAutoCommitEnable(false);
+ commitManager = async
+ ? new AsyncCommitManager(consumer, kafkaConsumer(), "t1",
"orders")
+ : new SyncCommitManager(consumer, kafkaConsumer(), "t1",
"orders");
+ listener = new ClassicRebalanceListener("t1", configuration,
commitManager, consumer);
+ consumer.assign(List.of(P0));
+ }
+
+ private KafkaConsumer kafkaConsumer() {
+ configuration.setTopic("orders");
+ KafkaEndpoint endpoint = mock(KafkaEndpoint.class);
+ when(endpoint.getConfiguration()).thenReturn(configuration);
+ KafkaConsumer kafkaConsumer = mock(KafkaConsumer.class);
+ when(kafkaConsumer.getEndpoint()).thenReturn(endpoint);
+ return kafkaConsumer;
+ }
+
+ private void partitionComesBackAfterAnotherConsumerCommitted(long offset) {
+ consumer.poll(Duration.ZERO);
+ consumer.groupOffsets.put(P0, offset);
+ // the partition comes back, and is revoked again before a record of
it was polled
+ rebalance(() -> listener.onPartitionsAssigned(List.of(P0)));
+ rebalance(() -> listener.onPartitionsRevoked(List.of(P0)));
+ consumer.poll(Duration.ZERO);
+ }
+
+ /**
+ * Runs a rebalance callback as the Kafka client does: an exception of the
listener is thrown from the poll once the
+ * rebalance has completed.
+ */
+ private void rebalance(Runnable callback) {
+ try {
+ callback.run();
+ } catch (KafkaException e) {
+ pollErrors.add(e);
+ }
+ }
+
+ /**
+ * A consumer of a group: the group offsets survive the rebalances
(MockConsumer only returns those of the assigned
+ * partitions), a commit can be refused, and the callback of an async
commit runs in a later poll or commitAsync, as
+ * with the Kafka client.
+ */
+ private static final class GroupMockConsumer extends MockConsumer<Object,
Object> {
+ final Map<TopicPartition, Long> groupOffsets = new
ConcurrentHashMap<>();
+ final List<Runnable> completedCommits = new ArrayList<>();
+ volatile RuntimeException commitFailure;
+ int commitRequests;
+
+ GroupMockConsumer() {
+ super("earliest");
+ updateBeginningOffsets(Map.of(P0, 0L));
+ }
+
+ @Override
+ public synchronized void commitSync(Map<TopicPartition,
OffsetAndMetadata> offsets, Duration timeout) {
+ commitSync(offsets);
+ }
+
+ @Override
+ public synchronized void commitSync(Map<TopicPartition,
OffsetAndMetadata> offsets) {
+ commitRequests++;
+ if (commitFailure != null) {
+ throw commitFailure;
+ }
+ offsets.forEach((partition, offset) -> groupOffsets.put(partition,
offset.offset()));
+ }
+
+ @Override
+ public synchronized void commitAsync(Map<TopicPartition,
OffsetAndMetadata> offsets, OffsetCommitCallback callback) {
+ runCompletedCommitCallbacks();
+ commitRequests++;
+ RuntimeException failure = commitFailure;
+ if (failure == null) {
+ offsets.forEach((partition, offset) ->
groupOffsets.put(partition, offset.offset()));
+ }
+ if (callback != null) {
+ completedCommits.add(() -> callback.onComplete(offsets,
failure));
+ }
+ }
+
+ @Override
+ public synchronized ConsumerRecords<Object, Object> poll(Duration
timeout) {
+ runCompletedCommitCallbacks();
+ return super.poll(timeout);
+ }
+
+ private void runCompletedCommitCallbacks() {
+ List<Runnable> callbacks = new ArrayList<>(completedCommits);
+ completedCommits.clear();
+ callbacks.forEach(Runnable::run);
+ }
+ }
+}