8000 fix(inkless:switch): return a diskless leader epoch with a diskless offset in ListOffsets [KC-865] by giuseppelillo · Pull Request #900 · 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
45 changes: 41 additions & 4 deletions core/src/main/scala/kafka/server/DisklessFetchOffsetRouter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,12 @@ class DisklessFetchOffsetRouter(
isConsolidatingPartition && (!hasCommittedSwitchOffset || hasCompleteClassicPrefix(topicPartition, classicToDisklessStartOffset))
val allowFromFollower = switchedAllowsFollower || consolidatingAllowsFollower
val isFollowerRequest = replicaId >= 0
val disklessLeaderEpoch = inklessMetadataView.getDisklessLeaderEpoch(topicPartition)

def classicLookup(): ListOffsetsPartitionStatus = classicFetchOffset(topicPartition, partition, allowFromFollower)
def disklessLookup: Lookup = disklessLookupOnJob(job, topicPartition, partition)
def withLeaderEpoch(lookup: Lookup): Lookup =
withDisklessLeaderEpoch(lookup, classicToDisklessStartOffset, disklessLeaderEpoch)
def disklessLookup: Lookup = withLeaderEpoch(disklessLookupOnJob(job, topicPartition, partition))

if (switchPending && disklessManagedReplicasEnabled) {
// Case 3. A follower answers client requests only: a replica fetcher sends its request to the leader.
Expand Down Expand Up @@ -182,10 +185,10 @@ class DisklessFetchOffsetRouter(
recordTimestampLookupDeferral()
failedLookup(prefixNotSearchable(topicPartition, endBelowSeal.get, classicToDisklessStartOffset 8000 , version))
} else if (consolidationActive)
disklessLookupCheckingWalStart(onJob(), topicPartition, partition, startNow, classicToDisklessStartOffset,
() => searchableEnd(), version, recordTimestampLookupDeferral)
withLeaderEpoch(disklessLookupCheckingWalStart(onJob(), topicPartition, partition, startNow,
classicToDisklessStartOffset, () => searchableEnd(), version, recordTimestampLookupDeferral))
else
disklessLookupOnJob(onJob(), topicPartition, partition, startNow)
withLeaderEpoch(disklessLookupOnJob(onJob(), topicPartition, partition, startNow))
}
classicWithDisklessFallbackLookup(topicPartition, version, classicLookup _,
() => checkedDisklessLookup(() => job, startNow = false),
Expand Down Expand Up @@ -385,6 +388,40 @@ private[server] object DisklessFetchOffsetRouter {
new AsyncOffsetReadFutureHolder(job.cancelHandler(), checked)
}

/**
* Replaces the placeholder leader epoch of the control plane on a switched partition.
*
* A consumer that takes its position from `ListOffsets` validates it with `OffsetsForLeaderEpoch`. The broker
* treats an epoch below `initialDisklessLeaderEpoch` as a classic epoch and answers with an end offset at or
* below the seal, so the placeholder 0 on an offset past the seal makes the consumer truncate to the seal. An
* offset at or past the seal gets `disklessLeaderEpoch`, the epoch that a consumer fetch stamps on the same
* offsets. The broker doesn't know the classic epoch of an offset below the seal, so that offset gets no
* epoch, and the client skips the validation. The controller records `disklessLeaderEpoch` as a leader epoch
* of the partition, so it's never greater than the leader epoch in a metadata response from this broker.
*/
private def disklessResultWithLeaderEpoch(result: FileRecordsOrError,
classicToDisklessStartOffset: Long,
disklessLeaderEpoch: Int): FileRecordsOrError = {
if (classicToDisklessStartOffset < 0 ||
disklessLeaderEpoch == PartitionRegistration.NO_DISKLESS_LEADER_EPOCH ||
!result.hasTimestampAndOffset) {
result
} else {
val found = result.timestampAndOffset.get
val leaderEpoch =
if (found.offset >= classicToDisklessStartOffset) Optional.of[Integer](disklessLeaderEpoch)
else Optional.empty[Integer]()
new FileRecordsOrError(Optional.empty(),
Optional.of(new FileRecords.TimestampAndOffset(found.timestamp, found.offset, leaderEpoch)))
}
}

private def withDisklessLeaderEpoch(lookup: Lookup,
classicToDisklessStartOffset: Long,
disklessLeaderEpoch: Int): Lookup =
new AsyncOffsetReadFutureHolder(lookup.jobFuture, lookup.taskFuture.thenApply[FileRecordsOrError](
result => disklessResultWithLeaderEpoch(result, classicToDisklessStartOffset, disklessLeaderEpoch)))

private def failedLookup(result: FileRecordsOrError): Lookup =
new AsyncOffsetReadFutureHolder(NoOpCancel, CompletableFuture.completedFuture(result))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,17 @@
import org.apache.kafka.clients.admin.AlterDisklessSwitchOptions;
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.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.admin.TransactionDescription;
import org.apache.kafka.clients.admin.TransactionState;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
Expand Down Expand Up @@ -718,6 +721,61 @@ public void testElectedReplicaOutsideTheIsrRecoversAPhaseOnePartition() throws E
}
}

