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
1 change: 1 addition & 0 deletions INKLESS_OWNERSHIP
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,4 @@ core/src/main/scala/kafka/server/ReplicaAlterLogDirsThread.scala @aiven/inkless
storage/src/main/java/org/apache/kafka/server/log/remote/storage/RemoteLogManager.java @aiven/inkless @apache/kafka # remote read throws LeaderEpochNotAvailableException when the epoch cache has no epoch; remote offset updates skip a log that truncated during the task; epoch cleanup keeps consolidating segments from the cross-tier log start; remote read ends at the upper bound offset
storage/src/main/java/org/apache/kafka/storage/internals/log/RemoteStorageFetchInfo.java @aiven/inkless @apache/kafka # upper bound offset that ends a tiered read at the classic-to-diskless seal
core/src/main/scala/kafka/cluster/Partition.scala @aiven/inkless @apache/kafka # classic-to-diskless seal; ISR checks capped at the seal in phase 1; no new epoch entry for a consolidating leader
checkstyle/import-control-core.xml @aiven/inkless @apache/kafka # kafka.server allows io.aiven.inkless, Testcontainers, and the AWS SDK
27 changes: 17 additions & 10 deletions core/src/test/java/kafka/server/InklessDisklessTopicDeleteTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -291,21 +291,28 @@ private void waitUntilPurged(Uuid topicId) throws InterruptedException {
}

