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 7a580898866a CAMEL-27419: camel-kafka - with batching, a resume keeps
the records held for an incomplete batch and the offset recorded before it, and
the committed offset can move back (#30761)
7a580898866a is described below
commit 7a580898866a0eefc9125bb1b67abdce61c5b3a0
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 25 13:30:29 2026 +0530
CAMEL-27419: camel-kafka - with batching, a resume keeps the records held
for an incomplete batch and the offset recorded before it, and the committed
offset can move back (#30761)
A resume after a pause seeks every assigned partition that has a committed
offset to that offset, and the consumer reads the records after it again.
With batching=true two things from before the resume were kept:
- the records of the partition that the batch still held: they were
processed twice, and the batch that held them committed past them before
the records read again committed a lower offset;
- the offset recorded in the OffsetCache after failed async commits: the
facade commits it after the first poll, even when that poll returns fewer
records than a batch, and the batch of the records read again then
commits a lower offset.
Either way the committed offset moved back without any rebalance.
updateTaskState now calls commitManager.discardRecordedOffset (CAMEL-27317)
for each partition it seeks, and discardPendingRecords (CAMEL-27316) for
those partitions; the records are read and committed again from the
committed offset. Each half alone leaves one of the two cases.
Found with a TLA+ model.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../camel/component/kafka/KafkaFetchRecords.java | 11 ++
.../component/kafka/consumer/CommitManager.java | 6 +-
.../support/KafkaRecordProcessorFacade.java | 5 +-
.../batching/KafkaRecordBatchingProcessor.java | 6 +-
.../kafka/KafkaBatchingConsumerResumeTest.java | 216 +++++++++++++++++++++
5 files changed, 238 insertions(+), 6 deletions(-)
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java
index ecce1889b472..bad2a3ec1590 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java
@@ -17,7 +17,9 @@
package org.apache.camel.component.kafka;
import java.time.Duration;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.List;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -486,14 +488,23 @@ public class KafkaFetchRecords implements Runnable {
case RESUME_REQUESTED:
LOG.info("Resuming the consumer as a response to a resume
request");
if (consumer.committed(this.consumer.assignment()) != null) {
+ List<TopicPartition> seeked = new ArrayList<>();
consumer.committed(this.consumer.assignment()).forEach((k,
v) -> {
if (v != null) {
final TopicPartition tp = (TopicPartition) k;
LOG.info("Resuming from the offset {} for the
topic {} with partition {}",
((OffsetAndMetadata) v).offset(),
tp.topic(), tp.partition());
consumer.seek(tp, ((OffsetAndMetadata)
v).offset());
+ // an offset recorded after the committed one (its
commit failed) must not be committed
+ // any more: the records after the committed
offset are read and committed again
+ commitManager.discardRecordedOffset(tp);
+ seeked.add(tp);
}
});
+ // the records of these partitions that are held for an
incomplete batch are read again from the
+ // committed offset: keeping them would process them
twice, and the commit of the batch that holds
+ // them could move the committed offset back
+ recordProcessorFacade.discardPendingRecords(seeked);
}
consumer.resume(consumer.assignment());
state.compareAndSet(State.RESUME_REQUESTED, State.RUNNING);
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 bf9ff90e317d..108b5ce87c1c 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
@@ -73,9 +73,11 @@ public interface CommitManager {
* 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.
+ * back the offset that another consumer committed in the meantime. Also
called when a resume seeks the partition
+ * back to its committed offset: the records after it are read and
committed again, and an offset kept from before
+ * (such as one whose commit failed) could be committed in between and
move the committed offset back.
*
- * @param partition the partition that is no longer assigned to the
consumer
+ * @param partition the partition that is no longer assigned to the
consumer, or that is read again
*/
default void discardRecordedOffset(TopicPartition partition) {
// NO-OP
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/KafkaRecordProcessorFacade.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/KafkaRecordProcessorFacade.java
index 5d2aba6ac18d..bf5aa62db316 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/KafkaRecordProcessorFacade.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/KafkaRecordProcessorFacade.java
@@ -37,9 +37,10 @@ public interface KafkaRecordProcessorFacade {
/**
* Drops the records of the given partitions that were polled but are not
processed yet, such as the records held
* for an incomplete batch. Called when the partitions are revoked or
lost: they must not be processed and committed
- * by this consumer any more, and their next owner reads them again from
the committed offset.
+ * by this consumer any more, and their next owner reads them again from
the committed offset. Also called when a
+ * resume seeks the partitions back to their committed offset, from where
the consumer reads them again.
*
- * @param partitions the partitions that are no longer assigned to the
consumer
+ * @param partitions the partitions that are no longer assigned to the
consumer, or that are read again
*/
default void discardPendingRecords(Collection<TopicPartition> partitions) {
// NO-OP: by default the records of a poll are processed before the
next poll
diff --git
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/batching/KafkaRecordBatchingProcessor.java
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/batching/KafkaRecordBatchingProcessor.java
index 395605af4dd0..b67fea293ddd 100644
---
a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/batching/KafkaRecordBatchingProcessor.java
+++
b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/batching/KafkaRecordBatchingProcessor.java
@@ -189,7 +189,9 @@ final class KafkaRecordBatchingProcessor extends
KafkaRecordProcessor {
* Removes the records of the given partitions from the incomplete batch,
and releases their exchanges. Called when
* the partitions are revoked or lost (inside the poll, on the consumer
thread): the batch must not process them and
* commit their offsets, which could move back the offset that the new
owner of a partition committed. The new owner
- * reads them again from the committed offset (also this consumer, if the
partition is assigned to it again).
+ * reads them again from the committed offset (also this consumer, if the
partition is assigned to it again). Also
+ * called on a resume, which seeks the partitions back to the committed
offset (on the consumer thread, after the
+ * poll): the consumer reads these records again.
*/
void discardBufferedRecords(KafkaConsumer camelKafkaConsumer,
Collection<TopicPartition> partitions) {
if (exchangeList.isEmpty() || partitions.isEmpty()) {
@@ -209,7 +211,7 @@ final class KafkaRecordBatchingProcessor extends
KafkaRecordProcessor {
}
}
if (discarded > 0) {
- LOG.debug("Discarded {} records of the incomplete batch from the
revoked partitions {} ({} records left)",
+ LOG.debug("Discarded {} records of the incomplete batch from the
partitions {} ({} records left)",
discarded, partitions, exchangeList.size());
}
}
diff --git
a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaBatchingConsumerResumeTest.java
b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaBatchingConsumerResumeTest.java
new file mode 100644
index 000000000000..c393cebd2d02
--- /dev/null
+++
b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaBatchingConsumerResumeTest.java
@@ -0,0 +1,216 @@
+/*
+ * 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;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.kafka.clients.consumer.Consumer;
+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.clients.consumer.RetriableCommitFailedException;
+import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.common.TopicPartition;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * A resume of a paused batching consumer seeks each partition to its
committed offset, from where the consumer reads
+ * the records again. The records of the partition that the batch still holds
must then not stay in the batch: they
+ * would be processed twice, and the commit of the batch that holds them could
move the committed offset back. Nor must
+ * the offset recorded before the resume (its commit failed): committing it
before the records read again commit their
+ * own offsets would move the committed offset back too. Uses a {@link
MockConsumer} instead of a broker.
+ */
+class KafkaBatchingConsumerResumeTest extends CamelTestSupport {
+
+ private static final String TOPIC = "batching-resume";
+ private static final TopicPartition PARTITION = new TopicPartition(TOPIC,
0);
+
+ private final FailingCommitMockConsumer mockConsumer = new
FailingCommitMockConsumer();
+ private final List<List<String>> batches = new CopyOnWriteArrayList<>();
+
+ @BindToRegistry("mockFactory")
+ private final KafkaClientFactory factory = new KafkaClientFactory() {
+ @Override
+ public Producer getProducer(Properties kafkaProps) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Consumer getConsumer(Properties kafkaProps) {
+ return mockConsumer;
+ }
+
+ @Override
+ public String getBrokers(KafkaConfiguration configuration) {
+ return "localhost:9092";
+ }
+ };
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ // a batch of 2 records, committed by Camel; the poll timeout
is long enough that an incomplete batch
+ // is never dispatched during the test
+ from("kafka:" + TOPIC +
"?brokers=localhost:9092&kafkaClientFactory=#mockFactory&groupId=test"
+ +
"&batching=true&maxPollRecords=2&pollTimeoutMs=60000&autoCommitEnable=false")
+ .routeId("kafka")
+ .process(exchange -> {
+ List<String> batch = new ArrayList<>();
+ for (Object record :
exchange.getMessage().getBody(List.class)) {
+ batch.add(((Exchange)
record).getMessage().getBody(String.class));
+ }
+ batches.add(batch);
+ });
+ }
+ };
+ }
+
+ @Override
+ protected void setupResources() {
+ mockConsumer.updateBeginningOffsets(Map.of(PARTITION, 0L));
+ mockConsumer.schedulePollTask(() ->
mockConsumer.rebalance(List.of(PARTITION)));
+ }
+
+ @Test
+ void testResumeDoesNotKeepHeldRecordsTwice() throws Exception {
+ addRecords(0, 2);
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
Long.valueOf(2).equals(mockConsumer.lastCommitted()));
+
+ // record 2 is polled and held for the next batch
+ addRecords(2, 1);
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
mockConsumer.position(PARTITION) == 3);
+
+ // the resume seeks the partition to the committed offset 2: the
consumer reads record 2 again
+ pauseAndResume();
+ addRecords(2, 2);
+ await().atMost(20, TimeUnit.SECONDS).until(() -> batches.size() == 2);
+
+ assertEquals(List.of(List.of("a0", "a1"), List.of("a2", "a3")),
batches, "each record must be processed once");
+ assertEquals(4L, mockConsumer.lastCommitted());
+ }
+
+ @Test
+ void testResumeAfterFailedCommitDoesNotMoveCommittedOffsetBack() throws
Exception {
+ addRecords(0, 2);
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
Long.valueOf(2).equals(mockConsumer.lastCommitted()));
+
+ // the commits of the next two batches fail: the committed offset
stays at 2
+ mockConsumer.failCommits = true;
+ addRecords(2, 4);
+ await().atMost(20, TimeUnit.SECONDS).until(() -> batches.size() == 3);
+ // record 6 is polled and held for the next batch
+ addRecords(6, 1);
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
mockConsumer.position(PARTITION) == 7);
+
+ // the commits work again; the resume seeks the partition to the
committed offset 2, and the consumer reads the
+ // records from 2 again
+ pauseAndResume();
+ mockConsumer.failCommits = false;
+ // the first poll returns record 2 alone, fewer than a batch: it is
held, and the commit after that poll must
+ // not commit the offset recorded before the resume
+ addRecords(2, 1);
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
mockConsumer.position(PARTITION) == 3);
+ addRecords(3, 5);
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
Long.valueOf(8).equals(mockConsumer.lastCommitted()));
+
+ assertEquals(List.of(2L, 4L, 6L, 8L), mockConsumer.commits, "the
committed offset must not move back");
+ assertEquals(List.of(List.of("a2", "a3"), List.of("a4", "a5"),
List.of("a6", "a7")),
+ batches.subList(3, batches.size()), "the records read again
must be processed in order, once");
+ }
+
+ private void pauseAndResume() throws Exception {
+ context.getRouteController().suspendRoute("kafka");
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
mockConsumer.paused().contains(PARTITION));
+ context.getRouteController().resumeRoute("kafka");
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
mockConsumer.paused().isEmpty());
+ // the records are added once the consumer has seeked, as the mock
returns only records at or after its position
+ // and forgets the records it returned
+ await().atMost(20, TimeUnit.SECONDS)
+ .until(() -> mockConsumer.position(PARTITION) ==
mockConsumer.lastCommitted());
+ }
+
+ private void addRecords(long firstOffset, int count) {
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
mockConsumer.assignment().contains(PARTITION));
+ for (int i = 0; i < count; i++) {
+ long offset = firstOffset + i;
+ mockConsumer.addRecord(new ConsumerRecord<>(TOPIC,
PARTITION.partition(), offset, null, "a" + offset));
+ }
+ }
+
+ private static final class FailingCommitMockConsumer extends
MockConsumer<Object, Object> {
+ // the offsets committed for the partition, in order
+ final List<Long> commits = new CopyOnWriteArrayList<>();
+ volatile boolean failCommits;
+
+ FailingCommitMockConsumer() {
+ super("earliest");
+ }
+
+ Long lastCommitted() {
+ return commits.isEmpty() ? null : commits.get(commits.size() - 1);
+ }
+
+ @Override
+ public synchronized void commitAsync(Map<TopicPartition,
OffsetAndMetadata> offsets, OffsetCommitCallback callback) {
+ if (failCommits) {
+ // the Kafka client calls the callback of a failed commit in a
later poll, with the exception; the
+ // AsyncCommitManager keeps the offset in its cache either way
+ callback.onComplete(offsets, new
RetriableCommitFailedException("commit failed in the test"));
+ return;
+ }
+ OffsetAndMetadata offset = offsets.get(PARTITION);
+ // the commit after each poll commits the same offset again:
record each committed value once
+ if (offset != null &&
!Long.valueOf(offset.offset()).equals(lastCommitted())) {
+ commits.add(offset.offset());
+ }
+ super.commitAsync(offsets, callback);
+ }
+
+ @Override
+ public synchronized ConsumerRecords<Object, Object> poll(Duration
timeout) {
+ ConsumerRecords<Object, Object> records = super.poll(timeout);
+ if (records.isEmpty()) {
+ // a real consumer waits up to the poll timeout when there is
nothing to fetch
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
+ }
+ return records;
+ }
+
+ @Override
+ public synchronized void close() {
+ // keep the mock usable: a stopped route closes the consumer
+ }
+ }
+}