This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-26993-kafka-manual-commit-revoke in repository https://gitbox.apache.org/repos/asf/camel.git
commit b9a2976bd7d43a0855e3fb9be0eda420ec40b9c0 Author: Claus Ibsen <[email protected]> AuthorDate: Tue Nov 24 19:53:54 2026 +0100 CAMEL-26993: camel-kafka - with manual commits, a rebalance or a stop commits only what the route committed With allowManualCommit=true and the DefaultKafkaManualCommitFactory or the DefaultKafkaManualAsyncCommitFactory, the commit managers (SyncCommitManager, AsyncCommitManager) cache the offset of every processed record. On a revoke (rebalance, or the unsubscribe when the consumer stops) commit(partition) committed that cached offset: the last processed record, also when the route had not committed it, for example a record held in an aggregation group that is not complete. Such records were not consumed again, and were lost when the held exchanges were lost. The commit managers now keep the two offsets apart: - the last processed offset, in the OffsetCache, which breakOnFirstError commits through the new CommitManager.commitProcessedOffset(partition), so the records before the failed one are committed and the failed one is polled again, as before; - the offset the route committed through KafkaManualCommit.commit(): DefaultKafkaManualSyncCommit commits it at once (forceCommit), and DefaultKafkaManualAsyncCommit requests it (requestCommit no longer records it in the OffsetCache). With manual commits, commit(partition) (revoke, stop, the pausable consumer after a failed record, the per-poll flush of the batching consumer) commits only the offset the route committed and that is not committed yet: nothing with the synchronous commit, the pending requested offset with the asynchronous one. Without manual commits nothing changes. KafkaConsumerAsyncManualCommitIT stopped the Kafka route before the aggregator had committed the records, and passed only because the stop committed the processed records: it now waits for the commits first. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../apache/camel/catalog/docs/kafka-component.adoc | 7 + .../camel-kafka/src/main/docs/kafka-component.adoc | 7 + .../kafka/consumer/AsyncCommitManager.java | 28 +++- .../component/kafka/consumer/CommitManager.java | 26 ++- .../kafka/consumer/SyncCommitManager.java | 17 ++ .../streaming/KafkaRecordStreamingProcessor.java | 5 +- .../kafka/consumer/CommitManagerRebalanceTest.java | 102 +++++++++++ .../DefaultKafkaManualAsyncCommitTest.java | 8 +- .../consumer/KafkaManualCommitRevokeTest.java | 186 +++++++++++++++++++++ .../KafkaRecordStreamingProcessorTest.java | 23 +++ .../KafkaConsumerAsyncManualCommitIT.java | 11 ++ .../commit/KafkaConsumerManualCommitStopIT.java | 79 +++++++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 15 ++ 13 files changed, 500 insertions(+), 14 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 fa71ded6f167..247e1c977402 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 @@ -324,6 +324,12 @@ Then `commit()` records the offset, and the consumer thread commits it before it 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. +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()`, +not up to the last record that the consumer processed. A record that the route still holds, for example in an +aggregation group that is not complete, is not committed for it: the records that the route did not commit are consumed +again after a rebalance or a restart, so they may be processed more than once. + If you want to use a custom implementation of `KafkaManualCommit` then you can configure a custom `KafkaManualCommitFactory` on the `KafkaComponent` that creates instances of your custom implementation. @@ -357,6 +363,7 @@ message with an error is retried. The consumer must manage that in the route usi When the `CommitManager` is changed to either the synchronous or asynchronous manager then `breakOnFirstError` will automatically commit the offset so that the message with an error is retried. This message will be continually retried until it can be processed without an error. +The break commits the records processed before the failed one, whether the route committed them or not. NOTE: A synchronous commit must be called by the consumer thread. Certain EIPs, async or concurrent operations in the DSL continue on another thread: for example, the Aggregate EIP completes its groups on its own `Aggregator` thread. A synchronous commit on such a thread makes the Kafka client throw diff --git a/components/camel-kafka/src/main/docs/kafka-component.adoc b/components/camel-kafka/src/main/docs/kafka-component.adoc index fa71ded6f167..247e1c977402 100644 --- a/components/camel-kafka/src/main/docs/kafka-component.adoc +++ b/components/camel-kafka/src/main/docs/kafka-component.adoc @@ -324,6 +324,12 @@ Then `commit()` records the offset, and the consumer thread commits it before it 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. +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()`, +not up to the last record that the consumer processed. A record that the route still holds, for example in an +aggregation group that is not complete, is not committed for it: the records that the route did not commit are consumed +again after a rebalance or a restart, so they may be processed more than once. + If you want to use a custom implementation of `KafkaManualCommit` then you can configure a custom `KafkaManualCommitFactory` on the `KafkaComponent` that creates instances of your custom implementation. @@ -357,6 +363,7 @@ message with an error is retried. The consumer must manage that in the route usi When the `CommitManager` is changed to either the synchronous or asynchronous manager then `breakOnFirstError` will automatically commit the offset so that the message with an error is retried. This message will be continually retried until it can be processed without an error. +The break commits the records processed before the failed one, whether the route committed them or not. NOTE: A synchronous commit must be called by the consumer thread. Certain EIPs, async or concurrent operations in the DSL continue on another thread: for example, the Aggregate EIP completes its groups on its own `Aggregator` thread. A synchronous commit on such a thread makes the Kafka client throw 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 77bfcbe87455..5ccdf6364450 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 @@ -37,10 +37,12 @@ public class AsyncCommitManager extends AbstractCommitManager { private static final Logger LOG = LoggerFactory.getLogger(AsyncCommitManager.class); private final Consumer<?, ?> consumer; + // the offsets of the last processed records 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<>(); private final StateRepository<String, String> offsetRepository; + private final boolean manualCommit; public AsyncCommitManager(Consumer<?, ?> consumer, KafkaConsumer kafkaConsumer, String threadId, String printableTopic) { super(consumer, kafkaConsumer, threadId, printableTopic); @@ -48,6 +50,7 @@ public class AsyncCommitManager extends AbstractCommitManager { this.consumer = consumer; offsetRepository = configuration.getOffsetRepository(); + manualCommit = configuration.isAllowManualCommit(); } @Override @@ -62,6 +65,28 @@ public class AsyncCommitManager extends AbstractCommitManager { public void commit(TopicPartition partition) { // the partition is committed now (for example, it is revoked): its requested offset is not committed later Long requested = requestedOffsets.remove(partition); + Long offset; + if (manualCommit) { + // only what the route committed: the route may still hold the records it processed after that, for + // example in an aggregation group that is not complete + offset = requested; + } else { + offset = offsetCache.getOffset(partition); + if (offset == null) { + offset = requested; + } + } + if (offset == null) { + return; + } + + commitAsync(consumer, partition, offset); + } + + @Override + public void commitProcessedOffset(TopicPartition partition) { + // the partition is committed now: its requested offset is not committed later + Long requested = requestedOffsets.remove(partition); Long offset = offsetCache.getOffset(partition); if (offset == null) { offset = requested; @@ -76,7 +101,6 @@ public class AsyncCommitManager extends AbstractCommitManager { @Override public void requestCommit(TopicPartition partition, long partitionLastOffset) { // the Kafka consumer must only be used by its own thread, which commits before its next poll - offsetCache.recordOffset(partition, partitionLastOffset); requestedOffsets.put(partition, partitionLastOffset); } @@ -98,8 +122,6 @@ public class AsyncCommitManager extends AbstractCommitManager { if (assignment.contains(partition)) { offsets.put(partition, new OffsetAndMetadata(offset + 1)); } else { - // requestCommit also recorded the offset in the cache: a later revoke of the partition must not commit it - offsetCache.remove(partition); LOG.debug("Dropping the requested commit of offset {} on {} from {}: the partition is no longer assigned", offset, partition, threadId); } 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 e4d220ada6c7..bf9ff90e317d 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 @@ -31,12 +31,28 @@ public interface CommitManager { void commit(); /** - * Commits the offsets of the given partition + * Commits the offsets of the given partition, for example when the partition is revoked or the consumer stops. + * <p> + * With manual commits (allowManualCommit=true), only the offset that the route committed through + * {@link KafkaManualCommit#commit()} is committed, if it is not committed yet: the last processed record may still + * be held by the route (for example in an aggregation group that is not complete), and is not committed for it. + * Without manual commits, the offset of the last processed record is committed. * * @param partition the partition to commit the offsets */ void commit(TopicPartition partition); + /** + * Commits the offset of the last processed record of the given partition, also with manual commits, whether the + * route committed it or not. Used by breakOnFirstError to commit the records before the failed one, so that the + * failed one is polled again. + * + * @param partition the partition to commit the offsets + */ + default void commitProcessedOffset(TopicPartition partition) { + commit(partition); + } + /** * Forcefully commits the offset of the given partition * @@ -66,16 +82,16 @@ public interface CommitManager { } /** - * 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 - * can be called from any thread. + * Commits the given offset, for an asynchronous manual commit (the route called + * {@link KafkaManualCommit#commit()}). A commit manager that commits asynchronously leaves the commit to the + * consumer thread (see {@link #commitRequestedOffsets()}), so this can be called from any thread. * * @param partition the partition to commit the offsets * @param partitionLastOffset the last offset to commit */ default void requestCommit(TopicPartition partition, long partitionLastOffset) { recordOffset(partition, partitionLastOffset); - commit(partition); + commitProcessedOffset(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 af9a624bba8a..6c5bdc886418 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 @@ -32,9 +32,11 @@ import org.slf4j.LoggerFactory; public class SyncCommitManager extends AbstractCommitManager { private static final Logger LOG = LoggerFactory.getLogger(SyncCommitManager.class); + // the offsets of the last processed records private final OffsetCache offsetCache = new OffsetCache(); private final Consumer<?, ?> consumer; private final StateRepository<String, String> offsetRepository; + private final boolean manualCommit; public SyncCommitManager(Consumer<?, ?> consumer, KafkaConsumer kafkaConsumer, String threadId, String printableTopic) { super(consumer, kafkaConsumer, threadId, printableTopic); @@ -42,6 +44,7 @@ public class SyncCommitManager extends AbstractCommitManager { this.consumer = consumer; offsetRepository = configuration.getOffsetRepository(); + manualCommit = configuration.isAllowManualCommit(); } @Override @@ -54,6 +57,20 @@ public class SyncCommitManager extends AbstractCommitManager { @Override public void commit(TopicPartition partition) { + if (manualCommit) { + // a manual commit of the route (KafkaManualCommit.commit()) is committed at once (forceCommit), so nothing + // is left to commit. The last processed record is not committed: the route may still hold it, for example + // in an aggregation group that is not complete + LOG.debug("Not committing the last processed offset of {} from thread {}: the route commits manually", + partition, threadId); + return; + } + + commitProcessedOffset(partition); + } + + @Override + public void commitProcessedOffset(TopicPartition partition) { if (LOG.isDebugEnabled()) { LOG.debug("Auto commitSync from thread {} from topic {}", threadId, partition.topic()); } diff --git a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessor.java b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessor.java index 2ff958e6c5e5..0ccc1f2a9d1e 100644 --- a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessor.java +++ b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessor.java @@ -731,10 +731,11 @@ final class KafkaRecordStreamingProcessor extends KafkaRecordProcessor { // when route uses NOOP Commit Manager it will rely // on the route implementation to explicitly commit offset // when route uses Synch/Asynch Commit Manager it commits the offset of the - // records before the failing record. That commit can fail or time out: the + // records before the failing record, also with manual commits (whether the route + // committed them or not). That commit can fail or time out: the // consumer still breaks out and polls again from the last committed offset try { - commitManager.commit(topicPartition); + commitManager.commitProcessedOffset(topicPartition); } catch (WakeupException | InterruptException e) { throw e; } catch (KafkaException e) { 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 index abf48cf3d475..1d7be3c89a47 100644 --- 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 @@ -39,6 +39,7 @@ import org.apache.kafka.common.errors.TimeoutException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -139,6 +140,90 @@ class CommitManagerRebalanceTest { assertEquals(10L, consumer.groupOffsets.get(P0)); } + @Test + void testRevokeWithManualCommitDoesNotCommitTheProcessedRecordsSync() { + setup(false, true); + revokeWithManualCommitDoesNotCommitTheProcessedRecords(); + } + + @Test + void testRevokeWithManualCommitDoesNotCommitTheProcessedRecordsAsync() { + setup(true, true); + revokeWithManualCommitDoesNotCommitTheProcessedRecords(); + } + + private void revokeWithManualCommitDoesNotCommitTheProcessedRecords() { + // the records up to offset 4 are processed, the route did not commit any of them (it holds them, for example + // in an aggregation group that is not complete) + commitManager.recordOffset(P0, 4); + rebalance(() -> listener.onPartitionsRevoked(List.of(P0))); + consumer.poll(Duration.ZERO); + + assertEquals(0, consumer.commitRequests, "the records the route did not commit must not be committed"); + assertNull(consumer.groupOffsets.get(P0)); + assertEquals(List.of(), pollErrors); + } + + @Test + void testRevokeWithManualCommitCommitsWhatTheRouteCommittedSync() { + setup(false, true); + // the route commits the records up to offset 2 (at once), and processes the records up to offset 4 + commitManager.forceCommit(P0, 2); + commitManager.recordOffset(P0, 4); + rebalance(() -> listener.onPartitionsRevoked(List.of(P0))); + + assertEquals(1, consumer.commitRequests, "only the commit of the route"); + assertEquals(3L, consumer.groupOffsets.get(P0)); + } + + @Test + void testRevokeWithManualCommitCommitsWhatTheRouteCommittedAsync() { + setup(true, true); + // the route commits the records up to offset 2, which the consumer thread has not committed yet, and processes + // the records up to offset 4 + commitManager.recordOffset(P0, 2); + commitManager.requestCommit(P0, 2); + commitManager.recordOffset(P0, 4); + rebalance(() -> listener.onPartitionsRevoked(List.of(P0))); + consumer.poll(Duration.ZERO); + + assertEquals(1, consumer.commitRequests); + assertEquals(3L, consumer.groupOffsets.get(P0), "the revoke must commit the records the route committed"); + + // nothing is left to commit before the next poll + commitManager.commitRequestedOffsets(); + assertEquals(1, consumer.commitRequests); + } + + @Test + void testBreakOnFirstErrorWithManualCommitCommitsTheProcessedRecordsSync() { + setup(false, true); + breakOnFirstErrorWithManualCommitCommitsTheProcessedRecords(); + } + + @Test + void testBreakOnFirstErrorWithManualCommitCommitsTheProcessedRecordsAsync() { + setup(true, true); + breakOnFirstErrorWithManualCommitCommitsTheProcessedRecords(); + } + + private void breakOnFirstErrorWithManualCommitCommitsTheProcessedRecords() { + // the records up to offset 4 are processed, the route committed up to offset 2, and the record at offset 5 + // failed: breakOnFirstError commits the records before the failed one, so the failed one is polled again + routeCommits(2); + commitManager.recordOffset(P0, 4); + commitManager.commitProcessedOffset(P0); + consumer.poll(Duration.ZERO); + assertEquals(5L, consumer.groupOffsets.get(P0)); + + // the consumer breaks out and unsubscribes: the revoke has nothing left to commit + int commitRequests = consumer.commitRequests; + rebalance(() -> listener.onPartitionsRevoked(List.of(P0))); + consumer.poll(Duration.ZERO); + assertEquals(commitRequests, consumer.commitRequests); + assertEquals(5L, consumer.groupOffsets.get(P0)); + } + @Test void testLostPartitionIsNotSavedInTheOffsetRepository() { MemoryStateRepository repository = new MemoryStateRepository(); @@ -157,7 +242,12 @@ class CommitManagerRebalanceTest { } private void setup(boolean async) { + setup(async, false); + } + + private void setup(boolean async, boolean manualCommit) { configuration.setAutoCommitEnable(false); + configuration.setAllowManualCommit(manualCommit); commitManager = async ? new AsyncCommitManager(consumer, kafkaConsumer(), "t1", "orders") : new SyncCommitManager(consumer, kafkaConsumer(), "t1", "orders"); @@ -165,6 +255,18 @@ class CommitManagerRebalanceTest { consumer.assign(List.of(P0)); } + /** + * The route calls KafkaManualCommit.commit() for the record at the given offset: DefaultKafkaManualSyncCommit + * commits at once, DefaultKafkaManualAsyncCommit leaves the commit to the consumer thread. + */ + private void routeCommits(long offset) { + if (commitManager instanceof AsyncCommitManager) { + commitManager.requestCommit(P0, offset); + } else { + commitManager.forceCommit(P0, offset); + } + } + private KafkaConsumer kafkaConsumer() { configuration.setTopic("orders"); KafkaEndpoint endpoint = mock(KafkaEndpoint.class); diff --git a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommitTest.java b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommitTest.java index 995c0b55e892..aa6ff33c2da0 100644 --- a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommitTest.java +++ b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/DefaultKafkaManualAsyncCommitTest.java @@ -126,10 +126,10 @@ class DefaultKafkaManualAsyncCommitTest extends CamelTestSupport { sendTwoRecords(); MockEndpoint.assertIsSatisfied(context); - // the partition is revoked: the last processed offset is committed (offset 2) + // the partition is revoked: the route committed none of the records, so none is committed (CAMEL-26993) mockConsumer.schedulePollTask(() -> mockConsumer.rebalance(List.of())); await().atMost(10, TimeUnit.SECONDS).until(() -> mockConsumer.assignment().isEmpty()); - assertEquals(2, lastCommittedOffset()); + assertEquals(-1, lastCommittedOffset()); int commitsAtRevoke = mockConsumer.commits.size(); // the route commits the first record after the revoke, from another thread than the consumer @@ -142,7 +142,7 @@ class DefaultKafkaManualAsyncCommitTest extends CamelTestSupport { // the commit is not made: it would move back the offset the new owner of the partition committed assertFalse(mockConsumer.commits.subList(commitsAtRevoke, mockConsumer.commits.size()).stream() .anyMatch(offsets -> offsets.containsKey(PARTITION))); - assertEquals(2, lastCommittedOffset()); + assertEquals(-1, lastCommittedOffset()); // the partition comes back and is revoked again before any of its records is processed: the dropped request // left no offset behind for that revoke to commit @@ -150,7 +150,7 @@ class DefaultKafkaManualAsyncCommitTest extends CamelTestSupport { await().atMost(10, TimeUnit.SECONDS).until(() -> mockConsumer.assignment().contains(PARTITION)); mockConsumer.schedulePollTask(() -> mockConsumer.rebalance(List.of())); await().atMost(10, TimeUnit.SECONDS).until(() -> mockConsumer.assignment().isEmpty()); - assertEquals(2, lastCommittedOffset()); + assertEquals(-1, lastCommittedOffset()); } private void sendTwoRecords() { diff --git a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/KafkaManualCommitRevokeTest.java b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/KafkaManualCommitRevokeTest.java new file mode 100644 index 000000000000..ca4a1ba4bb96 --- /dev/null +++ b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/KafkaManualCommitRevokeTest.java @@ -0,0 +1,186 @@ +/* + * 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.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.camel.BindToRegistry; +import org.apache.camel.Exchange; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.kafka.KafkaClientFactory; +import org.apache.camel.component.kafka.KafkaConfiguration; +import org.apache.camel.component.kafka.KafkaConstants; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit6.CamelTestSupport; +import org.apache.camel.test.junit6.TestExecutionConfiguration; +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerRecord; +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.producer.Producer; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * With manual commits, a rebalance or a stop commits only the records that the route committed, not the last processed + * record: the route may still hold the records it processed after that, for example in an aggregation group that is not + * complete (CAMEL-26993). A {@link MockConsumer} instead of a broker. + */ +class KafkaManualCommitRevokeTest extends CamelTestSupport { + + private static final String TOPIC = "manual-commit-revoke"; + private static final TopicPartition PARTITION = new TopicPartition(TOPIC, 0); + + private final RevokingMockConsumer mockConsumer = new RevokingMockConsumer(); + + @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 + public void configureTest(TestExecutionConfiguration testExecutionConfiguration) { + testExecutionConfiguration.withUseRouteBuilder(false); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testRevokeCommitsOnlyWhatTheRouteCommitted(boolean async) throws Exception { + startRouteAndConsumeThreeRecords(async); + + // the partition is revoked: the records b and c, which the route did not commit, are not committed + mockConsumer.schedulePollTask(() -> mockConsumer.rebalance(List.of())); + await().atMost(10, TimeUnit.SECONDS).until(() -> mockConsumer.assignment().isEmpty()); + assertEquals(1, lastCommittedOffset()); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testStopCommitsOnlyWhatTheRouteCommitted(boolean async) throws Exception { + startRouteAndConsumeThreeRecords(async); + + // the route stops: the consumer unsubscribes, which revokes the partition + context.getRouteController().stopRoute("kafka"); + assertTrue(mockConsumer.revokedOnUnsubscribe.get(), "the stop must revoke the partition"); + assertEquals(1, lastCommittedOffset()); + } + + private void startRouteAndConsumeThreeRecords(boolean async) throws Exception { + mockConsumer.updateBeginningOffsets(Map.of(PARTITION, 0L)); + mockConsumer.schedulePollTask(() -> mockConsumer.rebalance(List.of(PARTITION))); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + String factoryClass = async + ? DefaultKafkaManualAsyncCommitFactory.class.getName() + : DefaultKafkaManualCommitFactory.class.getName(); + from("kafka:" + TOPIC + "?brokers=localhost:9092&kafkaClientFactory=#mockFactory&groupId=test" + + "&autoCommitEnable=false&allowManualCommit=true&kafkaManualCommitFactory=#class:" + factoryClass) + .routeId("kafka") + // the route commits the record a, and holds the records b and c (as an aggregator would) + .filter(body().isEqualTo("a")) + .process(KafkaManualCommitRevokeTest::commit) + .end() + .to("mock:result"); + } + }); + context.start(); + + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("a", "b", "c"); + + await().atMost(10, TimeUnit.SECONDS).until(() -> mockConsumer.assignment().contains(PARTITION)); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 0, null, "a")); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 1, null, "b")); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 2, null, "c")); + + MockEndpoint.assertIsSatisfied(context); + // an asynchronous commit is done by the consumer thread before its next poll + await().atMost(10, TimeUnit.SECONDS).until(() -> lastCommittedOffset() == 1); + } + + private static void commit(Exchange exchange) { + exchange.getMessage().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class).commit(); + } + + /** + * The last offset committed on the partition, also when it is no longer assigned (unlike + * {@link MockConsumer#committed(java.util.Set)}). + */ + private long lastCommittedOffset() { + long offset = -1; + for (Map<TopicPartition, OffsetAndMetadata> offsets : mockConsumer.commits) { + OffsetAndMetadata committed = offsets.get(PARTITION); + if (committed != null) { + offset = committed.offset(); + } + } + return offset; + } + + /** + * Records the commits (MockConsumer#commitSync calls commitAsync), and revokes the assigned partitions on + * unsubscribe, as the Kafka consumer does. + */ + private static final class RevokingMockConsumer extends MockConsumer<Object, Object> { + private final List<Map<TopicPartition, OffsetAndMetadata>> commits = new CopyOnWriteArrayList<>(); + private final AtomicBoolean revokedOnUnsubscribe = new AtomicBoolean(); + + RevokingMockConsumer() { + super("earliest"); + } + + @Override + public synchronized void commitAsync(Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) { + commits.add(Map.copyOf(offsets)); + super.commitAsync(offsets, callback); + } + + @Override + public synchronized void unsubscribe() { + if (!assignment().isEmpty()) { + rebalance(List.of()); + revokedOnUnsubscribe.set(true); + } + super.unsubscribe(); + } + } +} diff --git a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessorTest.java b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessorTest.java index c44a06ae7191..c86a2980855d 100644 --- a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessorTest.java +++ b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/consumer/support/streaming/KafkaRecordStreamingProcessorTest.java @@ -98,6 +98,28 @@ class KafkaRecordStreamingProcessorTest { verify(commitManager).recordOffset(topicPartition, 42L); } + @Test + void breakOnFirstErrorWithManualCommitCommitsTheProcessedRecords() throws Exception { + // the records before the failed one are committed, whether the route committed them or not, so the failed one + // is polled again + when(configuration.isAllowManualCommit()).thenReturn(true); + when(configuration.isBreakOnFirstError()).thenReturn(true); + when(commitManager.getManualCommit(any(), any(), any())).thenReturn(mock(KafkaManualCommit.class)); + Exchange exchange = new DefaultExchange(new DefaultCamelContext()); + when(kafkaConsumer.createExchange(false)).thenReturn(exchange); + doAnswer(invocation -> { + throw new IllegalStateException("Simulated failure"); + }).when(processor).process(any(Exchange.class)); + + KafkaRecordStreamingProcessor proc = new KafkaRecordStreamingProcessor(configuration, processor, commitManager); + ProcessingResult result = proc.processExchange(kafkaConsumer, topicPartition, false, false, record); + + assertTrue(result.isBreakOnErrorHit()); + verify(commitManager).commitProcessedOffset(topicPartition); + verify(commitManager, never()).commit(any(TopicPartition.class)); + verify(commitManager, never()).recordOffset(topicPartition, 42L); + } + @Test void recordSkippedAfterAHandledFailureIsNotReportedAsRolledBackWhenStillRollbackOnly() throws Exception { // a doCatch handled the failure of a send, the transaction synchronization aborted the output and committed the @@ -111,6 +133,7 @@ class KafkaRecordStreamingProcessorTest { assertFalse(result.isFailed()); verify(commitManager).recordOffset(topicPartition, 42L); verify(commitManager, never()).commit(any(TopicPartition.class)); + verify(commitManager, never()).commitProcessedOffset(any(TopicPartition.class)); } @Test diff --git a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerAsyncManualCommitIT.java b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerAsyncManualCommitIT.java index 02bf9e90c9a4..7661d9796baa 100644 --- a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerAsyncManualCommitIT.java +++ b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerAsyncManualCommitIT.java @@ -18,6 +18,8 @@ package org.apache.camel.component.kafka.integration; import java.util.List; import java.util.Properties; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.camel.BindToRegistry; import org.apache.camel.CamelContext; @@ -42,6 +44,7 @@ import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -51,6 +54,9 @@ public class KafkaConsumerAsyncManualCommitIT extends BaseKafkaTestSupport { private static final Logger LOG = LoggerFactory.getLogger(KafkaConsumerAsyncManualCommitIT.class); + // the records the route committed: the aggregator commits them on its own thread, after the mock received them + private static final AtomicInteger COMMITTED = new AtomicInteger(); + @BindToRegistry("testFactory") private final KafkaManualCommitFactory manualCommitFactory = new DefaultKafkaManualAsyncCommitFactory(); @@ -99,6 +105,7 @@ public class KafkaConsumerAsyncManualCommitIT extends BaseKafkaTestSupport { try { manual.commit(); + COMMITTED.incrementAndGet(); } catch (Exception commitException) { LOG.error("Failed to commit: {}", commitException.getMessage(), commitException); failCount++; @@ -138,6 +145,10 @@ public class KafkaConsumerAsyncManualCommitIT extends BaseKafkaTestSupport { void kafkaManualCommit() throws Exception { MockEndpoint to = contextExtension.getMockEndpoint(KafkaTestUtil.MOCK_RESULT); + // the route commits the records once the aggregator completed its group: a stop before that does not commit + // them, so they would be consumed again after the restart + await().atMost(10, TimeUnit.SECONDS).until(() -> COMMITTED.get() >= 5); + // Second step: We shut down our route, we expect nothing will be recovered by our route context.getRouteController().stopRoute("foo"); to.expectedMessageCount(0); diff --git a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/commit/KafkaConsumerManualCommitStopIT.java b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/commit/KafkaConsumerManualCommitStopIT.java new file mode 100644 index 000000000000..ba68e9c2a1b7 --- /dev/null +++ b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/commit/KafkaConsumerManualCommitStopIT.java @@ -0,0 +1,79 @@ +/* + * 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.integration.commit; + +import java.util.Set; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.kafka.KafkaConstants; +import org.apache.camel.component.kafka.consumer.DefaultKafkaManualAsyncCommitFactory; +import org.apache.camel.component.kafka.consumer.KafkaManualCommit; +import org.apache.camel.component.kafka.integration.common.KafkaTestUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * With manual commits, a stop commits only the records that the route committed: the records that the route processed + * but did not commit (as an aggregator holds the records of a group that is not complete) are consumed again after the + * restart (CAMEL-26993). + */ +public class KafkaConsumerManualCommitStopIT extends BaseManualCommitTestSupport { + + public static final String TOPIC = "testManualCommitStopTest"; + + private static final Set<String> COMMITTED = Set.of("message-0", "message-1", "message-2"); + + @AfterEach + public void after() { + cleanupKafka(TOPIC); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("kafka:" + TOPIC + + "?groupId=KafkaConsumerManualCommitStopIT&pollTimeoutMs=1000&autoCommitEnable=false" + + "&allowManualCommit=true&autoOffsetReset=earliest&kafkaManualCommitFactory=#class:" + + DefaultKafkaManualAsyncCommitFactory.class.getName()) + .routeId("foo") + .to(KafkaTestUtil.MOCK_RESULT) + // the route commits the first three records only + .filter(e -> COMMITTED.contains(e.getMessage().getBody(String.class))) + .process(e -> e.getMessage().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class) + .commit()); + } + }; + } + + @Test + public void testStopCommitsOnlyWhatTheRouteCommitted() throws Exception { + to.expectedBodiesReceived("message-0", "message-1", "message-2", "message-3", "message-4"); + sendRecords(0, 5, TOPIC); + to.assertIsSatisfied(10000); + to.reset(); + + contextExtension.getContext().getRouteController().stopRoute("foo"); + sendRecords(5, 8, TOPIC); + + // the records 3 and 4, which the route did not commit, are consumed again + to.expectedBodiesReceived("message-3", "message-4", "message-5", "message-6", "message-7"); + contextExtension.getContext().getRouteController().startRoute("foo"); + to.assertIsSatisfied(30000); + } +} 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 b4fbea392414..94dedfda4a35 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 @@ -1144,6 +1144,21 @@ consumer thread (for example, after an aggregator). A commit called after the partition was revoked from the consumer is not made. It would move back the offset that the new owner of the partition committed. +=== camel-kafka - with manual commits, a rebalance or a stop commits only what the route committed + +With `allowManualCommit=true` and the `DefaultKafkaManualCommitFactory` or the `DefaultKafkaManualAsyncCommitFactory`, +a partition that is revoked from the consumer (in a rebalance, or when the consumer stops) is now committed up to the +last record that the route committed with `KafkaManualCommit.commit()`. Before, it was committed up to the last record +that the route processed, also when the route had not committed it, for example a record held in an aggregation group +that is not complete. Such a record was not consumed again, and was lost when the application stopped before the group +completed. Now the records that the route did not commit are consumed again after a rebalance or a restart, by this +consumer or another one of the group, so they may be processed more than once. This includes the records that the +route commits only after the partition was revoked, for example when an aggregator completes its group after the +Kafka route was stopped: that commit is not made. The same applies when a pausable +consumer pauses after a failed record: the failed record is no longer committed. `breakOnFirstError` is unchanged: it +still commits the records before the failed one, whether the route committed them or not, so that the failed one is +polled again. + === camel-kafka - each consumer of consumersCount gets its own group instance id With `groupInstanceId` (or `additionalProperties.group.instance.id`) and `consumersCount` greater than 1, the consumer