/**
* One cycle cannot finish the drain: each broker deletes at most
* {@code topic.purger.max.batches.per.cycle} batches. Count saturated cycles from TopicPurger
* logs instead of a {@code COUNT(*)} poll, which can miss leftovers between 1s ticks.
* With one batch per cycle, every deleting cycle hits the cap except the one that removes the
* last deleted log: {@code capReached} requires {@code moreRemain}. Both brokers can finish
* concurrently, but each probes {@code moreRemain} before it commits, so at most one of them
* finds every deleted log gone. That gives a floor of {@code batchesAtDelete - 1} saturated
* lines.
*/
private static void assertSaturatedAcrossMultipleCycles(LogCaptureAppender appender, long batchesAtDelete) {
long saturated = appender.getMessages().stream()
.filter(message -> message.contains("per-cycle cap reached"))
.count();
assertTrue(saturated >= batchesAtDelete - NUM_BROKERS,
"TopicPurger must hit the per-cycle cap across multiple cycles (max "
+ MAX_BATCHES_PER_CYCLE + " per cycle); saturated=" + saturated
private static void assertSaturatedAcrossMultipleCycles(LogCaptureAppender appender, long batchesAtDelete)
throws InterruptedException {
final long expected = batchesAtDelete - 1;
TestUtils.waitForCondition(() -> countSaturated(appender) >= expected, 10_000,
() -> "TopicPurger must hit the per-cycle cap on every cycle but the last (max "
+ MAX_BATCHES_PER_CYCLE + " per cycle); saturated=" + countSaturated(appender)
+ " batchesAtDelete=" + batchesAtDelete
+ " messages=" + appender.getMessages());
}

private static long countSaturated(LogCaptureAppender appender) {
return appender.getMessages().stream()
.filter(message -> message.contains(TopicPurger.CAP_REACHED_LOG_FRAGMENT))
.count();
}

private record ControlPlaneSnapshot(
int logCount,
int deletedLogCount,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import io.aiven.inkless.TimeUtils;
Expand All @@ -55,13 +54,16 @@ public class FileCleaner implements Runnable, Closeable {
final int maxFilesPerCycle;
final FileCleanerMetrics metrics;
private final ExponentialBackoff errorBackoff = new ExponentialBackoff(100, 2, 60 * 1000, 0.2);
private final Supplier<Long> noWorkBackoffSupplier;

/**
* The counter of cleaning attempts.
*/
private final AtomicInteger attempts = new AtomicInteger();

// A sleep in `run()` holds a thread of the shared `KafkaScheduler`. If a run outlasts the interval,
// `scheduleAtFixedRate` fires the missed ticks back to back past `file.cleaner.max.files.per.cycle`.
private volatile long nextEligibleMs;

public FileCleaner(SharedState sharedState) {
this(
sharedState.time(),
Expand All @@ -87,16 +89,14 @@ public FileCleaner(SharedState sharedState) {
this.retentionPeriod = retentionPeriod;
this.maxFilesPerCycle = maxFilesPerCycle;
this.metrics = new FileCleanerMetrics(time);

// This backoff is needed only for jitter, there's no exponent in it.
final int noWorkBackoffDuration = 10 * 1000;
final var noWorkBackoff = new ExponentialBackoff(noWorkBackoffDuration, 1, noWorkBackoffDuration * 2, 0.2);
noWorkBackoffSupplier = () -> noWorkBackoff.backoff(1);
}


@Override
public void run() {
if (time.milliseconds() < nextEligibleMs) {
return;
}
try {
final var now = TimeUtils.now(time);

Expand All @@ -114,10 +114,7 @@ public void run() {
.map(FileToDelete::objectKey)
.collect(Collectors.toSet());
if (objectKeyPaths.isEmpty()) {
final long sleepMillis = noWorkBackoffSupplier.get();
final Duration sleepDuration = Duration.ofMillis(sleepMillis);
LOGGER.info("No files to delete, sleeping for {}", sleepDuration);
time.sleep(sleepMillis);
LOGGER.debug("No files to delete this cycle");
} else {
if (saturated) {
metrics.recordFileCleanerCycleSaturated();
Expand All @@ -142,8 +139,8 @@ public void run() {
} catch (final Exception e) {
metrics.recordFileCleanerError();
final long backoff = errorBackoff.backoff(attempts.incrementAndGet());
LOGGER.error("Error while deleting files, waiting for {}", Duration.ofMillis(backoff), e);
time.sleep(backoff);
nextEligibleMs = time.milliseconds() + backoff;
LOGGER.error("Error while deleting files, skipping ticks for the next {}", Duration.ofMillis(backoff), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,16 @@
public class TopicPurger implements Runnable, Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(TopicPurger.class);

public static final String CAP_REACHED_LOG_FRAGMENT = "per-cycle cap reached";

final Time time;
final ControlPlane controlPlane;
final int maxBatchesPerCycle;
final TopicPurgerMetrics metrics;
private final ExponentialBackoff errorBackoff = new ExponentialBackoff(100, 2, 60 * 1000, 0.2);
private final AtomicInteger attempts = new AtomicInteger();
// KafkaScheduler uses scheduleAtFixedRate. Sleeping inside run() queues missed ticks, and
// the next work cycle bursts past topic.purger.max.batches.per.cycle / interval. Skip the
// tick until this time instead.
// A sleep in `run()` holds a thread of the shared `KafkaScheduler`. If a run outlasts the interval,
// `scheduleAtFixedRate` fires the missed ticks back to back past `topic.purger.max.batches.per.cycle`.
private volatile long nextEligibleMs;

public TopicPurger(SharedState sharedState) {
Expand Down Expand Up @@ -85,8 +86,9 @@ public void run() {
if (saturated) {
metrics.recordTopicPurgerCycleSaturated();
LOGGER.info("Running topic purger: deleted {} batches, purged {} logs, marked {} files "
+ "(per-cycle cap reached, more remain)",
result.batchesDeleted(), result.logsPurged(), result.filesMarked());
+ "({}, more remain)",
result.batchesDeleted(), result.logsPurged(), result.filesMarked(),
CAP_REACHED_LOG_FRAGMENT);
} else {
LOGGER.info("Running topic purger: deleted {} batches, purged {} logs, marked {} files",
result.batchesDeleted(), result.logsPurged(), result.filesMarked());
Expand All @@ -95,7 +97,6 @@ public void run() {
}

attempts.set(0);
nextEligibleMs = 0L;
metrics.recordTopicPurgerCycleSucceeded();
} catch (final ControlPlaneUnavailableException e) {
// Let the caller (ReplicaManager.runIfControlPlaneAvailable) catch this and skip quietly.
Expand All @@ -106,7 +107,7 @@ public void run() {
metrics.recordTopicPurgerError();
final long backoff = errorBackoff.backoff(attempts.incrementAndGet());
nextEligibleMs = time.milliseconds() + backoff;
LOGGER.error("Error while purging deleted logs, retrying after {}", Duration.ofMillis(backoff), e);
LOGGER.error("Error while purging deleted logs, skipping ticks for the next {}", Duration.ofMillis(backoff), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,11 @@ void empty() throws Exception {
final var cleaner = new FileCleaner(time, controlPlane, storageBackend, OBJECT_KEY_CREATOR, RETENTION_PERIOD, MAX_FILES_PER_CYCLE);
when(controlPlane.getFilesToDelete(any(), anyInt())).thenReturn(List.of());

final long beforeMs = time.milliseconds();
cleaner.run();

verify(storageBackend, times(0)).delete(Set.of());
assertEquals(beforeMs, time.milliseconds());
}

@Test
Expand Down Expand Up @@ -183,20 +185,33 @@ void tracksLastSuccessfulCycle() throws Exception {

assertEquals(-1, cleaner.metrics.lastSuccessfulCleanupTimeMs.get());

final long beforeMs = time.milliseconds();
cleaner.run();

// A cycle with no work still counts: the gauge answers "is the cleaner running", not "is it deleting".
assertEquals(time.milliseconds(), cleaner.metrics.lastSuccessfulCleanupTimeMs.get());
assertEquals(beforeMs, time.milliseconds());
}

@Test
void doesNotTrackFailedCycleAsSuccessful() throws Exception {
void errorBackoffSkipsTicksUntilEligible() throws Exception {
final var cleaner = new FileCleaner(time, controlPlane, storageBackend, OBJECT_KEY_CREATOR, RETENTION_PERIOD, MAX_FILES_PER_CYCLE);
when(controlPlane.getFilesToDelete(any(), anyInt())).thenThrow(new RuntimeException("boom"));
when(controlPlane.getFilesToDelete(any(), anyInt()))
.thenThrow(new RuntimeException("boom"))
.thenReturn(List.of());

cleaner.run();
assertEquals(-1, cleaner.metrics.lastSuccessfulCleanupTimeMs.get());
verify(controlPlane, times(1)).getFilesToDelete(any(), anyInt());

cleaner.run();
assertEquals(-1, cleaner.metrics.lastSuccessfulCleanupTimeMs.get());
verify(controlPlane, times(1)).getFilesToDelete(any(), anyInt());

time.sleep(1_000);
cleaner.run();
assertEquals(time.milliseconds(), cleaner.metrics.lastSuccessfulCleanupTimeMs.get());
verify(controlPlane, times(2)).getFilesToDelete(any(), anyInt());
}

@Test
Expand Down
Loading