8000 fix(inkless:switch): rebuild a follower below the seal when the leader's local log starts past it [KC-872] by giuseppelillo · Pull Request #905 · aiven/inkless · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions core/src/main/java/kafka/server/TierStateMachine.java
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,13 @@ private Long buildRemoteLogAuxState(TopicPartition topicPartition,
// will have the same epoch.
if (epochForLeaderLocalLogStartOffset == 0) {
targetEpoch = epochForLeaderLocalLogStartOffset;
} else if (seal >= 0 && leaderLocalLogStartOffset > seal) {
// Inkless: the record before the local log start of the source is at or past the classic-to-diskless seal.
// Consolidation writes every record from the seal on in one leader epoch, so that record is in the epoch
// of the local log start. A classic leader answers OffsetsForLeaderEpoch for the epoch before it with the
// diskless end offset, which a consumer needs to validate its position. No remote segment holds that
// epoch, so the lookup below would fail on every retry.
targetEpoch = epochForLeaderLocalLogStartOffset;
} else {
// Fetch the earlier epoch/end-offset(exclusive) from the leader.
OffsetForLeaderEpochResponseData.EpochEndOffset earlierEpochEndOffset = fetchEarlierEpochEndOffset(epochForLeaderLocalLogStartOffset, topicPartition, currentLeaderEpoch);
Expand Down
9 changes: 8 additions & 1 deletion core/src/main/scala/kafka/server/ReplicaManager.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2945,9 +2945,16 @@ class ReplicaManager(val config: KafkaConfig,
case Right(partition) =>
try {
// Use the classic follower-read validation without returning any records.
// In phase 2, local retention can move the local log start of the leader past the seal.
// A leader that holds no local record from there on, such as an idle one, can't read at
// the seal. A follower that rebuilt its log up to that offset would get
// OFFSET_OUT_OF_RANGE on every fetch and never hand off to consolidation.
val validationOffset = partition.log
.map(log => math.max(classicToDisklessStartOffset, log.localLogStartOffset))
.getOrElse(classicToDisklessStartOffset)
val fetchAtSeal = new PartitionData(
fetchPartitionData.topicId,
classicToDisklessStartOffset,
validationOffset,
fetchPartitionData.logStartOffset,
0,
fetchPartitionData.currentLeaderEpoch,
< 10BC8 svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-fold-down"> Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.apache.kafka.clients.admin.ConfigEntry;
import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.ListOffsetsResult;
import org.apache.kafka.clients.admin.NewPartitionReassignment;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.admin.TransactionDescription;
Expand Down Expand Up @@ -61,10 +62,12 @@
import org.apache.kafka.server.IntegrationTestUtils;
import org.apache.kafka.server.config.ReplicationConfigs;
import org.apache.kafka.server.config.ServerConfigs;
import org.apache.kafka.server.config.ServerLogConfigs;
import org.apache.kafka.server.log.remote.metadata.storage.TopicBasedRemoteLogMetadataManager;
import org.apache.kafka.server.log.remote.metadata.storage.TopicBasedRemoteLogMetadataManagerConfig;
import org.apache.kafka.server.log.remote.storage.RemoteLogManagerConfig;
import org.apache.kafka.storage.internals.log.UnifiedLog;
import org.apache.kafka.test.TestUtils;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
Expand All @@ -74,6 +77,7 @@
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.junit.jupiter.Container;
Expand Down Expand Up @@ -192,6 +196,7 @@ public void setup(final TestInfo testInfo) throws Exception {
.setConfigProp(ServerConfigs.DISKLESS_ALLOW_FROM_CLASSIC_ENABLE_CONFIG, "true")
.setConfigProp(RemoteLogManagerConfig.REMOTE_LOG_STORAGE_SYSTEM_ENABLE_PROP, "true")
.setConfigProp(RemoteLogManagerConfig.REMOTE_LOG_MANAGER_TASK_INTERVAL_MS_PROP, "5000")
.setConfigProp(ServerLogConfigs.LOG_CLEANUP_INTERVAL_MS_CONFIG, "500")
.setConfigProp(RemoteLogManagerConfig.REMOTE_LOG_MANAGER_FOLLOWER_THREAD_POOL_SIZE_PROP, "4")
.setConfigProp(RemoteLogManagerConfig.REMOTE_LOG_METADATA_MANAGER_CLASS_NAME_PROP, TopicBasedRemoteLogMetadataManager.class.getName())
.setConfigProp(RemoteLogManagerConfig.REMOTE_LOG_METADATA_MANAGER_LISTENER_NAME_PROP, "EXTERNAL")
Expand Down Expand Up @@ -401,6 +406,85 @@ public void testConsumerResumesFromCommittedOffsetPastSeal() throws Exception {
}
}

// Local retention deletes the consolidated segments that the leader uploaded, so the local log of the leader
// starts past the seal. A replica that a reassignment adds starts below the seal, and it rebuilds its log from
// the consolidated segment in remote storage that ends before the local log start of the leader. On an idle
// leader, local retention also rolls the last segment, and the broker uploads and deletes it. The local log of
// the leader is then empty.
@ParameterizedTest(name = "idleLeader={0}")
@ValueSource(booleans = {false, true})
public void testAddedReplicaRebuildsWhenLeaderLocalLogStartsPastSeal(final boolean idleLeader) throws Exception {
final String topic = "switch-added-replica-" + UUID.randomUUID().toString().substring(0, 8);
final TopicPartition tp = new TopicPartition(topic, 0);
final int classicRecords = 300;
final int disklessRecords = 2500;
final byte[] value = new byte[1500];

try (Admin admin = AdminClient.create(baseClientConfigs());
Producer<byte[], byte[]> producer = new KafkaProducer<>(producerConfigs())) {
// Consolidation fetches one batch at a time unless a segment is larger than the largest batch.
admin.createTopics(List.of(new NewTopic(topic, Map.of(0, List.of(0, 1))).configs(Map.of(
TopicConfig.DISKLESS_ENABLE_CONFIG, "false",
TopicConfig.SEGMENT_BYTES_CONFIG, "1048576",
TopicConfig.MAX_MESSAGE_BYTES_CONFIG, "262144")))).all().get(30, TimeUnit.SECONDS);
TopicMetadataProbe.awaitVisible(admin, topic);
for (int i = 0; i < classicRecords; i++) {
producer.send(new ProducerRecord<>(topic, 0, null, value));
}
producer.flush();
alterTopicConfigWithIncrementalAlterConfigs(admin, topic, Map.of(TopicConfig.DISKLESS_ENABLE_CONFIG, "true"));
final long seal = waitForSealOffset(admin, topic, 0, offset -> offset >= 0);
assertEquals(classicRecords, seal);
waitForClassicPrefixInRemoteStorage(admin, topic);
for (int i = 0; i < disklessRecords; i++) {
producer.send(new ProducerRecord<>(topic, 0, null, value));
}
producer.flush();
final long endOffset = seal + disklessRecords;

final int leaderId = cluster.brokers().get(0).replicaManager().getPartitionOrException(tp).isLeader() ? 0 : 1;
final UnifiedLog leaderLog = cluster.brokers().get(leaderId).replicaManager().getLog(tp).get();
alterTopicConfigWithIncrementalAlterConfigs(admin, topic, Map.of(TopicConfig.LOCAL_LOG_RETENTION_MS_CONFIG, "1000"));
final long expectedLocalLogStart = idleLeader ? endOffset : seal + 1;
TestUtils.waitForCondition(() -> leaderLog.localLogStartOffset() >= expectedLocalLogStart, 240_000L,
() -> "Local retention didn't move the local log start of the leader to " + expectedLocalLogStart
+ ": it's " + leaderLog.localLogStartOffset() + ", and the log end offset is "
+ leaderLog.logEndOffset());

admin.alterPartitionReassignments(Map.of(tp, Optional.of(new NewPartitionReassignment(List.of(0, 1, 2)))))
.all().get(30, TimeUnit.SECONDS);
final ReplicaManager addedReplica = cluster.brokers().get(2).replicaManager();
// The classic fetcher rebuilds the log, and it evicts the partition when it hands off to consolidation.
TestUtils.waitForCondition(
() -> addedReplica.getLog(tp).isDefined() && addedReplica.getLog(tp).get().logEndOffset() >= seal
&& addedReplica.replicaFetcherManager().getFetcher(tp).isEmpty(),
60_000L,
() -> "The added replica didn't rebuild its log up to the seal " + seal + " and hand off to "
+ "consolidation: its log end offset is "
+ (addedReplica.getLog(tp).isDefined() ? addedReplica.getLog(tp).get().logEndOffset() : -1)
+ ", and the classic fetcher " + (addedReplica.replicaFetcherManager().getFetcher(tp).isEmpty()
? "doesn't hold" : "still holds") + " the partition");

// Broker 2 is in az3. The metadata routing sends a consumer in that zone to the added replica.
final Map<String, Object> consumerConfigs = baseConsumerConfigs();
consumerConfigs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
consumerConfigs.put(ConsumerConfig.CLIENT_ID_CONFIG, "added-replica,diskless_az=az3");
try (Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(consumerConfigs)) {
consumer.assign(List.of(tp));
consumer.seek(tp, 0L);
long nextOffset = 0;
final long deadline = System.currentTimeMillis() + Duration.ofSeconds(60).toMillis();
while (nextOffset < endOffset && System.currentTimeMillis() < deadline) {
for (ConsumerRecord<byte[], byte[]> record : consumer.poll(Duration.ofMillis(500))) {
assertEquals(nextOffset, record.offset());
nextOffset++;
}
}
assertEquals(endOffset, nextOffset, "The consumer in az3 didn't read every record");
}
}
}

private Map<String, Object> baseClientConfigs() {
final Map<String, Object> configs = new HashMap<>();
configs.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, cluster.bootstrapServers());
Expand Down
8
Original file line number Diff line number Diff line change
Expand Up @@ -9113,6 +9113,68 @@ class ReplicaManagerInklessTest {
.fetchIndex(lastClassicSegment, RemoteStorageManager.IndexType.PRODUCER_SNAPSHOT)
}

// Local retention moved the local log start of a phase 2 leader past the seal. A follower below the seal rebuilds
// from the consolidated segment that ends before that offset. The leader answers OffsetsForLeaderEpoch for the
// epoch before the diskless leader epoch with the diskless end offset, and no remote segment holds that epoch.
@Test
def testTierStateMachineRebuildsFromSourceWhoseLocalLogStartsPastTheSeal(): Unit = {
val tp = new TopicPartition("switched-consolidating-topic", 0)
val sealOffset = 100L
val sourceLocalLogStartOffset = 250L
val disklessLeaderEpoch = 5
val lastClassicLeaderEpoch = 2
val epochs = Seq(new EpochEntry(0, 0L), new EpochEntry(lastClassicLeaderEpoch, 80L),
new EpochEntry(disklessLeaderEpoch, sealOffset))
val tip = new TopicIdPartition(Uuid.randomUuid(), tp)
val consolidatedSegment = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(tip, Uuid.randomUuid()), 180L,
sourceLocalLogStartOffset - 1, -1L, 0, 0L, 1024, Optional.empty(), RemoteLogSegmentState.COPY_SEGMENT_FINISHED,
util.Map.of[Integer, java.lang.Long](disklessLeaderEpoch, 180L))
val rsm = mock(classOf[RemoteStorageManager])
when(rsm.fetchIndex(consolidatedSegment, RemoteStorageManager.IndexType.LEADER_EPOCH))
.thenReturn(new ByteArrayInputStream(
(Seq("0", epochs.size.toString) ++ epochs.map(entry => s"${entry.epoch} ${entry.startOffset}"))
.mkString("", "\n", "\n").getBytes(StandardCharsets.UTF_8)))
when(rsm.fetchIndex(consolidatedSegment, RemoteStorageManager.IndexType.PRODUCER_SNAPSHOT))
.thenReturn(new ByteArrayInputStream(Array.emptyByteArray))
val rlm = mock(classOf[RemoteLogManager])
when(rlm.isPartitionReady(tp)).thenReturn(true)
when(rlm.storageManager()).thenReturn(rsm)
when(rlm.fetchRemoteLogSegmentMetadata(tp, disklessLeaderEpoch, sourceLocalLogStartOffset - 1))
.thenReturn(Optional.of(consolidatedSegment))
val epochCache = mock(classOf[LeaderEpochFileCache])
val log = mock(classOf[UnifiedLog])
when(log.remoteLogEnabled()).thenReturn(true)
when(log.leaderEpochCache).thenReturn(epochCache)
when(log.producerStateManager).thenReturn(mock(classOf[ProducerStateManager]))
when(log.dir).thenReturn(TestUtils.tempDir())
val partition = mock(classOf[Partition])
val replicaManager = mock(classOf[ReplicaManager])
when(replicaManager.brokerTopicStats).thenReturn(new BrokerTopicStats(true))
when(replicaManager.localLogOrException(tp)).thenReturn(log)
when(replicaManager.remoteLogManager).thenReturn(Some(rlm))
when(replicaManager.classicToDisklessStartOffset(tp)).thenReturn(sealOffset)
when(replicaManager.lastClassicLeaderEpoch(tp)).thenReturn(lastClassicLeaderEpoch)
when(replicaManager.getPartitionOrException(tp)).thenReturn(partition)
val source = mock(classOf[LeaderEndPoint])
when(source.fetchLatestOffset(tp, disklessLeaderEpoch)).thenReturn(new OffsetAndEpoch(400L, disklessLeaderEpoch))
// The answer of `ReplicaManager.lastOffsetForLeaderEpoch` on a phase 2 leader: the requested epoch and the
// diskless end offset.
when(source.fetchEpochEndOffsets(any())).thenReturn(util.Map.of(tp, new EpochEndOffset()
.setPartition(tp.partition)
.setErrorCode(Errors.NONE.code)
.setLeaderEpoch(disklessLeaderEpoch - 1)
.setEndOffset(400L)))

val fetchState = new TierStateMachine(source, replicaManager, false).start(tp, Optional.empty(),
disklessLeaderEpoch, new OffsetAndEpoch(sourceLocalLogStartOffset, disklessLeaderEpoch), 0L)

assertEquals(sourceLocalLogStartOffset, fetchState.fetchOffset)
verify(rlm, never()).fetchRemoteLogSegmentMetadata(tp, disklessLeaderEpoch - 1, sourceLocalLogStartOffset - 1)
verify(partition).truncateFullyAndStartAt(sourceLocalLogStartOffset, false, Optional.of[java.lang.Long](0L))
verify(log).maybeIncrementLocalLogStartOffset(ArgumentMatchers.eq(sourceLocalLogStartOffset), any())
verify(epochCache).assign(util.List.of(epochs.toSeq: _*))
}

// The classic fetcher thread deletes the prefix when it evicts a partition. If it took
// replicaStateChangeLock through markPartitionOffline, it would deadlock with applyDelta, which
// holds that lock while it shuts down idle fetcher threads.
Expand Down Expand Up @@ -11357,6 +11419,39 @@ class ReplicaManagerInklessTest {
}
}

// Local retention deleted every local segment of an idle phase 2 leader, so its local log is an empty active
// segment past the seal, and a read at the seal is out of range. The leader validates the fetch of a follower
// that rebuilt its log up to that offset at its local log start.
@Test
def testFollowerFetchPastSealSucceedsWhenLeaderLocalLogStartsPastSeal(): Unit = {
val followerId = 2
val sealOffset = 5L
val localLogStartOffset = 20L
val replicaManager = createReplicaManager(
List(disklessTopicPartition.topic()),
topicIdMapping = Map(disklessTopicPartition.topic() -> disklessTopicPartition.topicId()),
disklessManagedReplicasEnabled = true,
)
try {
val partition = setupSwitchedLeaderWithOutOfSyncFollower(
replicaManager, disklessTopicPartition, followerId, sealOffset, followerInIsr = true)
partition.truncateFullyAndStartAt(localLogStartOffset, isFuture = false, Optional.of[java.lang.Long](0L))
partition.localLogOrException.maybeIncrementLocalLogStartOffset(localLogStartOffset,
LogStartOffsetIncrementReason.LeaderOffsetIncremented)
assertEquals(localLogStartOffset, partition.localLogOrException.localLogStartOffset)
assertEquals(localLogStartOffset, partition.localLogOrException.logEndOffset)

val data = fetchFollowerAtSeal(replicaManager, disklessTopicPartition, followerId, sealOffset,
Optional.of(partition.getLeaderEpoch), fetchOffset = Some(localLogStartOffset))

assertEquals(Errors.NONE, data.error)
assertEquals(MemoryRecords.EMPTY, data.records)
assertEquals(sealOffset, data.highWatermark)
} finally {
replicaManager.shutdown(checkpointHW = false)
}
}

@Test
def testFollowerFetchAtSealReturnsDivergingEpochAndSkipsIsrExpansion(): Unit = {
val followerId = 2
Expand Down
Loading
Loading
0