8000 fix(inkless:switch): reject DeleteRecords while the switch is pending or in phase 1 [KC-867] by giuseppelillo · Pull Request #903 · 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
76 changes: 63 additions & 13 deletions core/src/main/scala/kafka/server/ReplicaManager.scala
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,27 @@ import scala.util.control.NonFatal
object ReplicaManager {
private val log = LoggerFactory.getLogger(classOf[ReplicaManager])

/**
* Splits the partitions of a `DeleteRecords` request by the state of their classic-to-diskless switch.
* Returns the `INVALID_REQUEST` results of the partitions whose switch is pending or in phase 1, and the
* offsets of the other partitions.
*/
private[server] def rejectDeleteRecordsDuringSwitch(
offsetPerPartition: Map[TopicPartition, Long],
inklessMetadataView: InklessMetadataView
): (Map[TopicPartition, DeleteRecordsPartitionResult], Map[TopicPartition, Long]) = {
val (switching, accepted) = offsetPerPartition.partition { case (topicPartition, _) =>
inklessMetadataView.isC 10000 lassicPrefixOnlyOnLocalDisks(topicPartition.topic, topicPartition.partition)
}
val rejected = switching.map { case (topicPartition, _) =>
topicPartition -> new DeleteRecordsPartitionResult()
.setPartitionIndex(topicPartition.partition)
.setLowWatermark(DeleteRecordsResponse.INVALID_LOW_WATERMARK)
.setErrorCode(Errors.INVALID_REQUEST.code)
}
(rejected, accepted)
}

val HighWatermarkFilename = "replication-offset-checkpoint"

// A faster retry doesn't help: the remote log manager refreshes a follower's view of remote storage
Expand Down Expand Up @@ -1734,7 +1755,27 @@ class ReplicaManager(val config: KafkaConfig,
responseCallback: Map[TopicPartition, DeleteRecordsPartitionResult] => Unit,
allowInternalTopicDeletion: Boolean = false): Unit = {

val disklessStartOffsetPerPartition = offsetPerPartition.keys.flatMap { topicPartition =>
// While the classic-to-diskless switch of a partition is pending or in phase 1, only DeleteRecords can
// move its log start offset: remote retention waits for the control plane to store the remote log start,
// which doesn't happen while the leader still uploads the classic prefix. The followers stop fetching at
// the seal, so they would never learn a new log start offset, and the metadata routing sends consumers to
// them. So the broker rejects the request.
val (rejectedDuringSwitch, remainingOffsets) =
ReplicaManager.rejectDeleteRecordsDuringSwitch(offsetPerPartition, _inklessMetadataView)
if (rejectedDuringSwitch.nonEmpty) {
info(s"Rejecting DeleteRecords for ${rejectedDuringSwitch.keys.mkString(", ")}: the classic-to-diskless switch " +
"of these partitions is pending or in phase 1")
if (remainingOffsets.isEmpty) {
responseCallback(rejectedDuringSwitch)
return
}
}
// Adds the rejected partitions to the response once the other partitions finish.
val effectiveCallback: Map[TopicPartition, DeleteRecordsPartitionResult] => Unit =
if (rejectedDuringSwitch.isEmpty) responseCallback
else response => responseCallback(response ++ rejectedDuringSwitch)

val disklessStartOffsetPerPartition = remainingOffsets.keys.flatMap { topicPartition =>
if (_inklessMetadataView.isDisklessTopic(topicPartition.topic)) {
Some(topicPartition -> _inklessMetadataView.getClassicToDisklessStartOffset(topicPartition))
} else {
Expand All @@ -1743,7 +1784,8 @@ class ReplicaManager(val config: KafkaConfig,
}.toMap
val disklessDeleteRecordsRequested = disklessStartOffsetPerPartition.nonEmpty

val failedDisklessDeleteRecords = if (disklessDeleteRecordsRequested && inklessDeleteRecordsInterceptor.isEmpty) {
val failedDisklessDeleteRecords = mutable.Map.empty[TopicPartition, DeleteRecordsPartitionResult]
failedDisklessDeleteRecords ++= (if (disklessDeleteRecordsRequested && inklessDeleteRecordsInterceptor.isEmpty) {
error(s"Cannot delete records from diskless partitions ${disklessStartOffsetPerPartition.keys.mkString(", ")}: DeleteRecordsInterceptor is not enabled")
disklessStartOffsetPerPartition.keys.map { topicPartition =>
topicPartition -> new DeleteRecordsPartitionResult()
Expand All @@ -1753,14 +1795,14 @@ class ReplicaManager(val config: KafkaConfig,
}.toMap
} else {
Map.empty[TopicPartition, DeleteRecordsPartitionResult]
}
})

val localOffsetPerPartition = mutable.Map.empty[TopicPartition, Long]
val disklessOffsetPerPartition = mutable.Map.empty[TopicPartition, Long]
val hybridDisklessPartitions = mutable.Set.empty[TopicPartition]

if (disklessDeleteRecordsRequested) {
offsetPerPartition.filterNot { case (topicPartition, _) =>
remainingOffsets.filterNot { case (topicPartition, _) =>
failedDisklessDeleteRecords.contains(topicPartition)
}.foreach { case (topicPartition, requestedOffset) =>
disklessStartOffsetPerPartition.get(topicPartition) match {
Expand All @@ -1779,8 +1821,12 @@ class ReplicaManager(val config: KafkaConfig,
hybridDisklessPartitions += topicPartition
}
case Some(PartitionRegistration.CLASSIC_TO_DISKLESS_SWITCH_PENDING) =>
// partition not switched yet to diskless: data is only available in local log
localOffsetPerPartition += topicPartition -> requestedOffset
// The record that starts the switch arrived after the check at the start of this method.
info(s"Rejecting DeleteRecords for $topicPartition: the classic-to-diskless switch of this partition is pending")
failedDisklessDeleteRecords += topicPartition -> new DeleteRecordsPartitionResult()
.setPartitionIndex(topicPartition.partition)
.setLowWatermark(DeleteRecordsResponse.INVALID_LOW_WATERMARK)
.setErrorCode(Errors.INVALID_REQUEST.code)
case Some(PartitionRegistration.NO_CLASSIC_TO_DISKLESS_START_OFFSET)
if config.disklessRemoteStorageConsolidationEnabled &&
_inklessMetadataView.isConsolidatingDisklessTopic(topicPartition.topic) =>
Expand Down Expand Up @@ -1822,22 +1868,23 @@ class ReplicaManager(val config: KafkaConfig,
}
} else {
// No diskless partitions are present, so keep the existing local delete path.
localOffsetPerPartition ++= offsetPerPartition
localOffsetPerPartition ++= remainingOffsets
}

// Convert to immutable before passing to the async closure to prevent accidental mutation.
val immutableDisklessOffsets = disklessOffsetPerPartition.toMap
val immutableHybridPartitions = hybridDisklessPartitions.toSet
val immutableFailedDisklessDeleteRecords = failedDisklessDeleteRecords.toMap

// Report the cross-tier earliest of successfully-deleted consolidating diskless partitions to the
// control plane and use it as their low watermark, so any broker (leader or the follower the
// metadata transformer routes clients to) returns the same value as ListOffsets(EARLIEST).
def finalizeCrossTierAndRespond(response: Map[TopicPartition, DeleteRecordsPartitionResult]): Unit = {
val advanced = advanceCrossTierEarliestForDeleteRecords(response, offsetPerPartition)
val advanced = advanceCrossTierEarliestForDeleteRecords(response, remainingOffsets)
if (advanced.isEmpty) {
responseCallback(response)
effectiveCallback(response)
} else {
responseCallback(response.map { case (topicPartition, result) =>
effectiveCallback(response.map { case (topicPartition, result) =>
topicPartition -> advanced.getOrElse(topicPartition, result)
})
}
Expand All @@ -1850,11 +1897,11 @@ class ReplicaManager(val config: KafkaConfig,
localResponse.get(topicPartition).exists(_.errorCode != Errors.NONE.code)
}
if (disklessOffsetsAfterLocalDelete.isEmpty) {
finalizeCrossTierAndRespond(localResponse ++ failedDisklessDeleteRecords)
finalizeCrossTierAndRespond(localResponse ++ immutableFailedDisklessDeleteRecords)
} else {
inklessDeleteRecordsInterceptor.get.intercept(
disklessOffsetsAfterLocalDelete.view.mapValues(java.lang.Long.valueOf).toMap.asJava,
r => finalizeCrossTierAndRespond(localResponse ++ failedDisklessDeleteRecords ++ r.asScala))
r => finalizeCrossTierAndRespond(localResponse ++ immutableFailedDisklessDeleteRecords ++ r.asScala))
}
}

Expand All @@ -1874,8 +1921,11 @@ class ReplicaManager(val config: KafkaConfig,
// finalizeCrossTierAndRespond; only classic partitions keep the ISR-gated delayed operation. The
// local leg above still ran to drive the leader's RemoteLogManager physical deletion of remote
// segments.
// A partition that this request classified as classic keeps the wait, even if the record that starts its
// switch arrived since: its followers still fetch, and they must learn the new log start offset.
val (crossTierResults, classicResults) = localDeleteRecordsResults.partition { case (topicPartition, _) =>
_inklessMetadataView.isConsolidatingDisklessTopic(topicPartition.topic)
disklessStartOffsetPerPartition.contains(topicPartition) &&
_inklessMetadataView.isConsolidatingDisklessTopic(topicPartition.topic)
}

val crossTierResponseStatus = crossTierResults.map { case (topicPartition, result) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
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.RecordsToDelete;
import org.apache.kafka.clients.admin.TransactionDescription;
import org.apache.kafka.clients.admin.TransactionState;
import org.apache.kafka.clients.consumer.Consumer;
Expand Down Expand Up @@ -867,6 +868,81 @@ private void assertConsumerKeepsTheLatestPosition(final Admin admin,
}
}

// DeleteRecords moves the log start of the leader only. In phase 1 the followers don't fetch, so they would keep
// serving the deleted records. The broker rejects the request until phase 2.
@Test
@Tag(BLOCKS_REMOTE_UPLOADS)
public void testDeleteRecordsIsRejectedUntilPhaseTwo() throws Exception {
final String topic = "switch-delete-records-" + UUID.randomUUID().toString().substring(0, 8);
final TopicPartition tp = new TopicPartition(topic, 0);
final int classicRecords = 20;
final long deleteBefore = 10;

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, classicRecords);
alterTopicConfigWithIncrementalAlterConfigs(admin, topic, Map.of(TopicConfig.DISKLESS_ENABLE_CONFIG, "true"));
assertEquals(classicRecords, waitForSealOffset(admin, topic, 0, offset -> offset >= 0));
waitForIsrRecovery(admin, topic, 0, 3);
assertFalse(readClassicPrefixInRemoteStorage(admin, topic, 0));

final ExecutionException rejected = assertThrows(ExecutionException.class, () ->
admin.deleteRecords(Map.of(tp, RecordsToDelete.beforeOffset(deleteBefore)))
.lowWatermarks().get(tp).get(30, TimeUnit.SECONDS));
assertInstanceOf(InvalidRequestException.class, rejected.getCause());
for (Map.Entry<Integer, BrokerServer> broker : cluster.brokers().entrySet()) {
assertEquals(0L, broker.getValue().replicaManager().getLog(tp).get().logStartOffset(),
"Broker " + broker.getKey() + " moved its log start offset");
}
// Brokers 0, 1, and 2 are in az1, az2, and az3. Each consumer reads from the replica in its zone.
for (int zone = 1; zone <= 3; zone++) {
assertEquals(0L, firstOffsetReadFromTheStart(tp, "az" + zone), "The consumer in az" + zone);
}

// With the bucket in place, the leader uploads the classic prefix, and phase 2 starts.
try (var s3Client = s3Container.getS3Client()) {
s3Client.createBucket(request -> request.bucket(tieredStorageBucket));
}
// `Admin` reads the phase from one broker. The leader rejects the request until its own
// metadata shows phase 2, and the client doesn't retry `INVALID_REQUEST`.
waitForPhaseTwoOnEveryBroker(tp);
assertEquals(deleteBefore, admin.deleteRecords(Map.of(tp, RecordsToDelete.beforeOffset(deleteBefore)))
.lowWatermarks().get(tp).get(30, TimeUnit.SECONDS).lowWatermark());
}
}

private void waitForPhaseTwoOnEveryBroker(final TopicPartition tp) throws Exception {
final long deadline = System.currentTimeMillis() + Duration.ofSeconds(90).toMillis();
while (System.currentTimeMillis() < deadline) {
if (cluster.brokers().values().stream().allMatch(broker ->
broker.replicaManager().inklessMetadataView().isClassicPrefixInRemoteStorage(tp))) {
return;
}
Thread.sleep(100);
}
throw new AssertionError("Not every broker applied phase 2 of " + tp + " within timeout");
}

private long firstOffsetReadFromTheStart(final TopicPartition tp, final String zone) {
final Map<String, Object> configs = baseConsumerConfigs();
configs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
configs.put(ConsumerConfig.CLIENT_ID_CONFIG, "delete-records,diskless_az=" + zone);
try (Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(configs)) {
consumer.assign(List.of(tp));
consumer.seek(tp, 0L);
final long deadline = System.currentTimeMillis() + Duration.ofSeconds(30).toMillis();
while (System.currentTimeMillis() < deadline) {
final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500));
if (!records.isEmpty()) {
return records.iterator().next().offset();
}
}
throw new AssertionError("The consumer in " + zone + " read no record from " + tp);
}
}

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
Loading
Loading
0