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 2f6e7801be92 CAMEL-27586: camel-kafka - async manual commit: a
commit() from before a rebalance is not made after the partition is assigned
back, and a late callback does not move the offset repository back (#30908)
2f6e7801be92 is described below
commit 2f6e7801be92f5646e8cb5dce96a58e17d60773f
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 12:42:27 2026 +0530
CAMEL-27586: camel-kafka - async manual commit: a commit() from before a
rebalance is not made after the partition is assigned back, and a late callback
does not move the offset repository back (#30908)
With the DefaultKafkaManualAsyncCommitFactory, KafkaManualCommit.commit()
records the offset and the consumer thread commits it before its next poll.
The revoke removed the recorded offset once, but a commit() that came after
it (a route that still held the record, for example in an aggregator) put it
again, and commitRequestedOffsets only checked that the partition was
assigned now. When the partition came back to the same consumer (every
rebalance with the eager protocol), the commit was made in the new
assignment: it moved back the offset another member committed in between,
and replaced a commit() of the current assignment made in the same poll
interval.
The AsyncCommitManager now numbers the assignments of each partition: the
number changes in discardRecordedOffset (revoke, lost, resume). A
DefaultKafkaManualAsyncCommit keeps the number of the assignment in which
its
record was polled, and its commit() is recorded only while the partition is
still in that assignment (checked inside requestedOffsets.compute, so a
commit() racing with a revoke is either committed by the revoke or dropped).
With offsetRepository, the callback of an async commit runs in a later poll
and saved its offset unconditionally in the repository that the consumers of
the endpoint share, also after the partition moved to another consumer that
had saved a newer offset. The callback now saves as before while the
partition is in the assignment in which the commit was sent, and otherwise
only an offset newer than the saved one, under a lock on the repository.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/catalog/docs/kafka-component.adoc | 4 +-
.../camel-kafka/src/main/docs/kafka-component.adoc | 4 +-
.../kafka/consumer/AsyncCommitManager.java | 72 ++++++-
.../consumer/DefaultKafkaManualAsyncCommit.java | 10 +-
.../consumer/AsyncCommitManagerReassignTest.java | 239 +++++++++++++++++++++
5 files changed, 321 insertions(+), 8 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc
index c0faf32bc841..d00aef44a20e 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc
@@ -322,7 +322,9 @@ You can use an asynchronous commit as well by configuring
the `KafkaManualCommit
Then `commit()` records the offset, and the consumer thread commits it before
its next poll, using the Kafka asynchronous commit API.
So the asynchronous commit can be called from a thread other than the consumer
thread, for example after an aggregator.
-A commit called after the partition was revoked from the consumer, for example
in a rebalance, is not made.
+A commit of a record that was polled before its partition was revoked from the
consumer (for example in a rebalance,
+also when the partition is assigned to the consumer again) or before the route
was suspended and resumed is not made:
+the consumer reads that record again.
With the synchronous or the asynchronous commit, a partition that is revoked
from the consumer (in a rebalance, or when
the consumer stops) is committed only up to the last record that the route
committed with `KafkaManualCommit.commit()`,
diff --git a/components/camel-kafka/src/main/docs/kafka-component.adoc
b/components/camel-kafka/src/main/docs/kafka-component.adoc
index c0faf32bc841..d00aef44a20e 100644
--- a/components/camel-kafka/src/main/docs/kafka-component.adoc
+++ b/components/camel-kafka/src/main/docs/kafka-component.adoc
@@ -322,7 +322,9 @@ You can use an asynchronous commit as well by configuring
the `KafkaManualCommit
Then `commit()` records the offset, and the consumer thread commits it before
its next poll, using the Kafka asynchronous commit API.
So the asynchronous commit can be called from a thread other than the consumer
thread, for example after an aggregator.
-A commit called after the partition was revoked from the consumer, for example
in a rebalance, is not made.
+A commit of a record that was polled before its partition was revoked from the
consumer (for example in a rebalance,
+also when the partition is assigned to the consumer again) or before the route
was suspended and resumed is not made:
+the consumer reads that record again.
With the synchronous or the asynchronous commit, a partition that is revoked
from the consumer (in a rebalance, or when
the consumer stops) is committed only up to the last record that the route
committed with `KafkaManualCommit.commit()`,
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 5ccdf6364450..580d5caed177 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
@@ -29,6 +29,7 @@ import org.apache.camel.spi.StateRepository;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.consumer.OffsetCommitCallback;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,6 +42,9 @@ public class AsyncCommitManager extends AbstractCommitManager
{
private final OffsetCache offsetCache = new OffsetCache();
// the offsets of the manual commits, which may come from any thread: the
consumer thread commits them
private final Map<TopicPartition, Long> requestedOffsets = new
ConcurrentHashMap<>();
+ // the assignment of each partition to this consumer: a number that
changes each time the partition is revoked, lost
+ // or read again (see discardRecordedOffset). A manual commit keeps the
assignment in which its record was polled
+ private final Map<TopicPartition, Long> assignments = new
ConcurrentHashMap<>();
private final StateRepository<String, String> offsetRepository;
private final boolean manualCommit;
@@ -100,8 +104,32 @@ public class AsyncCommitManager extends
AbstractCommitManager {
@Override
public void requestCommit(TopicPartition partition, long
partitionLastOffset) {
+ requestCommit(partition, partitionLastOffset, assignmentOf(partition));
+ }
+
+ /**
+ * Requests the commit of the given offset, for a record polled in the
given assignment of the partition (see
+ * {@link #assignmentOf(TopicPartition)}). The commit is not made if the
partition was revoked, lost or read again
+ * since, also when it is assigned to this consumer again: it could move
back the offset committed in the meantime,
+ * and replace the commit of a record of the current assignment.
+ */
+ void requestCommit(TopicPartition partition, long partitionLastOffset,
long assignment) {
// the Kafka consumer must only be used by its own thread, which
commits before its next poll
- requestedOffsets.put(partition, partitionLastOffset);
+ requestedOffsets.compute(partition, (p, requested) -> {
+ if (assignment == assignmentOf(p)) {
+ return partitionLastOffset;
+ }
+ LOG.debug("Dropping the requested commit of offset {} on {} from
{}: it is from an earlier assignment",
+ partitionLastOffset, p, threadId);
+ return requested;
+ });
+ }
+
+ /**
+ * The current assignment of the given partition to this consumer, which a
manual commit keeps when it is created
+ */
+ long assignmentOf(TopicPartition partition) {
+ return assignments.getOrDefault(partition, 0L);
}
@Override
@@ -128,7 +156,7 @@ public class AsyncCommitManager extends
AbstractCommitManager {
}
if (!offsets.isEmpty()) {
LOG.debug("Committing the requested offsets {} from {}", offsets,
threadId);
- consumer.commitAsync(offsets, this::postCommitCallback);
+ consumer.commitAsync(offsets, commitCallback(offsets.keySet()));
}
}
@@ -139,7 +167,7 @@ public class AsyncCommitManager extends
AbstractCommitManager {
final Map<TopicPartition, OffsetAndMetadata>
topicPartitionOffsetAndMetadataMap
= Collections.singletonMap(partition, new
OffsetAndMetadata(partitionLastOffset + 1));
- consumer.commitAsync(topicPartitionOffsetAndMetadataMap,
this::postCommitCallback);
+ consumer.commitAsync(topicPartitionOffsetAndMetadataMap,
commitCallback(Set.of(partition)));
}
@Override
@@ -161,22 +189,56 @@ public class AsyncCommitManager extends
AbstractCommitManager {
@Override
public void discardRecordedOffset(TopicPartition partition) {
+ // a new assignment: the manual commits of the records polled before
are not made (see requestCommit)
+ assignments.merge(partition, 1L, Long::sum);
requestedOffsets.remove(partition);
offsetCache.remove(partition);
}
- private void postCommitCallback(Map<TopicPartition, OffsetAndMetadata>
committed, Exception exception) {
+ private OffsetCommitCallback commitCallback(Set<TopicPartition>
partitions) {
+ // the assignments in which the offsets are committed
+ Map<TopicPartition, Long> sentIn = new HashMap<>();
+ partitions.forEach(partition -> sentIn.put(partition,
assignmentOf(partition)));
+ return (committed, exception) -> postCommitCallback(committed,
exception, sentIn);
+ }
+
+ private void postCommitCallback(
+ Map<TopicPartition, OffsetAndMetadata> committed, Exception
exception, Map<TopicPartition, Long> sentIn) {
if (exception == null) {
if (offsetRepository != null) {
for (var entry : committed.entrySet()) {
// Store the last read offset (Kafka committed offset - 1)
to match
// the contract in
OffsetPartitionAssignmentAdapter.resumeFromOffset
// which seeks to state + 1
- saveStateToOffsetRepository(entry.getKey(),
entry.getValue().offset() - 1, offsetRepository);
+ saveCommittedOffset(entry.getKey(),
entry.getValue().offset() - 1, sentIn.get(entry.getKey()));
}
}
}
offsetCache.removeCommittedEntries(committed, exception);
}
+
+ private void saveCommittedOffset(TopicPartition partition, long
partitionLastOffset, Long sentIn) {
+ // the repository is shared by the consumers of the endpoint, and the
callback runs in a later poll: when the
+ // partition was revoked from this consumer since the commit, another
consumer may own it and have saved a newer
+ // offset, which must be kept (the next assignment of the partition
seeks to the saved offset)
+ synchronized (offsetRepository) {
+ if ((sentIn != null && sentIn == assignmentOf(partition))
+ || isNewerThanSavedOffset(partition, partitionLastOffset))
{
+ saveStateToOffsetRepository(partition, partitionLastOffset,
offsetRepository);
+ } else {
+ LOG.debug("Not saving the offset {} of {} from {}: the
partition was revoked, and a newer offset is saved",
+ partitionLastOffset, partition, threadId);
+ }
+ }
+ }
+
+ private boolean isNewerThanSavedOffset(TopicPartition partition, long
partitionLastOffset) {
+ String saved =
offsetRepository.getState(serializeOffsetKey(partition));
+ try {
+ return saved == null || saved.isEmpty() || Long.parseLong(saved) <
partitionLastOffset;
+ } catch (NumberFormatException e) {
+ return true;
+ }
+ }
}
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommit.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommit.java
index e217f67358ce..559944c081ac 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommit.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommit.java
@@ -18,17 +18,25 @@ package org.apache.camel.component.kafka.consumer;
public class DefaultKafkaManualAsyncCommit extends DefaultKafkaManualCommit
implements KafkaAsyncManualCommit {
private final CommitManager commitManager;
+ // the assignment of the partition to the consumer in which the record was
polled
+ private final long assignment;
public
DefaultKafkaManualAsyncCommit(KafkaManualCommitFactory.CamelExchangePayload
camelExchangePayload,
KafkaManualCommitFactory.KafkaRecordPayload recordPayload,
CommitManager commitManager) {
super(camelExchangePayload, recordPayload);
this.commitManager = commitManager;
+ this.assignment = commitManager instanceof AsyncCommitManager async ?
async.assignmentOf(recordPayload.partition) : 0;
}
@Override
public void commit() {
// can be called from another thread than the consumer, such as the
one of an aggregator
- commitManager.requestCommit(getPartition(), getRecordOffset());
+ if (commitManager instanceof AsyncCommitManager async) {
+ // not committed if the partition was revoked or lost since the
record was polled
+ async.requestCommit(getPartition(), getRecordOffset(), assignment);
+ } else {
+ commitManager.requestCommit(getPartition(), getRecordOffset());
+ }
}
}
diff --git
a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/AsyncCommitManagerReassignTest.java
b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/AsyncCommitManagerReassignTest.java
new file mode 100644
index 000000000000..4a10901df585
--- /dev/null
+++
b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/AsyncCommitManagerReassignTest.java
@@ -0,0 +1,239 @@
+/*
+ * 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 java.util.concurrent.TimeUnit;
+
+import org.apache.camel.Exchange;
+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.ConsumerRecord;
+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.common.TopicPartition;
+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.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * With the asynchronous manual commit, the route may commit a record after
its partition was revoked from the consumer
+ * and assigned to it again (for example after an aggregator). Such a commit
is not made: it could move back the offset
+ * that another consumer committed in the meantime, or replace a commit of the
current assignment. The callback of a
+ * commit runs in a later poll, possibly after the partition moved to another
consumer of the endpoint, and must then
+ * not move back the offset that consumer saved in the offset repository the
consumers share.
+ */
+class AsyncCommitManagerReassignTest {
+
+ private static final TopicPartition P0 = new TopicPartition("orders", 0);
+
+ private final Map<TopicPartition, Long> groupOffsets = new
ConcurrentHashMap<>();
+ private final KafkaConfiguration configuration = new KafkaConfiguration();
+
+ @Test
+ void testCommitOfEarlierAssignmentIsNotMadeAfterReassign() {
+ Member member = new Member("t1");
+ member.assign();
+ KafkaManualCommit earlier = member.manualCommit(0);
+
+ // the partition is revoked while the route holds the record, and
another consumer commits up to offset 9
+ member.revoke();
+ groupOffsets.put(P0, 10L);
+ member.assign();
+
+ // the route commits the record of the earlier assignment
+ earlier.commit();
+ member.commitRequestedOffsetsAndPoll();
+
+ assertEquals(10L, groupOffsets.get(P0), "the offset committed by the
other consumer must be kept");
+ assertEquals(0, member.consumer.commitRequests);
+ }
+
+ @Test
+ void testCommitOfEarlierAssignmentDoesNotReplaceCurrentCommit() {
+ Member member = new Member("t1");
+ member.assign();
+ KafkaManualCommit earlier = member.manualCommit(0);
+ member.revoke();
+ groupOffsets.put(P0, 5L);
+ member.assign();
+ KafkaManualCommit current = member.manualCommit(6);
+
+ // both commits before the next poll: the one of the current
assignment, then the one of the earlier one
+ current.commit();
+ earlier.commit();
+ member.commitRequestedOffsetsAndPoll();
+
+ assertEquals(7L, groupOffsets.get(P0), "the commit of the current
assignment must be made");
+ }
+
+ @Test
+ void testCommitRacingWithRevokeIsNotMadeAfterReassign() throws Exception {
+ Member member = new Member("t1");
+ member.assign();
+ for (int i = 0; i < 500; i++) {
+ // the route commits a record while the partition is revoked and
assigned again: the revoke commits it,
+ // or it is not made at all
+ KafkaManualCommit earlier = member.manualCommit(i);
+ Thread route = new Thread(earlier::commit);
+ route.start();
+ member.revoke();
+ member.assign();
+ route.join(TimeUnit.SECONDS.toMillis(10));
+ assertFalse(route.isAlive());
+
+ int commitRequests = member.consumer.commitRequests;
+ member.commitRequestedOffsetsAndPoll();
+ assertEquals(commitRequests, member.consumer.commitRequests,
"iteration " + i);
+ }
+ }
+
+ @Test
+ void testLateCommitCallbackKeepsNewerOffsetInRepository() {
+ MemoryStateRepository repository = new MemoryStateRepository();
+ configuration.setOffsetRepository(repository);
+ Member first = new Member("t1");
+ Member second = new Member("t2");
+
+ // the first consumer commits up to offset 2: the callback (which
saves the offset) runs in its next poll
+ first.assign();
+ first.manualCommit(2).commit();
+ first.commitManager.commitRequestedOffsets();
+ assertEquals(3L, groupOffsets.get(P0));
+
+ // the partition moves to the second consumer, which commits up to
offset 5 and saves it
+ first.revoke();
+ second.assign();
+ second.manualCommit(5).commit();
+ second.commitRequestedOffsetsAndPoll();
+ assertEquals("5", repository.getState("orders/0"));
+
+ // the next poll of the first consumer runs the callback of its commit
+ first.consumer.poll(Duration.ZERO);
+ assertEquals("5", repository.getState("orders/0"), "the newer offset
of the second consumer must be kept");
+ }
+
+ @Test
+ void testLateCommitCallbackSavesOffsetAfterRevoke() {
+ MemoryStateRepository repository = new MemoryStateRepository();
+ configuration.setOffsetRepository(repository);
+ Member member = new Member("t1");
+ member.assign();
+ member.manualCommit(1).commit();
+ member.commitRequestedOffsetsAndPoll();
+ assertEquals("1", repository.getState("orders/0"));
+
+ // the revoke commits up to offset 4, and the callback runs in the
next poll, after the revoke
+ member.manualCommit(4).commit();
+ member.revoke();
+ assertEquals(5L, groupOffsets.get(P0));
+ member.consumer.poll(Duration.ZERO);
+ assertEquals("4", repository.getState("orders/0"), "the offset
committed on revoke must be saved");
+ }
+
+ private KafkaConsumer kafkaConsumer() {
+ configuration.setTopic("orders");
+ configuration.setAutoCommitEnable(false);
+ configuration.setAllowManualCommit(true);
+ KafkaEndpoint endpoint = mock(KafkaEndpoint.class);
+ when(endpoint.getConfiguration()).thenReturn(configuration);
+ KafkaConsumer kafkaConsumer = mock(KafkaConsumer.class);
+ when(kafkaConsumer.getEndpoint()).thenReturn(endpoint);
+ return kafkaConsumer;
+ }
+
+ /**
+ * A consumer thread of the endpoint: its Kafka consumer, commit manager
and rebalance listener.
+ */
+ private final class Member {
+ final GroupMockConsumer consumer = new GroupMockConsumer();
+ final AsyncCommitManager commitManager;
+ final ClassicRebalanceListener listener;
+
+ Member(String threadId) {
+ commitManager = new AsyncCommitManager(consumer, kafkaConsumer(),
threadId, "orders");
+ listener = new ClassicRebalanceListener(threadId, configuration,
commitManager, consumer);
+ }
+
+ void assign() {
+ consumer.assign(List.of(P0));
+ listener.onPartitionsAssigned(List.of(P0));
+ }
+
+ void revoke() {
+ listener.onPartitionsRevoked(List.of(P0));
+ }
+
+ KafkaManualCommit manualCommit(long offset) {
+ return commitManager.getManualCommit(mock(Exchange.class), P0,
+ new ConsumerRecord<>(P0.topic(), P0.partition(), offset,
null, "r" + offset));
+ }
+
+ void commitRequestedOffsetsAndPoll() {
+ commitManager.commitRequestedOffsets();
+ consumer.poll(Duration.ZERO);
+ }
+ }
+
+ /**
+ * A consumer of the group: the group offsets survive the rebalances, and
the callback of an async commit runs in a
+ * later poll or commitAsync, as with the Kafka client.
+ */
+ private final class GroupMockConsumer extends MockConsumer<Object, Object>
{
+ final List<Runnable> completedCommits = new ArrayList<>();
+ int commitRequests;
+
+ GroupMockConsumer() {
+ super("earliest");
+ updateBeginningOffsets(Map.of(P0, 0L));
+ }
+
+ @Override
+ public synchronized void commitAsync(Map<TopicPartition,
OffsetAndMetadata> offsets, OffsetCommitCallback callback) {
+ runCompletedCommitCallbacks();
+ commitRequests++;
+ offsets.forEach((partition, offset) -> groupOffsets.put(partition,
offset.offset()));
+ if (callback != null) {
+ completedCommits.add(() -> callback.onComplete(offsets, null));
+ }
+ }
+
+ @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);
+ }
+ }
+}