8000 fix(inkless:delete-records): fail DeleteRecords when the cross-tier advance fails [KC-883] by viktorsomogyi · Pull Request #931 · 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
* Inkless
* Copyright (C) 2024 - 2026 Aiven OY
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package io.aiven.inkless.consolidation

import io.aiven.inkless.common.SharedState
import io.aiven.inkless.control_plane.{AdvanceCrossTierLogStartOffsetRequest, AdvanceCrossTierLogStartOffsetResponse, ControlPlaneUnavailableException}
import kafka.server.metadata.InklessMetadataView
import kafka.utils.Logging
import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
import org.apache.kafka.common.message.DeleteRecordsResponseData.DeleteRecordsPartitionResult
import org.apache.kafka.common.protocol.Errors
import org.apache.kafka.common.requests.{DeleteRecordsRequest, DeleteRecordsResponse}

import java.util.ArrayList
import scala.collection.{Map, mutable}

object CrossTierDeleteRecords extends Logging {
/**
* Returns replacement delete results after advancing the control-plane cross-tier earliest offset.
* Failed results contain an error and an invalid low watermark. The caller can retry. A partition absent
* from the result keeps its original result, such as one that the control plane doesn't track yet.
* A delete below the current `EARLIEST` leaves it unchanged.
*
* The stored offset keeps the delete low watermark and `ListOffsets(EARLIEST)` in agreement on every
* broker. `RemoteLogManager` also uses this control-plane value as its remote cleanup floor for
* consolidating partitions and defers cleanup while the value is unavailable. This operation doesn't
* delete data itself. The control-plane call is synchronous because `DeleteRecords` is infrequent.
*/
def advance(sharedState: SharedState,
metadataView: InklessMetadataView,
response: Map[TopicPartition, DeleteRecordsPartitionResult],
offsetPerPartition: Map[TopicPartition, Long]): Map[TopicPartition, DeleteRecordsPartitionResult] = {
// A `HIGH_WATERMARK` delete needs a known low watermark before the broker can advance the offset.
val requests = new ArrayList[AdvanceCrossTierLogStartOffsetRequest]()
val partitionsInOrder = mutable.ArrayBuffer.empty[TopicPartition]
val unresolvedReplacements = mutable.Map.empty[TopicPartition, DeleteRecordsPartitionResult]
response.foreach { case (topicPartition, result) =>
if (result.errorCode == Errors.NONE.code &&
metadataView.isConsolidatingDisklessTopic(topicPartition.topic)) {
val requested = offsetPerPartition.getOrElse(topicPartition, DeleteRecordsRequest.HIGH_WATERMARK)
val convertedOffset = if (requested == DeleteRecordsRequest.HIGH_WATERMARK) result.lowWatermark else requested
val topicId = metadataView.getTopicId(topicPartition.topic)
if (topicId == null || topicId.equals(Uuid.ZERO_UUID)) {
error(s"Can't advance cross-tier log start offset for $topicPartition: missing topic id $topicId")
unresolvedReplacements += topicPartition ->
advanceFailureResult(topicPartition, Errors.UNKNOWN_TOPIC_OR_PARTITION)
} else if (convertedOffset < 0) {
debug(s"Skipping cross-tier log start offset advance for $topicPartition: offset $convertedOffset, keeping its delete result")
} else {
partitionsInOrder += topicPartition
requests.add(new AdvanceCrossTierLogStartOffsetRequest(topicId, topicPartition.partition, convertedOffset))
}
}
}

if (requests.isEmpty) {
return unresolvedReplacements.toMap
}

val advanced = try {
val responses = sharedState.controlPlane().advanceCrossTierLogStartOffset(requests)
if (responses.size() != requests.size()) {
throw new IllegalStateException(
s"Expected ${requests.size()} advance responses but got ${responses.size()}")
}
val replacements = mutable.Map.empty[TopicPartition, DeleteRecordsPartitionResult]
val cacheWrites = mutable.ArrayBuffer.empty[(TopicIdPartition, Long)]
for (i <- 0 until responses.size()) {
val topicPartition = partitionsInOrder(i)
val advanceResponse = responses.get(i)
if (advanceResponse.errors() == Errors.NONE &&
advanceResponse.remoteLogStartOffset() != AdvanceCrossTierLogStartOffsetResponse.NO_OFFSET) {
val stored = advanceResponse.remoteLogStartOffset()
cacheWrites += new TopicIdPartition(requests.get(i).topicId(), topicPartition.partition, topicPartition.topic) -> stored
replacements += topicPartition -> new DeleteRecordsPartitionResult()
.setPartitionIndex(topicPartition.partition)
.setLowWatermark(stored)
.setErrorCode(Errors.NONE.code)
} else if (advanceResponse.errors() == Errors.UNKNOWN_TOPIC_OR_PARTITION) {
debug(s"Control plane doesn't track $topicPartition yet, keeping its delete result")
} else if (advanceResponse.errors() != Errors.NONE) {
error(s"Failed to advance cross-tier log start offset for $topicPartition: ${advanceResponse.errors()}")
replacements += topicPartition -> advanceFailureResult(topicPartition, Errors.UNKNOWN_SERVER_ERROR)
} else {
error(s"Control plane advanced the cross-tier log start offset for $topicPartition but returned no stored offset")
replacements += topicPartition -> advanceFailureResult(topicPartition, Errors.UNKNOWN_SERVER_ERROR)
}
}
// Stage cache writes until validation finishes, so malformed responses don't leave partial entries.
cacheWrites.foreach { case (topicIdPartition, stored) =>
sharedState.crossTierLogStartCache().put(topicIdPartition, stored)
}
replacements.toMap
} catch {
case e: Exception =>
// Catch Exception rather than Throwable so fatal errors, such as OutOfMemoryError, propagate.
error(s"Failed to advance cross-tier log start offset for ${partitionsInOrder.mkString(", ")}", e)
val errorCode = e match {
case _: ControlPlaneUnavailableException => Errors.KAFKA_STORAGE_ERROR
case _ => Errors.UNKNOWN_SERVER_ERROR
}
partitionsInOrder.map(tp => tp -> advanceFailureResult(tp, errorCode)).toMap
}
unresolvedReplacements.toMap ++ advanced
}

private def advanceFailureResult(topicPartition: TopicPartition, error: Errors): DeleteRecordsPartitionResult =
new DeleteRecordsPartitionResult()
.setPartitionIndex(topicPartition.partition)
.setLowWatermark(DeleteRecordsResponse.INVALID_LOW_WATERMARK)
.setErrorCode(error.code)
}
93 changes: 9 additions & 84 deletions core/src/main/scala/kafka/server/ReplicaManager.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ import io.aiven.inkless.common.SharedState
import io.aiven.inkless.common.metrics.PartitionRateTracker
import io.aiven.inkless.consume.{ConcatenatedRecords, FetchHandler, FetchOffsetHandler, Reader}
import io.aiven.inkless.storage_backend.common.ObjectFetcher
import io.aiven.inkless.control_plane.{AdvanceCrossTierLogStartOffsetRequest, AdvanceCrossTierLogStartOffsetResponse, AvailabilityGatedControlPlane, BatchInfo, ControlPlaneAvailability, ControlPlaneUnavailableException, FindBatchRequest, FindBatchResponse, InitDisklessLogProducerState, ListOffsetsRequest => CpListOffsetsRequest}
import io.aiven.inkless.control_plane.{AvailabilityGatedControlPlane, BatchInfo, ControlPlaneAvailability, ControlPlaneUnavailableException, FindBatchRequest, FindBatchResponse, InitDisklessLogProducerState, ListOffsetsRequest => CpListOffsetsRequest}
import io.aiven.inkless.delete.{ConsolidatedDisklessLogPrunerMetrics, DeleteRecordsInterceptor, FileCleaner, RetentionEnforcer, TopicPurger}
import io.aiven.inkless.produce.AppendHandler
import io.aiven.inkless.consolidation.{ConsolidatedDisklessLogPruner, ConsolidationFetcherManager, ConsolidationMetrics, ConsolidationReconciler, DelayedConsolidationFetch}
import io.aiven.inkless.consolidation.{ConsolidatedDisklessLogPruner, ConsolidationFetcherManager, ConsolidationMetrics, ConsolidationReconciler, CrossTierDeleteRecords, DelayedConsolidationFetch}
import kafka.cluster.Partition
import kafka.server.DisklessFetchOffsetRouter.ClassicSearchRange
import org.apache.kafka.server.quota.QuotaFactory.QuotaManagers
Expand Down Expand Up @@ -1879,9 +1879,11 @@ class ReplicaManager(val config: KafkaConfig,

// 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).
// metadata transformer routes clients to) returns the same value as ListOffsets(EARLIEST). If the
// report fails, the partition gets an error instead, so the caller receives the failure and can retry.
def finalizeCrossTierAndRespond(response: Map[TopicPartition, DeleteRecordsPartitionResult]): Unit = {
val advanced = advanceCrossTierEarliestForDeleteRecords(response, remainingOffsets)
val advanced = inklessSharedState.map(state =>
CrossTierDeleteRecords.advance(state, _inklessMetadataView, response, remainingOffsets)).getOrElse(Map.empty)
if (advanced.isEmpty) {
effectiveCallback(response)
} else {
Expand Down Expand Up @@ -1920,8 +1922,9 @@ class ReplicaManager(val config: KafkaConfig,
// wait on the ISR low watermark (Partition.lowWatermarkIfLeader), which is pinned at the followers'
// frozen, pre-switch logStartOffset. Their earliest is instead reported from the control plane in
// 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.
// local leg above still trimmed the leader's local log. RemoteLogManager reclaims their remote
// segments from the control-plane cross-tier start that finalizeCrossTierAndRespond advances, not
// from the local logStartOffset.
// 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, _) =>
Expand Down Expand Up @@ -2007,84 +2010,6 @@ class ReplicaManager(val config: KafkaConfig,
Math.max(classicToDisklessStartOffset, Math.min(requestedOffset, localHighWatermark))
}

/**
* For every successfully-deleted consolidating diskless partition in `response`, advance the
* control-plane cross-tier earliest (`remote_log_start_offset`) to the requested delete offset and
* return a replacement result whose low watermark is the stored value. A delete below the current
* `EARLIEST` leaves it unchanged. `EARLIEST` is
* `COALESCE(remote_log_start_offset, log_start_offset)`, so reporting the just-advanced (non-null)
* `remote_log_start_offset` keeps the DeleteRecords low watermark and a subsequent
* `ListOffsets(EARLIEST)` in agreement on every broker.
*
* Physical deletion is unchanged: the diskless WAL objects are freed by `delete_records_v1` +
* `FileCleaner`, and the remote-tier segments by the leader's `RemoteLogManager` (driven by the
* leader's local `logStartOffset`); this method only moves the logical earliest pointer.
*
* Returns the replacement results keyed by partition (empty when nothing applies). The control-plane
* call is synchronous; `DeleteRecords` is an infrequent admin operation.
*/
private def advanceCrossTierEarliestForDeleteRecords(
response: Map[TopicPartition, DeleteRecordsPartitionResult],
offsetPerPartition: Map[TopicPartition, Long]
): Map[TopicPartition, DeleteRecordsPartitionResult] = {
val sharedState = inklessSharedState.orNull
if (sharedState == null) {
return Map.empty
}

// Convert each delete offset: use the requested offset, or the leg's returned low watermark when
// the request was HIGH_WATERMARK (which always reaches the WAL, so the diskless leg ran).
val requests = new java.util.ArrayList[AdvanceCrossTierLogStartOffsetRequest]()
val partitionsInOrder = mutable.ArrayBuffer.empty[TopicPartition]
response.foreach { case (topicPartition, result) =>
// Non-consolidating partitions and errors will be skipped here as they're handled in the caller
// finalizeCrossTierAndRespond by returning their original response.
if (result.errorCode == Errors.NONE.code &&
_inklessMetadataView.isConsolidatingDisklessTopic(topicPartition.topic)) {
val requested = offsetPerPartition.getOrElse(topicPartition, DeleteRecordsRequest.HIGH_WATERMARK)
val convertedOffset = if (requested == DeleteRecordsRequest.HIGH_WATERMARK) result.lowWatermark else requested
val topicId = _inklessMetadataView.getTopicId(topicPartition.topic)
if (convertedOffset >= 0 && topicId != null && !topicId.equals(Uuid.ZERO_UUID)) {
partitionsInOrder += topicPartition
requests.add(new AdvanceCrossTierLogStartOffsetRequest(topicId, topicPartition.partition, convertedOffset))
}
}
}

if (requests.isEmpty) {
return Map.empty
}

try {
val responses = sharedState.controlPlane().advanceCrossTierLogStartOffset(requests)
val replacements = mutable.Map.empty[TopicPartition, DeleteRecordsPartitionResult]
for (i <- 0 until responses.size()) {
val topicPartition = partitionsInOrder(i)
val advanceResponse = responses.get(i)
if (advanceResponse.errors() == Errors.NONE &&
advanceResponse.remoteLogStartOffset() != AdvanceCrossTierLogStartOffsetResponse.NO_OFFSET) {
val stored = advanceResponse.remoteLogStartOffset()
// Write-through so the leader's local read path does not re-query the control plane.
sharedState.crossTierLogStartCache().put(
new TopicIdPartition(requests.get(i).topicId(), topicPartition.partition, topicPartition.topic), stored)
replacements += topicPartition -> new DeleteRecordsPartitionResult()
.setPartitionIndex(topicPartition.partition)
.setLowWatermark(stored)
.setErrorCode(Errors.NONE. 81B2 code)
}
}
replacements.toMap
} catch {
case e: Exception =>
// Catch only Exception, not Throwable: control-plane failures are ControlPlaneException (a
// RuntimeException), but Errors (e.g. OutOfMemoryError) must propagate rather than fail open.
// Reporting failure must not fail the delete (the data is already deleted); leave the per-leg
// low watermark in place and let the RLM's own report reconcile the control plane later.
error(s"Failed to advance cross-tier log start offset for ${partitionsInOrder.mkString(", ")}", e)
Map.empty
}
}

/**
* Whether `topicPartition` is a consolidating diskless topic on this broker (covers both switched
* partitions, which carry a seal, and born-diskless partitions, which do not). Used by the
Expand Down
Loading
Loading
0