aliehsaeedii commented on code in PR #24002:
URL: https://github.com/apache/kafka/pull/24002#discussion_r4540249530


##########
streams/src/test/java/org/apache/kafka/streams/processor/internals/StreamTaskTest.java:
##########
@@ -471,6 +471,28 @@ public void 
shouldResetOffsetsToLastCommittedForSpecifiedPartitions() {
         verify(resetter).accept(Collections.emptySet());
     }
 
+    @Test
+    public void shouldReturnPartitionsForOffsetResetUntilOffsetsAreReset() {

Review Comment:
   This has the same setup and flow as 
`shouldResetOffsetsToLastCommittedForSpecifiedPartitions` above. Wondering if 
it makes sense to add the two `partitionsForOffsetReset()` assertions to that 
test instead? Up to you.



##########
streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/CommitTimeoutOffsetResetIntegrationTest.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.kafka.streams.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.serialization.Serdes;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.streams.GroupProtocol;
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.kafka.streams.StreamsBuilder;
+import org.apache.kafka.streams.StreamsConfig;
+import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
+import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
+import org.apache.kafka.streams.kstream.Consumed;
+import org.apache.kafka.streams.kstream.Materialized;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.apache.kafka.streams.state.QueryableStoreTypes;
+import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
+import org.apache.kafka.test.TestUtils;
+import org.apache.kafka.test.faultproxy.FaultRule;
+import org.apache.kafka.test.faultproxy.KafkaProtocolFaultProxy;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.Timeout;
+
+import java.time.Duration;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.apache.kafka.streams.utils.TestUtils.safeUniqueTestName;
+import static org.junit.jupiter.api.Assertions.assertAll;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A commit whose EndTxn outlives {@code max.block.ms} corrupts the task. It 
is closed dirty, which drops the records it
+ * fetched but did not process yet, and revived with its input partitions 
marked to be reset to the committed offsets.
+ * The rebalance enforced because of the corruption completes before the 
revived task is initialized, so the revived
+ * task is closed and replaced by a new one, which has to do that reset. 
Otherwise the new task starts from the
+ * consumer position, and the next commit moves the input offset past the 
dropped records, which never reach the store.
+ */
+@Tag("integration")
+@Timeout(600)
+public class CommitTimeoutOffsetResetIntegrationTest {
+
+    private static final int NUM_RECORDS = 1_500;
+    private static final String INPUT_TOPIC = "input";
+    private static final TopicPartition INPUT_PARTITION = new 
TopicPartition(INPUT_TOPIC, 0);
+    private static final String STORE = "store";
+    private static final String CLIENT_ID = "instance";
+    private static final String PRODUCER_CLIENT_ID = CLIENT_ID + 
"-StreamThread-1-producer";
+    private static final long PRODUCER_MAX_BLOCK_MS = 2_000L;
+    // outlasts the commit, but not the retry of the pending commit in 
TaskManager#handleCorruption, so the transaction
+    // commits and the producer is usable again, as when the transaction 
coordinator becomes reachable again
+    private static final Duration END_TXN_DELAY = Duration.ofMillis(3 * 
PRODUCER_MAX_BLOCK_MS / 2);
+    // slow enough that the commit lands while most of the fetched records are 
still buffered in the task
+    private static final long PROCESSING_DELAY_MS = 2L;
+    private static final long WAIT_MS = 120_000L;
+
+    private EmbeddedKafkaCluster cluster;
+    private KafkaProtocolFaultProxy proxy;
+    private Admin admin;
+    private KafkaStreams streams;
+    private String appId;
+
+    @BeforeEach
+    public void setUp(final TestInfo testInfo) throws Exception {
+        appId = "commit-timeout-offset-reset-" + safeUniqueTestName(testInfo);
+        cluster = new EmbeddedKafkaCluster(1);
+        cluster.start();
+        cluster.createTopic(INPUT_TOPIC, 1, 1);
+        proxy = KafkaProtocolFaultProxy.inFrontOf(cluster.bootstrapServers());
+        admin = cluster.createAdminClient();
+    }
+
+    @AfterEach
+    public void tearDown() {
+        if (streams != null) {
+            streams.close(Duration.ofSeconds(30));
+        }
+        if (admin != null) {
+            admin.close();
+        }
+        if (proxy != null) {
+            proxy.close();
+        }
+        cluster.stop();
+    }
+
+    @Test
+    public void 
shouldNotSkipInputRecordsIfRevivedTaskIsReplacedBeforeInitialization() throws 
Exception {
+        // all input is there before the first poll, so the first commit 
happens while most of it is still buffered
+        produceUniqueKeys();
+        final FaultRule commitTimeout =
+            proxy.delayOn(ApiKeys.END_TXN, 
END_TXN_DELAY).forClient(PRODUCER_CLIENT_ID).once();
+
+        streams = streams();
+        final AtomicInteger rebalances = new AtomicInteger();
+        streams.setStateListener((newState, oldState) -> {
+            if (newState == KafkaStreams.State.REBALANCING) {
+                rebalances.incrementAndGet();
+            }
+        });
+        IntegrationTestUtils.startApplicationAndWaitUntilRunning(streams);
+
+        TestUtils.waitForCondition(
+            () -> committedInputOffset() == NUM_RECORDS,
+            WAIT_MS,
+            "the input offset was never committed up to the end of the " + 
NUM_RECORDS + " input records"
+        );
+        final int storedKeys = countStoredKeys();
+
+        assertAll(

Review Comment:
   None of these checks shows that the revived task was replaced before it was 
initialized. If the rebalance takes longer than one poll, the revived task 
initializes first and does the reset itself, so this test passes even without 
the fix. Could you assert the new "replaces a revived task" log line, for 
example with `LogCaptureAppender`?



##########
streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java:
##########
@@ -517,6 +541,10 @@ private void handleTasksPendingInitialization() {
         final Set<Task> tasksToCloseDirty = new 
TreeSet<>(Comparator.comparing(Task::id));
 
         for (final Task task : tasks.drainPendingTasksToInit()) {
+            // a revived task seeks its input partitions back to the committed 
offsets only after it is initialized,
+            // so remember them, otherwise the task created in its place 
starts from the current consumer position
+            // and skips the records the revived task dropped when it was 
closed dirty
+            
partitionsPendingOffsetReset.addAll(task.partitionsForOffsetReset());

Review Comment:
   This also covers the revocation path: if the commit in `handleRevocation` 
fails, retained tasks are closed dirty and revived, and `onAssignment` closes 
them here in the same rebalance. That path has no timing window and hits ALOS 
too (the `TimeoutException` branch). Could you add a unit test for it?



##########
streams/src/test/java/org/apache/kafka/streams/processor/internals/TaskManagerTest.java:
##########
@@ -2409,6 +2411,42 @@ public void shouldReviveCorruptTasks() {
         verify(consumer, never()).commitSync(emptyMap());
     }
 
+    @Test
+    public void 
shouldResetOffsetsInNewTaskIfRevivedTaskIsClosedOnAssignmentBeforeInitialization()
 {
+        final StreamTask revivedTask = statefulTask(taskId00, 
taskId00ChangelogPartitions)
+            .withInputPartitions(taskId00Partitions)
+            .build();
+        final AtomicReference<State> revivedTaskState = new 
AtomicReference<>(State.RUNNING);
+        when(revivedTask.state()).thenAnswer(invocation -> 
revivedTaskState.get());
+        doAnswer(invocation -> {
+            revivedTaskState.set(State.SUSPENDED);
+            return null;
+        }).when(revivedTask).suspend();
+        final StreamTask newTask = statefulTask(taskId00, 
taskId00ChangelogPartitions)
+            .withInputPartitions(taskId00Partitions)
+            .inState(State.CREATED)
+            .build();
+        final Tasks taskRegistry = new Tasks(new LogContext());
+        taskRegistry.addTask(revivedTask);
+        
when(activeTaskCreator.streamsProducer()).thenReturn(mock(StreamsProducer.class));
+        when(activeTaskCreator.createTasks(consumer, 
taskId00Assignment)).thenReturn(singletonList(newTask));
+        when(consumer.assignment()).thenReturn(taskId00Partitions);
+        final TaskManager taskManager = 
setUpTaskManager(ProcessingMode.EXACTLY_ONCE_V2, taskRegistry);
+
+        // the corrupted task is closed dirty, which drops its buffered 
records, and revived with its input
+        // partitions marked to be reset to the committed offsets once it is 
initialized again
+        taskManager.handleCorruption(Set.of(taskId00));
+        verify(revivedTask).addPartitionsForOffsetReset(taskId00Partitions);
+        
when(revivedTask.partitionsForOffsetReset()).thenReturn(taskId00Partitions);
+
+        // the rebalance triggered by the corruption completes before the 
revived task is initialized
+        taskManager.handleAssignment(taskId00Assignment, emptyMap());
+
+        verify(revivedTask).closeClean();
+        verify(newTask).addPartitionsForOffsetReset(taskId00Partitions);

Review Comment:
   Only the happy path is tested. Nothing covers a pending partition that is 
filtered out (not in `consumer.assignment()`, or not an input of the new task), 
or the final `clear()`. A second `handleAssignment` that checks no reset is 
handed over again would pin the `clear()`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to