// A consumer validates a position and its leader epoch with OffsetsForLeaderEpoch. For a classic epoch, the end
// offset in the response is at or below the seal, so ListOffsets must return a diskless epoch with a diskless offset.
@Test
@Tag(BLOCKS_REMOTE_UPLOADS)
public void testConsumerKeepsAPositionFromListOffsetsOnASwitchedPartition() throws Exception {
final String topic = "switch-list-offsets-epoch-" + UUID.randomUUID().toString().substring(0, 8);
final TopicPartition tp = new TopicPartition(topic, 0);
try (Admin admin = AdminClient.create(baseClientConfigs())) {
admin.createTopics(List.of(new NewTopic(topic, 1, (short) 3)
.configs(Map.of(TopicConfig.DISKLESS_ENABLE_CONFIG, "false")))).all().get(30, TimeUnit.SECONDS);
TopicMetadataProbe.awaitVisible(admin, topic);
produceRecords(topic, 20);
alterTopicConfigWithIncrementalAlterConfigs(admin, topic, Map.of(TopicConfig.DISKLESS_ENABLE_CONFIG, "true"));
assertEquals(20L, waitForSealOffset(admin, topic, 0, offset -> offset >= 0));
produceRecords(topic, 30);

// Phase 1.
assertConsumerKeepsTheLatestPosition(admin, tp, 50L);

try (var s3Client = s3Container.getS3Client()) {
s3Client.createBucket(request -> request.bucket(tieredStorageBucket));
}
waitForClassicPrefixInRemoteStorage(admin, topic);

// Phase 2 set a new diskless leader epoch.
assertConsumerKeepsTheLatestPosition(admin, tp, 55L);
}
}

private void assertConsumerKeepsTheLatestPosition(final Admin admin,
final TopicPartition tp,
final long expectedLatest) throws Exception {
final ListOffsetsResult.ListOffsetsResultInfo latest = admin.listOffsets(Map.of(tp, OffsetSpec.latest()))
.partitionResult(tp).get(30, TimeUnit.SECONDS);
assertEquals(expectedLatest, latest.offset());
assertTrue(latest.leaderEpoch().isPresent(), "ListOffsets returned no leader epoch for a diskless offset");

final Map<String, Object> consumerConfigs = baseConsumerConfigs();
consumerConfigs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
try (Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(consumerConfigs)) {
consumer.assign(List.of(tp));
// librdkafka keeps the epoch of a ListOffsets reset. A Java client does the same with this seek.
consumer.seek(tp, new OffsetAndMetadata(latest.offset(), latest.leaderEpoch(), ""));
produceRecords(tp.topic(), 5);
final long deadline = System.currentTimeMillis() + Duration.ofSeconds(30).toMillis();
ConsumerRecords<byte[], byte[]> records = ConsumerRecords.empty();
while (records.isEmpty() && System.currentTimeMillis() < deadline) {
records = consumer.poll(Duration.ofMillis(500));
}
assertFalse(records.isEmpty(), "The consumer read no records");
assertEquals(latest.offset(), records.iterator().next().offset(),
"The consumer didn't start at the offset and leader epoch from ListOffsets");
}
}

