You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fluss.apache.org by ja...@apache.org on 2026/09/17 16:39:17 UTC

(fluss) branch release-1.0 updated: [server] Clean up stale KV directories during startup (#4407)

This is an automated email from the ASF dual-hosted git repository.

wuchong pushed a commit to branch release-1.0
in repository https://gitbox.apache.org/repos/asf/fluss.git


The following commit(s) were added to refs/heads/release-1.0 by this push:
     new 4ba9d5275 [server] Clean up stale KV directories during startup (#4407)
4ba9d5275 is described below

commit 4ba9d5275401c959333c039523880bbd94eae008
Author: yunhong <33...@qq.com>
AuthorDate: Fri Sep 18 00:39:13 2026 +0800

    [server] Clean up stale KV directories during startup (#4407)
    
    Remove leftover local KV directories in KvManager.startup() before the
    TabletServer accepts replica assignments, including directories without
    logs or table metadata. Share tablet discovery and retain logs and caches.
    
    Atomically rename stale tablets before deletion to prevent reuse of
    partially deleted RocksDB state. Retry pending deletions, skip symbolic
    links, and tolerate cleanup I/O failures without preventing startup.
    
    Cover controlled shutdown, snapshot and log recovery, multiple disks,
    and directory isolation, permissions, and cleanup boundaries.
    
    
    AI-Model: gpt-6
    AI-Contributed/Feature: 223/223
    AI-Contributed/UT: 350/350
    
    Co-authored-by: Codex <no...@openai.com>
---
 .../org/apache/fluss/server/TabletManagerBase.java |  74 +++--
 .../java/org/apache/fluss/server/kv/KvManager.java | 129 +++++++-
 .../apache/fluss/server/TabletManagerBaseTest.java |  51 +++-
 .../org/apache/fluss/server/kv/KvManagerTest.java  | 328 ++++++++++++++++++++-
 .../server/tablet/TabletServerShutdownITCase.java  | 165 +++++++++++
 5 files changed, 702 insertions(+), 45 deletions(-)

diff --git a/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java b/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java
index 389c85918..187f2c5a1 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java
@@ -54,6 +54,7 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.function.Consumer;
+import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
 import static org.apache.fluss.utils.FlussPaths.HISTORICAL_LOOKUP_CACHE_DIR_NAME;
@@ -113,47 +114,56 @@ public abstract class TabletManagerBase {
 
     /** Returns the tablet directories to be loaded from a single configured data directory. */
     protected List<File> listTabletsToLoad(File dataDir) {
-        List<File> tabletsToLoad = new ArrayList<>();
-        // Get all database directory.
-        File[] dbDirs = FileUtils.listDirectories(dataDir);
-        for (File dbDir : dbDirs) {
-            if (dbDir.getName().equals(HISTORICAL_LOOKUP_CACHE_DIR_NAME)
-                    || dbDir.getName().equals(REMOTE_LOG_INDEX_LOCAL_CACHE)) {
-                continue;
-            }
-            // Get all table path directory.
-            File[] tableDirs = FileUtils.listDirectories(dbDir);
-            for (File tableDir : tableDirs) {
-                // maybe tablet directories or partition directories
-                File[] tabletOrPartitionDirs = FileUtils.listDirectories(tableDir);
+        return listTabletsToLoad(
+                dataDir,
+                (directory, nameFilter) ->
+                        Arrays.stream(FileUtils.listDirectories(directory))
+                                .filter(file -> nameFilter.test(file.getName()))
+                                .collect(Collectors.toList()));
+    }
 
-                List<File> tabletDirs = new ArrayList<>();
-                for (File tabletOrPartitionDir : tabletOrPartitionDirs) {
-                    // if not partition dir, consider it as a tablet dir
-                    if (!isPartitionDir(tabletOrPartitionDir.getName())) {
-                        tabletDirs.add(tabletOrPartitionDir);
+    /**
+     * Lists tablet directories using the common layout and cache exclusions, with a caller-supplied
+     * directory lister to control symbolic-link handling and listing failures.
+     */
+    protected <E extends Exception> List<File> listTabletsToLoad(
+            File dataDir, DirectoryLister<E> directoryLister) throws E {
+        List<File> tabletsToLoad = new ArrayList<>();
+        for (File dbDir :
+                directoryLister.listDirectories(
+                        dataDir,
+                        name ->
+                                !name.equals(HISTORICAL_LOOKUP_CACHE_DIR_NAME)
+                                        && !name.equals(REMOTE_LOG_INDEX_LOCAL_CACHE))) {
+            for (File tableDir : directoryLister.listDirectories(dbDir, name -> true)) {
+                for (File tabletOrPartitionDir :
+                        directoryLister.listDirectories(
+                                tableDir,
+                                name -> isPartitionDir(name) || name.startsWith(tabletDirPrefix))) {
+                    if (isPartitionDir(tabletOrPartitionDir.getName())) {
+                        tabletsToLoad.addAll(
+                                directoryLister.listDirectories(
+                                        tabletOrPartitionDir,
+                                        name -> name.startsWith(tabletDirPrefix)));
                     } else {
-                        // consider all dirs in partition as tablet dirs
-                        tabletDirs.addAll(
-                                Arrays.asList(FileUtils.listDirectories(tabletOrPartitionDir)));
+                        tabletsToLoad.add(tabletOrPartitionDir);
                     }
                 }
-
-                // it may contain the directory for kv tablet and log tablet
-                // filter out the directory for specific type tablet
-                // actually it identified by the prefix of the directory
-                tabletsToLoad.addAll(
-                        tabletDirs.stream()
-                                .filter(
-                                        tabletDir ->
-                                                tabletDir.getName().startsWith(tabletDirPrefix))
-                                .collect(Collectors.toList()));
             }
         }
-
         return tabletsToLoad;
     }
 
+    /**
+     * Lists child directories whose names match a filter, optionally reporting listing failures.
+     */
+    @FunctionalInterface
+    protected interface DirectoryLister<E extends Exception> {
+
+        /** Returns the matching child directories. */
+        List<File> listDirectories(File parent, Predicate<String> nameFilter) throws E;
+    }
+
     protected ExecutorService createThreadPool(String poolName) {
         return Executors.newFixedThreadPool(recoveryThreads, new ExecutorThreadFactory(poolName));
     }
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java b/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java
index 14a14714b..1ac64e786 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java
@@ -67,13 +67,24 @@ import javax.annotation.concurrent.ThreadSafe;
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.file.DirectoryIteratorException;
+import java.nio.file.DirectoryNotEmptyException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Predicate;
 
+import static org.apache.fluss.utils.Preconditions.checkState;
 import static org.apache.fluss.utils.concurrent.LockUtils.inLock;
 
 /**
@@ -358,8 +369,124 @@ public final class KvManager extends TabletManagerBase implements ServerReconfig
                 : 0L;
     }
 
+    /**
+     * Starts the manager by deleting local KV directories left by a previous TabletServer process.
+     *
+     * <p>This must run before the TabletServer accepts replica assignments. Leaders rebuild KV
+     * state from snapshots and logs, while followers never open these directories. Scan the disk
+     * rather than registered tablets so that KV directories without logs or table metadata are also
+     * removed. Symbolic links below a data directory are skipped, and cleanup I/O failures are
+     * logged without preventing startup or cleanup of other tablets and data directories.
+     * Directories are atomically renamed before deletion so that partially deleted state cannot be
+     * reopened as a live KV tablet.
+     */
     public void startup() {
-        // should do nothing now
+        cleanupStaleKvDirectories();
+    }
+
+    private void cleanupStaleKvDirectories() {
+        inLock(
+                tabletCreationOrDeletionLock,
+                () -> {
+                    checkState(!isShutdown, "Cannot clean KV directories after shutdown.");
+                    checkState(
+                            currentKvs.isEmpty(),
+                            "Cannot clean KV directories while KV tablets are open.");
+                    for (File dataDir : dataDirs) {
+                        try {
+                            Path realDataDir = dataDir.toPath().toRealPath();
+                            List<File> staleDirs =
+                                    listTabletsToLoad(
+                                            realDataDir.toFile(), this::listCleanupDirectories);
+                            int deletedDirectories = 0;
+                            for (File tabletDir : staleDirs) {
+                                try {
+                                    deleteStaleKvDirectory(tabletDir.toPath(), realDataDir);
+                                    deletedDirectories++;
+                                } catch (IOException e) {
+                                    LOG.warn(
+                                            "Failed to clean stale KV tablet directory {}. "
+                                                    + "Continuing cleanup of other tablet directories.",
+                                            tabletDir,
+                                            e);
+                                }
+                            }
+                            LOG.info(
+                                    "Cleaned up {} of {} stale KV tablet directories in {}.",
+                                    deletedDirectories,
+                                    staleDirs.size(),
+                                    dataDir);
+                        } catch (IOException e) {
+                            LOG.warn(
+                                    "Failed to clean stale KV directories in {}. Skipping remaining "
+                                            + "cleanup for this data directory; startup will continue.",
+                                    dataDir,
+                                    e);
+                        }
+                    }
+                });
+    }
+
+    private void deleteStaleKvDirectory(Path tabletDir, Path dataDir) throws IOException {
+        Path deletedDir = tabletDir;
+        if (!tabletDir.getFileName().toString().endsWith(FlussPaths.DELETED_FILE_SUFFIX)) {
+            deletedDir =
+                    tabletDir.resolveSibling(
+                            tabletDir.getFileName()
+                                    + "."
+                                    + UUID.randomUUID()
+                                    + FlussPaths.DELETED_FILE_SUFFIX);
+            // Never delete from the live path if atomic isolation fails. A unique name also lets
+            // a new tablet be cleaned up while an earlier deletion is still pending.
+            Files.move(tabletDir, deletedDir, StandardCopyOption.ATOMIC_MOVE);
+            LOG.info(
+                    "Moved stale KV tablet directory {} to {} for deletion.",
+                    tabletDir,
+                    deletedDir);
+        }
+        FileUtils.deleteDirectory(deletedDir.toFile());
+        LOG.info("Deleted stale KV tablet directory {}.", deletedDir);
+        deleteEmptyParentDirectories(deletedDir.getParent(), dataDir);
+    }
+
+    private List<File> listCleanupDirectories(File parent, Predicate<String> nameFilter)
+            throws IOException {
+        List<File> directories = new ArrayList<>();
+        try (DirectoryStream<Path> entries = Files.newDirectoryStream(parent.toPath())) {
+            for (Path entry : entries) {
+                if (!nameFilter.test(entry.getFileName().toString())) {
+                    continue;
+                }
+                BasicFileAttributes attributes =
+                        Files.readAttributes(
+                                entry, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+                if (attributes.isSymbolicLink()) {
+                    LOG.warn(
+                            "Skipping symbolic link {} during stale KV cleanup; its target will "
+                                    + "not be cleaned.",
+                            entry);
+                    continue;
+                }
+                if (attributes.isDirectory()) {
+                    directories.add(entry.toFile());
+                }
+            }
+        } catch (DirectoryIteratorException e) {
+            throw e.getCause();
+        }
+        return directories;
+    }
+
+    private void deleteEmptyParentDirectories(Path directory, Path dataDir) throws IOException {
+        for (Path parent = directory;
+                parent != null && parent.startsWith(dataDir) && !parent.equals(dataDir);
+                parent = parent.getParent()) {
+            try {
+                Files.deleteIfExists(parent);
+            } catch (DirectoryNotEmptyException e) {
+                return;
+            }
+        }
     }
 
     public void shutdown() {
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/TabletManagerBaseTest.java b/fluss-server/src/test/java/org/apache/fluss/server/TabletManagerBaseTest.java
index 01d43c556..8e0997243 100644
--- a/fluss-server/src/test/java/org/apache/fluss/server/TabletManagerBaseTest.java
+++ b/fluss-server/src/test/java/org/apache/fluss/server/TabletManagerBaseTest.java
@@ -23,8 +23,12 @@ import org.apache.fluss.utils.FlussPaths;
 
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
 
 import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
@@ -57,6 +61,47 @@ final class TabletManagerBaseTest {
         assertThat(tabletManager.tabletsToLoad(tempDir)).isEmpty();
     }
 
+    @ParameterizedTest
+    @EnumSource(TabletManagerBase.TabletType.class)
+    void testListsTabletLayoutAndExcludesCaches(TabletManagerBase.TabletType tabletType)
+            throws Exception {
+        for (String path :
+                Arrays.asList(
+                        "db/table-1/kv-0",
+                        "db/table-1/log-0",
+                        "db/table-2/partition-p2/kv-1",
+                        "db/table-2/partition-p2/log-1",
+                        "db/table-1/backup",
+                        FlussPaths.HISTORICAL_LOOKUP_CACHE_DIR_NAME + "/table-1/kv-0",
+                        FlussPaths.HISTORICAL_LOOKUP_CACHE_DIR_NAME + "/table-1/log-0",
+                        FlussPaths.REMOTE_LOG_INDEX_LOCAL_CACHE + "/table-1/kv-0",
+                        FlussPaths.REMOTE_LOG_INDEX_LOCAL_CACHE + "/table-1/log-0")) {
+            Files.createDirectories(tempDir.toPath().resolve(path));
+        }
+        String prefix =
+                tabletType == TabletManagerBase.TabletType.KV
+                        ? FlussPaths.KV_TABLET_DIR_PREFIX
+                        : FlussPaths.LOG_TABLET_DIR_PREFIX;
+        TestingTabletManager tabletManager = new TestingTabletManager(tempDir, tabletType);
+
+        assertThat(tabletManager.tabletsToLoad(tempDir))
+                .containsExactlyInAnyOrder(
+                        new File(tempDir, "db/table-1/" + prefix + "0"),
+                        new File(tempDir, "db/table-2/partition-p2/" + prefix + "1"));
+    }
+
+    @Test
+    void testLogLoadingStillFollowsSymbolicDatabaseDirectory(@TempDir Path outsideDir)
+            throws Exception {
+        Files.createDirectories(outsideDir.resolve("table-1/log-0"));
+        Path dbLink = Files.createSymbolicLink(tempDir.toPath().resolve("db"), outsideDir);
+        TestingTabletManager tabletManager =
+                new TestingTabletManager(tempDir, TabletManagerBase.TabletType.LOG);
+
+        assertThat(tabletManager.tabletsToLoad(tempDir))
+                .containsExactly(dbLink.resolve("table-1/log-0").toFile());
+    }
+
     @Test
     void testCloseTabletsConcurrentlyWaitsForAllTasksAndShutsDownPoolOnFailure() throws Exception {
         TestingTabletManager tabletManager = new TestingTabletManager(2);
@@ -111,7 +156,11 @@ final class TabletManagerBaseTest {
         }
 
         private TestingTabletManager(File dataDir) {
-            super(TabletType.KV, Collections.singletonList(dataDir), new Configuration(), 1);
+            this(dataDir, TabletType.KV);
+        }
+
+        private TestingTabletManager(File dataDir, TabletType tabletType) {
+            super(tabletType, Collections.singletonList(dataDir), new Configuration(), 1);
         }
 
         private List<File> tabletsToLoad(File dataDir) {
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java
index e9c69e4fe..31f92f543 100644
--- a/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java
+++ b/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java
@@ -52,6 +52,7 @@ import org.apache.fluss.server.zk.data.TableRegistration;
 import org.apache.fluss.testutils.common.AllCallbackWrapper;
 import org.apache.fluss.types.RowType;
 import org.apache.fluss.utils.ByteArraySlice;
+import org.apache.fluss.utils.FlussPaths;
 import org.apache.fluss.utils.clock.SystemClock;
 import org.apache.fluss.utils.concurrent.FlussScheduler;
 
@@ -62,13 +63,17 @@ import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.RegisterExtension;
 import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
 
 import javax.annotation.Nullable;
 
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -87,6 +92,7 @@ import static org.apache.fluss.server.kv.KvTabletTestUtils.flushAndWait;
 import static org.apache.fluss.testutils.common.CommonTestUtils.waitUntil;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assumptions.assumeThat;
 
 /** Test for {@link KvManager} . */
 final class KvManagerTest {
@@ -134,6 +140,10 @@ final class KvManagerTest {
         tablePath1 = TablePath.of(dbName, "t1");
         tablePath2 = TablePath.of(dbName, "t2");
 
+        createManagers();
+    }
+
+    private void createManagers() throws Exception {
         // we need a log manager for kv manager
         localDiskManager = LocalDiskManager.create(conf);
         logManager =
@@ -171,6 +181,300 @@ final class KvManagerTest {
         return Arrays.asList(null, "2024");
     }
 
+    @Test
+    void testStartupCleanupAcrossDisks(@TempDir File secondDataDir) throws Exception {
+        configureTwoDataDirs(secondDataDir);
+
+        List<Path> staleDirs = new ArrayList<>();
+        List<Path> retainedFiles = new ArrayList<>();
+        List<Path> emptyParentDirs = new ArrayList<>();
+        for (File dataDir : localDiskManager.dataDirs()) {
+            for (String path :
+                    Arrays.asList(
+                            "db/table-1/kv-0",
+                            "db/table-2/20260917-p2/kv-1",
+                            "dropped/table-3/kv-0",
+                            "dropped/table-4/20260917-p4/kv-2")) {
+                Path kvDir = dataDir.toPath().resolve(path);
+                Files.createDirectories(kvDir.resolve("db"));
+                Files.write(kvDir.resolve("db/000001.sst"), new byte[] {1, 2, 3});
+                staleDirs.add(kvDir);
+            }
+            emptyParentDirs.add(dataDir.toPath().resolve("dropped/table-3"));
+            emptyParentDirs.add(dataDir.toPath().resolve("dropped/table-4"));
+            emptyParentDirs.add(dataDir.toPath().resolve("dropped"));
+            for (String path :
+                    Arrays.asList(
+                            "db/table-1/log-0/segment.log",
+                            "db/table-2/20260917-p2/log-1/segment.log",
+                            "db/table-1/backup/file",
+                            FlussPaths.HISTORICAL_LOOKUP_CACHE_DIR_NAME + "/table-1/kv-0/file",
+                            FlussPaths.REMOTE_LOG_INDEX_LOCAL_CACHE + "/table-1/kv-0/file",
+                            "recovery-point-offset-checkpoint")) {
+                Path retainedFile = dataDir.toPath().resolve(path);
+                Files.createDirectories(retainedFile.getParent());
+                Files.write(retainedFile, new byte[] {4, 5, 6});
+                retainedFiles.add(retainedFile);
+            }
+        }
+
+        kvManager.startup();
+        // A second startup cleanup must also succeed when the orphan directories are gone.
+        kvManager.startup();
+
+        for (Path staleDir : staleDirs) {
+            assertThat(staleDir).doesNotExist();
+        }
+        for (Path parentDir : emptyParentDirs) {
+            assertThat(parentDir).doesNotExist();
+        }
+        for (Path retainedFile : retainedFiles) {
+            assertThat(Files.readAllBytes(retainedFile)).containsExactly(4, 5, 6);
+        }
+        for (File dataDir : localDiskManager.dataDirs()) {
+            assertThat(new File(dataDir, LocalDiskManager.DISK_PROPERTIES_FILE_NAME)).isFile();
+            assertThat(new File(dataDir, LocalDiskManager.LOCK_FILE_NAME)).isFile();
+        }
+    }
+
+    private void configureTwoDataDirs(File secondDataDir) throws Exception {
+        tearDown();
+        kvManager = null;
+        logManager = null;
+        localDiskManager = null;
+        conf.set(
+                ConfigOptions.DATA_DIRS,
+                Arrays.asList(tempDir.getAbsolutePath(), secondDataDir.getAbsolutePath()));
+        createManagers();
+    }
+
+    @Test
+    void testStartupCleanupRejectsOpenTablets() throws Exception {
+        initTableBuckets(null);
+        KvTablet kv = getOrCreateKv(tablePath1, null, tableBucket1);
+        byte[] key = "live-key".getBytes(StandardCharsets.UTF_8);
+        KvRecord record = kvRecordFactory.ofRecord(key, new Object[] {1, "value"});
+        put(kv, record);
+
+        assertThatThrownBy(kvManager::startup)
+                .isInstanceOf(IllegalStateException.class)
+                .hasMessage("Cannot clean KV directories while KV tablets are open.");
+
+        assertThat(kv.getKvTabletDir()).isDirectory();
+        verifyMultiGet(kv, key, valueOf(record));
+    }
+
+    @Test
+    void testStartupCleanupContinuesOnOtherDisksAfterDeletionFailure(@TempDir File secondDataDir)
+            throws Exception {
+        configureTwoDataDirs(secondDataDir);
+        Path otherKvDir =
+                Files.createDirectories(secondDataDir.toPath().resolve("db/table-2/kv-0"));
+        Path kvDir = tempDir.toPath().resolve("db/table-1/kv-0");
+        Path dbDir = Files.createDirectories(kvDir.resolve("db"));
+        Files.write(dbDir.resolve("data"), new byte[] {1});
+        File tableDir = kvDir.getParent().toFile();
+        try {
+            assertThat(dbDir.toFile().setWritable(false)).isTrue();
+            assumeThat(Files.isWritable(dbDir)).isFalse();
+
+            kvManager.startup();
+            assertThat(kvDir).doesNotExist();
+            File[] pendingDirs = tableDir.listFiles(File::isDirectory);
+            assertThat(pendingDirs).hasSize(1);
+            assertThat(pendingDirs[0].getName()).endsWith(FlussPaths.DELETED_FILE_SUFFIX);
+            assertThat(Files.readAllBytes(pendingDirs[0].toPath().resolve("db/data")))
+                    .containsExactly(1);
+            assertThat(otherKvDir).doesNotExist();
+        } finally {
+            makeKvStoreDirectoriesWritable(tableDir);
+        }
+
+        // Cleanup can be retried once the disk problem is resolved.
+        kvManager.startup();
+        assertThat(tableDir).doesNotExist();
+    }
+
+    @Test
+    void testStartupCleanupRetriesPendingDeletionWithoutBlockingNewTablet() throws Exception {
+        Path kvDir = Files.createDirectories(tempDir.toPath().resolve("db/table-1/kv-0"));
+        Files.write(kvDir.resolve("data"), new byte[] {1});
+        Path pendingDir = Files.createDirectory(kvDir.resolveSibling("kv-0.deleted"));
+        Path pendingFile = Files.write(pendingDir.resolve("data"), new byte[] {2});
+        try {
+            assertThat(pendingDir.toFile().setWritable(false)).isTrue();
+            assumeThat(Files.isWritable(pendingDir)).isFalse();
+
+            kvManager.startup();
+            // Retrying an older deletion must neither rename it again nor prevent isolation of
+            // the current tablet, regardless of directory enumeration order.
+            kvManager.startup();
+
+            assertThat(kvDir).doesNotExist();
+            assertThat(kvDir.getParent().toFile().listFiles()).containsExactly(pendingDir.toFile());
+            assertThat(Files.readAllBytes(pendingFile)).containsExactly(2);
+        } finally {
+            assertThat(pendingDir.toFile().setWritable(true)).isTrue();
+        }
+
+        kvManager.startup();
+        assertThat(kvDir.getParent()).doesNotExist();
+    }
+
+    @Test
+    void testStartupCleanupKeepsOriginalDirectoryWhenRenameFails() throws Exception {
+        Path kvDir = Files.createDirectories(tempDir.toPath().resolve("db/table-1/kv-0"));
+        Path retainedFile = Files.write(kvDir.resolve("data"), new byte[] {1, 2, 3});
+        File tableDir = kvDir.getParent().toFile();
+        Path otherKvDir = Files.createDirectories(tempDir.toPath().resolve("db/table-2/kv-0"));
+        try {
+            assertThat(tableDir.setWritable(false)).isTrue();
+            assumeThat(tableDir.canWrite()).isFalse();
+
+            kvManager.startup();
+
+            assertThat(Files.readAllBytes(retainedFile)).containsExactly(1, 2, 3);
+            assertThat(tableDir.listFiles()).containsExactly(kvDir.toFile());
+            assertThat(otherKvDir).doesNotExist();
+        } finally {
+            assertThat(tableDir.setWritable(true)).isTrue();
+        }
+
+        kvManager.startup();
+        assertThat(tableDir).doesNotExist();
+    }
+
+    private void makeKvStoreDirectoriesWritable(File directory) {
+        File[] children = directory.listFiles(File::isDirectory);
+        if (children != null) {
+            for (File child : children) {
+                File dbDir = new File(child, "db");
+                if (dbDir.exists()) {
+                    assertThat(dbDir.setWritable(true)).isTrue();
+                }
+            }
+        }
+    }
+
+    @Test
+    void testStartupCleanupWithSymbolicDataRoot(@TempDir Path linkDir) throws Exception {
+        tearDown();
+        kvManager = null;
+        logManager = null;
+        localDiskManager = null;
+        Path dataLink = Files.createSymbolicLink(linkDir.resolve("data"), tempDir.toPath());
+        conf.set(ConfigOptions.DATA_DIR, dataLink.toString());
+        createManagers();
+        Path staleDir = tempDir.toPath().resolve("db/table-1/kv-0");
+        Files.createDirectories(staleDir);
+        Files.write(staleDir.resolve("data"), new byte[] {1});
+
+        kvManager.startup();
+
+        assertThat(staleDir).doesNotExist();
+        assertThat(Files.isSymbolicLink(dataLink)).isTrue();
+        assertThat(tempDir).isDirectory();
+    }
+
+    @ParameterizedTest
+    @CsvSource({
+        "db, table-1/kv-0",
+        "db/table-1, kv-0",
+        "db/table-1/partition-p1, kv-0",
+        "db/table-1/kv-0, db",
+        "db/table-1/partition-p1/kv-0, db"
+    })
+    void testStartupCleanupSkipsSymbolicLinks(
+            String linkPath, String targetPath, @TempDir Path outsideDir) throws Exception {
+        Path outsideKvDir = Files.createDirectories(outsideDir.resolve(targetPath));
+        Path outsideFile = Files.write(outsideKvDir.resolve("data"), new byte[] {1, 2, 3});
+        Path link = tempDir.toPath().resolve(linkPath);
+        Files.createDirectories(link.getParent());
+        Files.createSymbolicLink(link, outsideDir);
+        Path staleDir = Files.createDirectories(tempDir.toPath().resolve("other/table-2/kv-0"));
+
+        kvManager.startup();
+
+        assertThat(staleDir).doesNotExist();
+        assertThat(Files.readAllBytes(outsideFile)).containsExactly(1, 2, 3);
+        assertThat(Files.isSymbolicLink(link)).isTrue();
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"db", "db/table-1", "db/table-1/partition-p1"})
+    void testStartupCleanupContinuesOnOtherDisksAfterListingFailure(
+            String unreadablePath, @TempDir File secondDataDir) throws Exception {
+        configureTwoDataDirs(secondDataDir);
+        Path otherKvDir =
+                Files.createDirectories(secondDataDir.toPath().resolve("db/table-2/kv-0"));
+        Path kvDir = tempDir.toPath().resolve("db/table-1/partition-p1/kv-0");
+        Files.createDirectories(kvDir);
+        Path retainedFile = Files.write(kvDir.resolve("data"), new byte[] {1});
+        File unreadableDir = tempDir.toPath().resolve(unreadablePath).toFile();
+        try {
+            assertThat(unreadableDir.setReadable(false)).isTrue();
+            assumeThat(unreadableDir.canRead()).isFalse();
+
+            kvManager.startup();
+            assertThat(otherKvDir).doesNotExist();
+        } finally {
+            assertThat(unreadableDir.setReadable(true)).isTrue();
+        }
+
+        assertThat(retainedFile).exists();
+        kvManager.startup();
+        assertThat(kvDir).doesNotExist();
+    }
+
+    @Test
+    void testStartupCleanupLeavesExcludedSymbolicLinks(@TempDir Path outsideDir) throws Exception {
+        Path outsideFile = Files.write(outsideDir.resolve("data"), new byte[] {1, 2, 3});
+        Path kvDir = tempDir.toPath().resolve("db/table-1/kv-0");
+        Files.createDirectories(kvDir);
+        List<Path> links = new ArrayList<>();
+        for (String path :
+                Arrays.asList(
+                        FlussPaths.HISTORICAL_LOOKUP_CACHE_DIR_NAME,
+                        FlussPaths.REMOTE_LOG_INDEX_LOCAL_CACHE,
+                        "db/table-1/log-0",
+                        "db/table-1/backup")) {
+            links.add(Files.createSymbolicLink(tempDir.toPath().resolve(path), outsideDir));
+        }
+
+        kvManager.startup();
+
+        assertThat(kvDir).doesNotExist();
+        assertThat(Files.readAllBytes(outsideFile)).containsExactly(1, 2, 3);
+        for (Path link : links) {
+            assertThat(Files.isSymbolicLink(link)).isTrue();
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"db/foo/kv-0", "db/table-1/kv-abc", "db/foo/partition-p1/kv-abc"})
+    void testStartupCleanupDoesNotRequireValidTabletIds(String path) throws Exception {
+        Path staleDir = Files.createDirectories(tempDir.toPath().resolve(path));
+        Files.write(staleDir.resolve("data"), new byte[] {1});
+
+        kvManager.startup();
+
+        assertThat(staleDir).doesNotExist();
+        assertThat(tempDir.toPath().resolve("db")).doesNotExist();
+        assertThat(tempDir).isDirectory();
+    }
+
+    @Test
+    void testStartupCleanupDoesNotFollowLinksInsideKv(@TempDir Path outsideDir) throws Exception {
+        Path outsideFile = Files.write(outsideDir.resolve("data"), new byte[] {1, 2, 3});
+        Path staleDir = Files.createDirectories(tempDir.toPath().resolve("db/table-1/kv-0"));
+        Files.createSymbolicLink(staleDir.resolve("db"), outsideDir);
+
+        kvManager.startup();
+
+        assertThat(staleDir).doesNotExist();
+        assertThat(Files.readAllBytes(outsideFile)).containsExactly(1, 2, 3);
+    }
+
     @Test
     void testPositiveSharedBlockCacheSizeEnablesSharedCache() throws Exception {
         kvManager.shutdown();
@@ -265,7 +569,7 @@ final class KvManagerTest {
         kvManager =
                 KvManager.create(
                         conf, zkClient, logManager, recoveredMetricGroup, localDiskManager);
-        kvManager.startup();
+        // Reopen preserved local state directly, without TabletServer startup cleanup.
         KvTablet loadedKv =
                 kvManager.loadKv(
                         secondKvDir,
@@ -305,7 +609,7 @@ final class KvManagerTest {
 
     @ParameterizedTest
     @MethodSource("partitionProvider")
-    void testRecoveryAfterKvManagerShutDown(String partitionName) throws Exception {
+    void testReopenKvDirectlyWithoutStartupCleanup(String partitionName) throws Exception {
         initTableBuckets(partitionName);
         KvTablet kv1 = getOrCreateKv(tablePath1, partitionName, tableBucket1);
         int kvRecordCount = 50;
@@ -322,7 +626,7 @@ final class KvManagerTest {
         }
         put(kv2, kvRecords2);
 
-        // restart
+        // Close and directly reopen the preserved local state.
         kvManager.shutdown();
         kvManager =
                 KvManager.create(
@@ -331,7 +635,7 @@ final class KvManagerTest {
                         logManager,
                         TestingMetricGroups.TABLET_SERVER_METRICS,
                         localDiskManager);
-        kvManager.startup();
+        // Reopen preserved local state directly, without TabletServer startup cleanup.
         kv1 = getOrCreateKv(tablePath1, partitionName, tableBucket1);
         kv2 = getOrCreateKv(tablePath2, partitionName, tableBucket2);
 
@@ -355,7 +659,8 @@ final class KvManagerTest {
 
     @ParameterizedTest
     @MethodSource("partitionProvider")
-    void testDiscardShutdownDoesNotPersistUnflushedState(String partitionName) throws Exception {
+    void testDirectReopenAfterDiscardShutdownDoesNotPersistUnflushedState(String partitionName)
+            throws Exception {
         initTableBuckets(partitionName);
         KvTablet kv = getOrCreateKv(tablePath1, partitionName, tableBucket1);
         byte[] key = "discarded-key".getBytes(StandardCharsets.UTF_8);
@@ -369,7 +674,7 @@ final class KvManagerTest {
                         logManager,
                         TestingMetricGroups.TABLET_SERVER_METRICS,
                         localDiskManager);
-        kvManager.startup();
+        // Reopen preserved local state directly, without TabletServer startup cleanup.
 
         KvTablet reopened = getOrCreateKv(tablePath1, partitionName, tableBucket1);
         assertThat(toByteArrays(reopened.multiGet(Collections.singletonList(key))))
@@ -378,21 +683,22 @@ final class KvManagerTest {
 
     @ParameterizedTest
     @MethodSource("partitionProvider")
-    void testRecoveryWithSchemaChange(String partitionName) throws Exception {
+    void testDirectReopenWithSchemaChangeWithoutStartupCleanup(String partitionName)
+            throws Exception {
         TestingSchemaGetter testingSchemaGetter =
                 new TestingSchemaGetter(new SchemaInfo(DATA1_SCHEMA_PK, 1));
         initTableBuckets(partitionName);
         KvTablet kv1 = getOrCreateKv(tablePath1, partitionName, tableBucket1, testingSchemaGetter);
         int kvRecordCount = 50;
 
-        // insert before restart.
+        // Insert before closing the manager.
         KvRecord[] kvRecords1 = new KvRecord[kvRecordCount];
         for (int i = 0; i < kvRecordCount; i++) {
             kvRecords1[i] = kvRecordFactory.ofRecord(("key" + i).getBytes(), new Object[] {i, "a"});
         }
         put(kv1, kvRecords1);
 
-        // restart with schema change
+        // Close and directly reopen with a schema change.
         short newSchemaId = 2;
         kvManager.shutdown();
         testingSchemaGetter.updateLatestSchemaInfo(new SchemaInfo(DATA2_SCHEMA, newSchemaId));
@@ -403,9 +709,9 @@ final class KvManagerTest {
                         logManager,
                         TestingMetricGroups.TABLET_SERVER_METRICS,
                         localDiskManager);
-        kvManager.startup();
+        // Reopen preserved local state directly, without TabletServer startup cleanup.
 
-        // insert again after restart.
+        // Insert again after reopening the local state.
         kv1 = getOrCreateKv(tablePath1, partitionName, tableBucket1, testingSchemaGetter);
         KvRecordTestUtils.KvRecordBatchFactory batchFactoryOfSchema2 =
                 KvRecordTestUtils.KvRecordBatchFactory.of(newSchemaId);
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java
index 1460553fd..d1921f7df 100644
--- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java
+++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java
@@ -28,16 +28,24 @@ import org.apache.fluss.rpc.gateway.TabletServerGateway;
 import org.apache.fluss.rpc.messages.ErrorMessage;
 import org.apache.fluss.rpc.protocol.Errors;
 import org.apache.fluss.server.log.LogSegment;
+import org.apache.fluss.server.replica.Replica;
 import org.apache.fluss.server.testutils.FlussClusterExtension;
 import org.apache.fluss.server.zk.ZooKeeperClient;
 import org.apache.fluss.server.zk.data.LeaderAndIsr;
 import org.apache.fluss.types.DataTypes;
+import org.apache.fluss.utils.FlussPaths;
+import org.apache.fluss.utils.types.Tuple2;
 
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.RegisterExtension;
 import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.ValueSource;
+import org.rocksdb.FlushOptions;
 
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -45,14 +53,22 @@ import java.util.List;
 import java.util.concurrent.ExecutionException;
 
 import static org.apache.fluss.record.TestData.DATA1;
+import static org.apache.fluss.record.TestData.DATA1_SCHEMA_PK;
 import static org.apache.fluss.record.TestData.DATA_1_WITH_KEY_AND_VALUE;
+import static org.apache.fluss.server.kv.KvTabletTestUtils.flushAndWait;
+import static org.apache.fluss.server.testutils.KvTestUtils.assertLookupResponse;
 import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createTable;
+import static org.apache.fluss.server.testutils.RpcMessageTestUtils.dropTable;
+import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newLookupRequest;
 import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newProduceLogRequest;
 import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newPutKvRequest;
 import static org.apache.fluss.testutils.DataTestUtils.genKvRecordBatch;
+import static org.apache.fluss.testutils.DataTestUtils.genKvRecords;
 import static org.apache.fluss.testutils.DataTestUtils.genMemoryLogRecordsByObject;
+import static org.apache.fluss.testutils.DataTestUtils.getKeyValuePairs;
 import static org.apache.fluss.testutils.common.CommonTestUtils.retry;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assumptions.assumeThat;
 
 /** The ITCase for tabletServer shutdown (controlled shutdown). */
 public class TabletServerShutdownITCase {
@@ -196,6 +212,155 @@ public class TabletServerShutdownITCase {
         FLUSS_CLUSTER_EXTENSION.startTabletServer(leader, true);
     }
 
+    @Test
+    void testControlledShutdownCleansKvWhenRestartedAsFollower() throws Exception {
+        TablePath tablePath = TablePath.of("test_shutdown", "kv_orphan_cleanup");
+        long tableId =
+                createTable(
+                        FLUSS_CLUSTER_EXTENSION,
+                        tablePath,
+                        TableDescriptor.builder()
+                                .schema(DATA1_SCHEMA_PK)
+                                .distributedBy(1)
+                                .property(ConfigOptions.TABLE_REPLICATION_FACTOR, 3)
+                                .build());
+        TableBucket tableBucket = new TableBucket(tableId, 0);
+        FLUSS_CLUSTER_EXTENSION.waitUntilAllReplicaReady(tableBucket);
+        int oldLeader = FLUSS_CLUSTER_EXTENSION.waitAndGetLeader(tableBucket);
+        TabletServerGateway gateway =
+                FLUSS_CLUSTER_EXTENSION.newTabletServerClientForNode(oldLeader);
+        assertThat(writeData(gateway, tableId, false).hasErrorCode()).isFalse();
+        Replica replica = FLUSS_CLUSTER_EXTENSION.waitAndGetLeaderReplica(tableBucket);
+        flushAndWait(replica.getKvTablet(), Long.MAX_VALUE);
+        try (FlushOptions flushOptions = new FlushOptions().setWaitForFlush(true)) {
+            replica.getKvTablet().getRocksDBKv().getDb().flush(flushOptions);
+        }
+        File kvDir = replica.getKvTablet().getKvTabletDir();
+        File logDir = replica.getLogTablet().getLogDir();
+
+        FLUSS_CLUSTER_EXTENSION.stopTabletServer(oldLeader);
+        try {
+            // Controlled shutdown closes the old leader's RocksDB without deleting its files.
+            assertThat(kvDir).isDirectory();
+            assertThat(kvDir.toPath().resolve("db"))
+                    .isDirectoryContaining(path -> path.toString().endsWith(".sst"));
+        } finally {
+            FLUSS_CLUSTER_EXTENSION.startTabletServer(oldLeader);
+        }
+
+        Replica follower =
+                FLUSS_CLUSTER_EXTENSION.waitAndGetFollowerReplica(tableBucket, oldLeader);
+        assertThat(follower.getKvTablet()).isNull();
+        assertThat(kvDir).doesNotExist();
+        assertThat(logDir).isDirectory();
+
+        dropTable(FLUSS_CLUSTER_EXTENSION, tablePath);
+        retry(
+                Duration.ofMinutes(1),
+                () -> {
+                    assertThat(logDir).doesNotExist();
+                    assertThat(kvDir.getParentFile()).doesNotExist();
+                });
+    }
+
+    @ParameterizedTest
+    @CsvSource({"true, false", "false, false", "true, true", "false, true"})
+    void testKvRecoveryAfterStartupCleanup(boolean withSnapshot, boolean failCleanup)
+            throws Exception {
+        TablePath tablePath =
+                TablePath.of(
+                        "test_shutdown", "kv_startup_recovery_" + withSnapshot + "_" + failCleanup);
+        long tableId =
+                createTable(
+                        FLUSS_CLUSTER_EXTENSION,
+                        tablePath,
+                        TableDescriptor.builder()
+                                .schema(DATA1_SCHEMA_PK)
+                                .distributedBy(1)
+                                .property(ConfigOptions.TABLE_REPLICATION_FACTOR, 1)
+                                .build());
+        TableBucket tableBucket = new TableBucket(tableId, 0);
+        Replica replica = FLUSS_CLUSTER_EXTENSION.waitAndGetLeaderReplica(tableBucket);
+        int leader = FLUSS_CLUSTER_EXTENSION.waitAndGetLeader(tableBucket);
+        TabletServerGateway gateway = FLUSS_CLUSTER_EXTENSION.newTabletServerClientForNode(leader);
+        assertThat(writeData(gateway, tableId, false).hasErrorCode()).isFalse();
+        flushAndWait(replica.getKvTablet(), Long.MAX_VALUE);
+        if (withSnapshot) {
+            FLUSS_CLUSTER_EXTENSION.triggerAndWaitSnapshot(tableBucket);
+        }
+
+        // This update is recovered from the log, including when an older snapshot exists.
+        assertThat(
+                        gateway.putKv(
+                                        newPutKvRequest(
+                                                tableId,
+                                                0,
+                                                1,
+                                                genKvRecordBatch(new Object[] {1, "updated"})))
+                                .get()
+                                .getBucketsRespAt(0)
+                                .hasErrorCode())
+                .isFalse();
+        File kvDir = replica.getKvTablet().getKvTabletDir();
+        Path staleFile = kvDir.toPath().resolve("stale-file");
+        Files.write(staleFile, new byte[] {1});
+
+        FLUSS_CLUSTER_EXTENSION.stopTabletServer(leader);
+        boolean restarted = false;
+        try {
+            if (failCleanup) {
+                // The tablet can be renamed, but recursive deletion of its RocksDB files fails.
+                File dbDir = new File(kvDir, "db");
+                assertThat(dbDir.setWritable(false)).isTrue();
+                assumeThat(Files.isWritable(dbDir.toPath())).isFalse();
+            }
+            FLUSS_CLUSTER_EXTENSION.startTabletServer(leader);
+            restarted = true;
+            Replica recovered = FLUSS_CLUSTER_EXTENSION.waitAndGetLeaderReplica(tableBucket);
+            assertThat(staleFile).doesNotExist();
+            assertThat(kvDir).isDirectory();
+            if (failCleanup) {
+                File[] pendingDeletionDirs =
+                        kvDir.getParentFile()
+                                .listFiles(
+                                        file ->
+                                                file.getName().startsWith(kvDir.getName() + ".")
+                                                        && file.getName()
+                                                                .endsWith(
+                                                                        FlussPaths
+                                                                                .DELETED_FILE_SUFFIX));
+                assertThat(pendingDeletionDirs).hasSize(1);
+                assertThat(new File(pendingDeletionDirs[0], "db")).isDirectory();
+            }
+            assertThat(recovered.getRowCount()).isEqualTo(2L);
+            TabletServerGateway recoveredGateway =
+                    FLUSS_CLUSTER_EXTENSION.newTabletServerClientForNode(leader);
+            for (Tuple2<byte[], byte[]> keyValue :
+                    getKeyValuePairs(
+                            genKvRecords(new Object[] {1, "updated"}, new Object[] {2, "b1"}))) {
+                assertLookupResponse(
+                        recoveredGateway.lookup(newLookupRequest(tableId, 0, keyValue.f0)).get(),
+                        keyValue.f1);
+            }
+        } finally {
+            if (failCleanup) {
+                // Restore permissions at either the original path or the renamed deletion path.
+                File[] tabletDirs = kvDir.getParentFile().listFiles(File::isDirectory);
+                assertThat(tabletDirs).isNotNull();
+                for (File tabletDir : tabletDirs) {
+                    File dbDir = new File(tabletDir, "db");
+                    if (dbDir.exists()) {
+                        assertThat(dbDir.setWritable(true)).isTrue();
+                    }
+                }
+            }
+            if (!restarted) {
+                FLUSS_CLUSTER_EXTENSION.startTabletServer(leader);
+            }
+        }
+        dropTable(FLUSS_CLUSTER_EXTENSION, tablePath);
+    }
+
     @Test
     void testControlledShutdownRetriesFailover() throws Exception {
         // This case is to test the scenario that the controlled shutdown request is retried and