private void waitForClassicPrefixInRemoteStorage(final Admin admin, final String topic) throws Exception {
final long deadline = System.currentTimeMillis() + Duration.ofSeconds(90).toMillis();
while (System.currentTimeMillis() < deadline) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,12 @@ class DisklessFetchOffsetRouterTest {
private val followerReplicaId = 1
private val localBrokerId = 0

private val inklessMetadataView: InklessMetadataView = mock(classOf[InklessMetadataView])
private val inklessMetadataView: InklessMetadataView = {
val m = mock(classOf[InklessMetadataView])
// Mockito answers 0 for an int, which is a valid epoch. A test that needs an epoch sets it.
when(m.getDisklessLeaderEpoch(any())).thenReturn(PartitionRegistration.NO_DISKLESS_LEADER_EPOCH)
m
}
private val purgatory: DelayedOperationPurgatory[DelayedRemoteListOffsets] =
mock(classOf[DelayedOperationPurgatory[DelayedRemoteListOffsets]])

Expand Down Expand Up @@ -990,4 +995,142 @@ class DisklessFetchOffsetRouterTest {
assertPrefixNotSearchable(status)
}

// ---------------------------------------------------------------------------
// Leader epoch of a diskless result. The control plane answers with the placeholder epoch 0.
// ---------------------------------------------------------------------------

private val seal = 100L
private val disklessLeaderEpoch = 3

private def switchedPartition(): Unit = {
when(inklessMetadataView.getClassicToDisklessStartOffset(tp)).thenReturn(seal)
when(inklessMetadataView.getDisklessLeaderEpoch(tp)).thenReturn(disklessLeaderEpoch)
}

private def assertResult(status: ListOffsetsPartitionStatus, offset: Long, leaderEpoch: Optional[Integer]): Unit = {
val result = resultOf(status)
assertFalse(result.hasException, s"unexpected error in $result")
assertEquals(offset, result.timestampAndOffset.get.offset)
assertEquals(leaderEpoch, result.timestampAndOffset.get.leaderEpoch)
}

@ParameterizedTest
@ValueSource(longs = Array(ListOffsetsRequest.LATEST_TIMESTAMP, ListOffsetsRequest.MAX_TIMESTAMP))
def switchedLatestAndMaxTimestampGetTheDisklessLeaderEpoch(timestamp: Long): Unit = {
switchedPartition()
disklessTaskFuture.complete(offsetResult(offset = 150L, leaderEpoch = 0))

val status = route(consolidatingRouter(), timestamp = timestamp)

assertResult(status, 150L, Optional.of(disklessLeaderEpoch))
assertTrue(classicCalls.isEmpty)
}

// A switched partition without diskless records answers LATEST with the seal.
@Test
def switchedLatestAtTheSealGetsTheDisklessLeaderEpoch(): Unit = {
switchedPartition()
disklessTaskFuture.complete(offsetResult(offset = seal, leaderEpoch = 0))

val status = route(consolidatingRouter(), timestamp = ListOffsetsRequest.LATEST_TIMESTAMP)

assertResult(status, seal, Optional.of(disklessLeaderEpoch))
}

// A partition that was empty at the switch has a seal of 0, so every offset is a diskless offset.
@Test
def switchedAtOffsetZeroLatestGetsTheDisklessLeaderEpoch(): Unit = {
when(inklessMetadataView.getClassicToDisklessStartOffset(tp)).thenReturn(0L)
when(inklessMetadataView.getDisklessLeaderEpoch(tp)).thenReturn(disklessLeaderEpoch)
disklessTaskFuture.complete(offsetResult(offset = 30L, leaderEpoch = 0))

val status = route(consolidatingRouter(), timestamp = ListOffsetsRequest.LATEST_TIMESTAMP)

assertResult(status, 30L, Optional.of(disklessLeaderEpoch))
}

@Test
def switchedSpecificTimestampPastTheSealGetsTheDisklessLeaderEpoch(): Unit = {
switchedPartition()
disklessTaskFuture.complete(offsetResult(offset = 150L, timestamp = 10150L, leaderEpoch = 0))
walStartFuture.complete(offsetResult(offset = seal))

val status = route(consolidatingRouter(), timestamp = 10150L, classicResult = syncNoMatch,
classicSearchableEnd = _ => seal)

assertResult(status, 150L, Optional.of(disklessLeaderEpoch))
verify(job).addWalStart(tp)
}

@Test
def switchedSpecificTimestampPastTheSealGetsTheDisklessLeaderEpochInPhase1(): Unit = {
switchedPartition()
when(inklessMetadataView.isClassicPrefixWaitingForUpload(tp)).thenReturn(true)
disklessTaskFuture.complete(offsetResult(offset = 150L, timestamp = 10150L, leaderEpoch = 0))

val status = route(consolidatingRouter(), timestamp = 10150L, classicResult = syncNoMatch,
classicSearchableEnd = _ => seal)

assertResult(status, 150L, Optional.of(disklessLeaderEpoch))
verify(job, never()).addWalStart(any())
}

// The control plane answers EARLIEST with the start of the remote tier, which can be a classic offset. The broker
// doesn't know its classic epoch.
@Test
def switchedEarliestBelowTheSealGetsNoLeaderEpoch(): Unit = {
switchedPartition()
disklessTaskFuture.complete(offsetResult(offset = 40L, leaderEpoch = 0))

val status = route(consolidatingRouter(), timestamp = ListOffsetsRequest.EARLIEST_TIMESTAMP)

assertResult(status, 40L, Optional.empty())
}

@Test
def switchedEarliestPastTheSealGetsTheDisklessLeaderEpoch(): Unit = {
switchedPartition()
disklessTaskFuture.complete(offsetResult(offset = 130L, leaderEpoch = 0))

val status = route(consolidatingRouter(), timestamp = ListOffsetsRequest.EARLIEST_TIMESTAMP)

assertResult(status, 130L, Optional.of(disklessLeaderEpoch))
}

@Test
def switchedSpecificTimestampBelowTheSealFromTheControlPlaneGetsNoLeaderEpoch(): Unit = {
when(inklessMetadataView.getClassicToDisklessStart BD0 Offset(tp)).thenReturn(seal)
when(inklessMetadataView.getDisklessLeaderEpoch(tp)).thenReturn(disklessLeaderEpoch)
disklessTaskFuture.complete(offsetResult(offset = 40L, timestamp = 123L, leaderEpoch = 0))

val status = route(newRouter(), timestamp = 123L, classicResult = syncNoMatch)

assertResult(status, 40L, Optional.empty())
}

@ParameterizedTest
@ValueSource(longs = Array(
ListOffsetsRequest.LATEST_TIMESTAMP,
ListOffsetsRequest.MAX_TIMESTAMP,
ListOffsetsRequest.EARLIEST_TIMESTAMP))
def bornDisklessResultKeepsTheControlPlaneEpoch(timestamp: Long): Unit = {
when(inklessMetadataView.getClassicToDisklessStartOffset(tp)).thenReturn(PartitionRegistration.NO_CLASSIC_TO_DISKLESS_START_OFFSET)
val disklessHit = offsetResult(offset = 150L, leaderEpoch = 0)
disklessTaskFuture.complete(disklessHit)

val status = route(consolidatingRouter(), timestamp = timestamp)

assertSame(disklessHit, resultOf(status))
}

@Test
def bornDisklessSpecificTimestampKeepsTheControlPlaneEpoch(): Unit = {
when(inklessMetadataView.getClassicToDisklessStartOffset(tp)).thenReturn(PartitionRegistration.NO_CLASSIC_TO_DISKLESS_START_OFFSET)
val disklessHit = offsetResult(offset = 150L, timestamp = 10150L, leaderEpoch = 0)
disklessTaskFuture.complete(disklessHit)

val status = route(newRouter(disklessManagedReplicasEnabled = false), timestamp = 10150L)

assertSame(disklessHit, resultOf(status))
}
}
Loading
Loading
0