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

gavinchou pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new a0443d84a38 [fix](storage) Fix file cache and storage failures exposed 
by BE unit tests (#71328)
a0443d84a38 is described below

commit a0443d84a38e4b9d14973acbe093462369768551
Author: Mingyu Chen (Rayner) <[email protected]>
AuthorDate: Thu Dec 3 19:25:24 2026 +0800

    [fix](storage) Fix file cache and storage failures exposed by BE unit tests 
(#71328)
    
    ### Background
    
    The BE file cache keeps local file readers in an LRU cache and runs
    separate threads for TTL maintenance and stale-file cleanup. Local
    storage engines send cooldown metadata to remote storage so other
    replicas can follow it. Several storage-engine tests share process-wide
    caches keyed by rowset ID.
    
    ### What problem does this PR solve?
    
    Issue Number: #71314
    Related PR: #57922 (TTL manager), #59269 (leak cleaner), #21975
    (file-reader cache), #16813 (async cooldown metadata upload), #1678
    (rowset ID generator), #68436 (cloud test workaround)
    PR Type: Bugfix
    
    Problem Summary: File cache workers can delay shutdown. Cooldown writers
    can use destroyed state or retry failed uploads in a tight loop. Engines
    using default options can read each other's cached segments. After
    filling the FD cache with four readers and lowering the limit to two,
    the next insertion used to grow the cache to five readers. It now leaves
    two.
    
    ### Details
    
    - **Change map:** 132 lines in production files and 370 test lines
    changed across ten commits. The changes below list each commit in review
    order.
    
      | Commit | Purpose |
      | --- | --- |
    | Wake TTL manager threads | Interrupt interval and exception waits on
    shutdown. |
    | Join cooldown metadata writers | Keep executor state alive through
    worker exit. |
    | Tear down the cooldown fixture | Release its executors before
    destroying its engine and storage policy. |
    | Shrink the FD cache | Evict to the new limit on the next insertion of
    a new key. |
    | Give default engines distinct backend UIDs | Prevent rowset ID
    collisions and use the actual output rowset IDs in the index tests. |
    | Reject negative FD cache capacity | Validate the value at startup and
    on runtime updates. |
    | Synchronize leak-cleaner stop | Close the lost-notification window
    before a condition-variable wait. |
    | Defer failed cooldown writes | Resubmit failed tablets from the next
    cooldown round. |
    | Isolate cache settings in tests | Keep the cooldown mock independent
    of the file cache and remove scan interval writes from synchronous
    tests. |
    | Explain the mutexes | Document the TTL lost-wakeup window and
    concurrent cooldown retry bookkeeping. |
    
    - **Frequency:** TTL stops stall during interval waits. Leak-cleaner and
    executor shutdown failures depend on thread scheduling. Any new key
    inserted into an over-capacity FD cache triggers the eviction bug.
    Persistent non-`ABORTED` cooldown failures trigger immediate retries.
    Default-option engines generate matching IDs at equal sequence
    positions.
    - **Root cause:** The TTL manager used uninterruptible sleeps, and the
    leak cleaner published its stop flag outside the wait mutex. FD cache
    eviction tested for equality against the limit. Cooldown workers used
    members after their destruction started and requeued themselves on
    failure. Default engine options used an all-zero backend UID.
    - **Why existing tests missed it:** The TTL and leak-cleaner tests used
    short waits. FD cache tests set a valid limit before filling the cache.
    `TabletCooldownTest` checked results without controlling teardown or
    counting retries. Rowset ID tests used explicit UIDs. Cold-data and
    storage-policy regression suites run successful cooldown against
    reachable storage.
    - **Fix:** Use interruptible waits and publish stops under the wait
    mutexes. Evict LRU readers until the new key fits, and validate the
    limit. Join cooldown writers while their state is alive and retry
    through the producer. Generate an independent UID for default engine
    options.
    - **Other paths and branches:** Both leak-cleaner waits use the same
    predicate. The cooldown retry change applies to local storage. The TTL
    and leak-cleaner bugs are present in 4.1 and 4.2. The FD config,
    cooldown retry and default UID code are also present in 3.1 and 4.0.
    Production BE startup already sets an explicit UID.
    - **Configs and defaults:** `file_cache_max_file_reader_cache_size`
    stays mutable and defaults to `1000000`. Valid values are zero
    (disabled) and positive capacities.
    - **Behavior change:** A negative FD cache limit now fails startup
    validation or returns an error from a runtime update. A failed cooldown
    upload is retried on the next producer round (20 seconds by default),
    and dropped tablets are skipped.
    
    ### Testing
    
    - Pre-fix regressions caught the blocked shutdowns, repeated cooldown
    retries, a cache growing past its new limit, acceptance of negative
    capacities, and equal rowset IDs across default engines.
    - Standalone macOS ASAN `run-be-ut.sh --run -j 6` ran 288 cases.
    Registration order had 285 passes and 3 skips. Shuffle seed 48256 had
    283 passes, the same 3 skips, and two existing test-isolation failures
    tracked in #71314: `BlockFileCacheTest.fd_cache_remove` and
    `BlockFileCacheTest.reader_dryrun_when_download_file_cache`. All new
    regressions passed in both runs.
    
    ### Release note
    
    Idle file cache workers wake promptly on BE shutdown. The file-reader
    cache shrinks to a lowered positive limit on the next insertion of a new
    key. Correct negative `file_cache_max_file_reader_cache_size` settings
    before upgrading. Failed cooldown metadata uploads retry on a subsequent
    cooldown round.
---
 be/src/common/config.cpp                           |   3 +
 be/src/io/cache/block_file_cache_ttl_mgr.cpp       |  27 +++-
 be/src/io/cache/block_file_cache_ttl_mgr.h         |   9 ++
 be/src/io/cache/fs_file_cache_storage.cpp          |  32 +++--
 be/src/storage/olap_server.cpp                     |   3 +
 be/src/storage/options.h                           |   7 +-
 be/src/storage/tablet/tablet.cpp                   |  43 +++++-
 be/src/storage/tablet/tablet.h                     |   8 ++
 be/test/cloud/cloud_tablet_test.cpp                |  11 +-
 be/test/io/cache/block_file_cache_test.cpp         |  59 +++++++++
 be/test/io/cache/block_file_cache_ttl_mgr_test.cpp |  15 +++
 .../fs_file_cache_storage_leak_cleaner_test.cpp    |  64 ++++++++-
 be/test/storage/index/index_builder_test.cpp       |  57 ++++----
 .../rowset/unique_rowset_id_generator_test.cpp     |  17 +++
 be/test/storage/tablet/tablet_cooldown_test.cpp    | 147 +++++++++++++++++++++
 15 files changed, 439 insertions(+), 63 deletions(-)

diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index 0e59ff6f9cb..f7f4f285800 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -1558,6 +1558,9 @@ DEFINE_Validator(s3_write_buffer_size, [](int64_t value) {
 // Log interval when doing s3 upload task
 DEFINE_mInt32(s3_file_writer_log_interval_second, "60");
 DEFINE_mInt64(file_cache_max_file_reader_cache_size, "1000000");
+// 0 disables the FD cache. A negative capacity would never be reached, so the 
cache would keep
+// every reader and its open file.
+DEFINE_Validator(file_cache_max_file_reader_cache_size, [](int64_t value) { 
return value >= 0; });
 // When file cache is enabled, the configured bytes must be divisible by
 // file_cache_each_block_size so every non-EOF HDFS cache block is canonical.
 DEFINE_mInt64(hdfs_write_batch_buffer_size_mb, "1"); // 1MB
diff --git a/be/src/io/cache/block_file_cache_ttl_mgr.cpp 
b/be/src/io/cache/block_file_cache_ttl_mgr.cpp
index 924526709b8..3c3d48e4b9b 100644
--- a/be/src/io/cache/block_file_cache_ttl_mgr.cpp
+++ b/be/src/io/cache/block_file_cache_ttl_mgr.cpp
@@ -52,7 +52,14 @@ BlockFileCacheTtlMgr::~BlockFileCacheTtlMgr() {
 
 void BlockFileCacheTtlMgr::stop() {
     std::lock_guard<std::mutex> lifecycle_lock(_thread_lifecycle_mutex);
-    _stop_background.store(true, std::memory_order_release);
+    {
+        // A worker can read the atomic stop flag as false just before it 
starts waiting.
+        // Set the flag under the wait mutex so the notification cannot land 
in that gap
+        // and leave the worker asleep until its interval expires.
+        std::lock_guard<std::mutex> lock(_stop_mutex);
+        _stop_background.store(true, std::memory_order_release);
+    }
+    _stop_cv.notify_all();
 
     if (_update_ttl_thread.joinable()) {
         _update_ttl_thread.join();
@@ -87,6 +94,14 @@ void BlockFileCacheTtlMgr::register_tablet_id(int64_t 
tablet_id) {
     _tablet_id_queue.enqueue(tablet_id);
 }
 
+void BlockFileCacheTtlMgr::wait_for_stop(std::chrono::milliseconds interval) {
+    // Use stop()'s mutex for the predicate. wait_for releases it as the 
worker goes to sleep
+    // and reacquires it before checking the flag again.
+    std::unique_lock<std::mutex> lock(_stop_mutex);
+    _stop_cv.wait_for(lock, interval,
+                      [this]() { return 
_stop_background.load(std::memory_order_acquire); });
+}
+
 void BlockFileCacheTtlMgr::update_ttl_info_map_size_metrics() {
     if (_ttl_info_map_size_metrics) {
         _ttl_info_map_size_metrics->set_value(_ttl_info_map.size());
@@ -136,7 +151,7 @@ void BlockFileCacheTtlMgr::run_background_tablet_id_flush() 
{
         flush_pending(&pending);
 
         if (!drained) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(
+            wait_for_stop(std::chrono::milliseconds(
                     
config::file_cache_background_tablet_id_flush_interval_ms));
         }
     }
@@ -345,12 +360,12 @@ void 
BlockFileCacheTtlMgr::run_backgroud_update_ttl_info_map() {
                 }
             }
 
-            std::this_thread::sleep_for(std::chrono::milliseconds(
+            wait_for_stop(std::chrono::milliseconds(
                     
config::file_cache_background_ttl_info_update_interval_ms));
 
         } catch (const std::exception& e) {
             LOG(WARNING) << "Exception in TTL update thread: " << e.what();
-            std::this_thread::sleep_for(std::chrono::seconds(10));
+            wait_for_stop(std::chrono::seconds(10));
         }
     }
 }
@@ -382,12 +397,12 @@ void 
BlockFileCacheTtlMgr::run_backgroud_expiration_check() {
                 reconcile_tablet_blocks(tablet_id);
             }
 
-            std::this_thread::sleep_for(
+            wait_for_stop(
                     
std::chrono::milliseconds(config::file_cache_background_ttl_gc_interval_ms));
 
         } catch (const std::exception& e) {
             LOG(WARNING) << "Exception in TTL expiration check thread: " << 
e.what();
-            std::this_thread::sleep_for(std::chrono::seconds(10));
+            wait_for_stop(std::chrono::seconds(10));
         }
     }
 }
diff --git a/be/src/io/cache/block_file_cache_ttl_mgr.h 
b/be/src/io/cache/block_file_cache_ttl_mgr.h
index 59e2233f284..303a3eb777a 100644
--- a/be/src/io/cache/block_file_cache_ttl_mgr.h
+++ b/be/src/io/cache/block_file_cache_ttl_mgr.h
@@ -24,6 +24,8 @@
 
 #include <array>
 #include <atomic>
+#include <chrono>
+#include <condition_variable>
 #include <limits>
 #include <map>
 #include <memory>
@@ -92,6 +94,9 @@ private:
     // Caller must hold _ttl_info_mutex.
     void update_ttl_info_map_size_metrics();
 
+    // Waits for `interval`, or less once stop() is called.
+    void wait_for_stop(std::chrono::milliseconds interval);
+
     std::mutex& transition_lock_for(int64_t tablet_id) {
         return _transition_locks[static_cast<uint64_t>(tablet_id) % 
kTransitionLockStripes];
     }
@@ -107,6 +112,10 @@ private:
     CacheBlockMetaStore* _meta_store;
 
     std::atomic<bool> _stop_background;
+    // stop() sets _stop_background under this mutex and notifies, so the 
background threads
+    // leave their interval waits at once instead of sleeping out the interval.
+    std::mutex _stop_mutex;
+    std::condition_variable _stop_cv;
     std::thread _update_ttl_thread;
     std::thread _expiration_check_thread;
     std::thread _tablet_id_flush_thread;
diff --git a/be/src/io/cache/fs_file_cache_storage.cpp 
b/be/src/io/cache/fs_file_cache_storage.cpp
index 289aed50d70..6ffed81792b 100644
--- a/be/src/io/cache/fs_file_cache_storage.cpp
+++ b/be/src/io/cache/fs_file_cache_storage.cpp
@@ -111,13 +111,17 @@ std::shared_ptr<FileReader> 
FDCache::get_file_reader(const AccessKeyAndOffset& k
 
 void FDCache::insert_file_reader(const AccessKeyAndOffset& key,
                                  std::shared_ptr<FileReader> file_reader) {
-    if (config::file_cache_max_file_reader_cache_size == 0) [[unlikely]] {
+    // Read once: the capacity is a mutable config.
+    const int64_t capacity = config::file_cache_max_file_reader_cache_size;
+    if (capacity == 0) [[unlikely]] {
         return;
     }
     std::lock_guard wlock(_mtx);
 
     if (auto iter = _file_name_to_reader.find(key); iter == 
_file_name_to_reader.end()) {
-        if (config::file_cache_max_file_reader_cache_size == 
_file_reader_list.size()) {
+        // Evict down to the capacity rather than one reader: the capacity may 
have been lowered
+        // since the cache last filled up.
+        while (_file_reader_list.size() >= static_cast<size_t>(capacity)) {
             _file_name_to_reader.erase(_file_reader_list.back().first);
             _file_reader_list.pop_back();
         }
@@ -1542,8 +1546,16 @@ void 
FSFileCacheStorage::start_leak_cleaner(BlockFileCache* mgr) {
 }
 
 void FSFileCacheStorage::stop_leak_cleaner() {
-    _stop_leak_cleaner.store(true, std::memory_order_relaxed);
+    {
+        // The loop checks the flag under this mutex right before it waits. 
Setting the flag
+        // without the mutex could land, with the notification, between that 
check and the wait:
+        // the loop would miss the notification and sleep a whole scan 
interval, and so would the
+        // join() below.
+        std::lock_guard<std::mutex> lock(_leak_cleaner_mutex);
+        _stop_leak_cleaner.store(true, std::memory_order_relaxed);
+    }
     _leak_cleaner_cv.notify_all();
+    TEST_SYNC_POINT("FSFileCacheStorage::stop_leak_cleaner::notified");
     if (_cache_leak_cleaner_thread.joinable()) {
         _cache_leak_cleaner_thread.join();
     }
@@ -1561,11 +1573,15 @@ void FSFileCacheStorage::leak_cleaner_loop() {
     int64_t initial_delay = dist(rng);
     
TEST_SYNC_POINT_CALLBACK("FSFileCacheStorage::leak_cleaner_loop::initial_delay",
                              &initial_delay);
+    // Called with _leak_cleaner_mutex held, before each wait.
+    auto stop_requested = [this]() {
+        bool stop = _stop_leak_cleaner.load(std::memory_order_relaxed);
+        
TEST_SYNC_POINT_CALLBACK("FSFileCacheStorage::leak_cleaner_loop::stop_checked", 
&stop);
+        return stop;
+    };
     if (initial_delay > 0) {
         std::unique_lock<std::mutex> lock(_leak_cleaner_mutex);
-        _leak_cleaner_cv.wait_for(lock, std::chrono::seconds(initial_delay), 
[this]() {
-            return _stop_leak_cleaner.load(std::memory_order_relaxed);
-        });
+        _leak_cleaner_cv.wait_for(lock, std::chrono::seconds(initial_delay), 
stop_requested);
         lock.unlock();
         if (_stop_leak_cleaner.load(std::memory_order_relaxed)) {
             return;
@@ -1577,9 +1593,7 @@ void FSFileCacheStorage::leak_cleaner_loop() {
         
TEST_SYNC_POINT_CALLBACK("FSFileCacheStorage::leak_cleaner_loop::interval", 
&interval_s);
         auto interval = std::chrono::seconds(interval_s);
         std::unique_lock<std::mutex> lock(_leak_cleaner_mutex);
-        _leak_cleaner_cv.wait_for(lock, interval, [this]() {
-            return _stop_leak_cleaner.load(std::memory_order_relaxed);
-        });
+        _leak_cleaner_cv.wait_for(lock, interval, stop_requested);
         lock.unlock();
         if (_stop_leak_cleaner.load(std::memory_order_relaxed)) {
             break;
diff --git a/be/src/storage/olap_server.cpp b/be/src/storage/olap_server.cpp
index 53498210581..4b27bcf3032 100644
--- a/be/src/storage/olap_server.cpp
+++ b/be/src/storage/olap_server.cpp
@@ -57,6 +57,7 @@
 #include "io/fs/file_writer.h" // IWYU pragma: keep
 #include "io/fs/path.h"
 #include "load/memtable/memtable_flush_executor.h"
+#include "runtime/exec_env.h"
 #include "runtime/memory/cache_manager.h"
 #include "runtime/memory/global_memory_arbitrator.h"
 #include "service/backend_options.h"
@@ -1352,6 +1353,8 @@ void StorageEngine::_cooldown_tasks_producer_callback() {
     // until it has done uploaded
     int64_t skip_failed_interval = interval * 10;
     do {
+        // Cooldown meta writes that failed since the last round are retried 
here, once a round.
+        
ExecEnv::GetInstance()->write_cooldown_meta_executors()->resubmit_failed(*_tablet_manager);
         // these tables are ordered by priority desc
         std::vector<TabletSharedPtr> tablets;
         std::vector<RowsetSharedPtr> rowsets;
diff --git a/be/src/storage/options.h b/be/src/storage/options.h
index cb352e56f6e..01e1e624760 100644
--- a/be/src/storage/options.h
+++ b/be/src/storage/options.h
@@ -80,7 +80,10 @@ struct EngineOptions {
     // list paths that tablet will be put into.
     std::vector<StorePath> store_paths;
     std::set<std::string> broken_paths;
-    // BE's UUID. It will be reset every time BE restarts.
-    UniqueId backend_uid {0, 0};
+    // BE's UUID, which rowset ids are generated from. It changes every time 
BE restarts, and each
+    // engine built from default options gets its own: the segment cache and 
the page cache, keyed
+    // on rowset ids and on the file names made from them, outlive an engine 
(a unit test process
+    // builds one engine per case).
+    UniqueId backend_uid = UniqueId::gen_uid();
 };
 } // namespace doris
diff --git a/be/src/storage/tablet/tablet.cpp b/be/src/storage/tablet/tablet.cpp
index 7ab8d1fa36d..fd6c8ab650e 100644
--- a/be/src/storage/tablet/tablet.cpp
+++ b/be/src/storage/tablet/tablet.cpp
@@ -70,6 +70,7 @@
 #include "core/data_type/data_type_factory.hpp"
 #include "core/data_type_serde/data_type_serde.h"
 #include "core/string_ref.h"
+#include "cpp/sync_point.h"
 #include "io/fs/file_reader.h"
 #include "io/fs/file_reader_writer_fwd.h"
 #include "io/fs/file_system.h"
@@ -185,6 +186,22 @@ 
WriteCooldownMetaExecutors::WriteCooldownMetaExecutors(size_t executor_nums)
     }
 }
 
+WriteCooldownMetaExecutors::~WriteCooldownMetaExecutors() {
+    // Members are destroyed in reverse order of declaration: _latch, 
_failed_tablets and
+    // _pending_tablets before _executors, whose destructors join the workers. 
Until then a worker
+    // may still run a task, which erases its tablet from _pending_tablets 
under _latch and, when
+    // the write fails with anything but ABORTED, adds the tablet to 
_failed_tablets under _latch.
+    // Example: the storage policy of a tablet has been dropped, so its write 
fails with NOT_FOUND
+    // while the executors are destroyed with ExecEnv; the task would lock the 
destroyed _latch
+    // (libc++ throws "mutex lock failed") and insert into a freed set. Stop 
every executor first,
+    // so that offer() rejects new tasks and the workers leave their loops, 
then join all of them
+    // while every executor still exists.
+    stop();
+    for (auto& pool_ptr : _executors) {
+        pool_ptr->join();
+    }
+}
+
 void WriteCooldownMetaExecutors::stop() {
     for (auto& pool_ptr : _executors) {
         if (pool_ptr) {
@@ -223,13 +240,20 @@ void 
WriteCooldownMetaExecutors::WriteCooldownMetaExecutors::submit(TabletShared
         }
         SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->orphan_mem_tracker());
         auto s = t->write_cooldown_meta();
+        
TEST_SYNC_POINT_CALLBACK("WriteCooldownMetaExecutors::write_cooldown_meta", 
t.get(), &s);
         if (s.ok()) {
             return;
         }
         if (!s.is<ABORTED>()) {
             LOG_EVERY_SECOND(WARNING)
                     << "write tablet " << t->tablet_id() << " cooldown meta 
failed because: " << s;
-            submit(t);
+            // Retry in the cooldown producer's next round 
(resubmit_failed()), not right away: a
+            // write that keeps failing, say because its storage policy is 
missing or the remote
+            // storage is down, would keep the only thread of this executor 
busy retrying.
+            // Other workers can report failures and the cooldown producer can 
take the set
+            // concurrently, so every insertion into _failed_tablets needs 
_latch.
+            std::unique_lock<std::mutex> lck {_latch};
+            _failed_tablets.insert(t->tablet_id());
             return;
         }
         VLOG_DEBUG << "tablet " << t->tablet_id() << " is not cooldown 
replica";
@@ -244,6 +268,23 @@ void 
WriteCooldownMetaExecutors::WriteCooldownMetaExecutors::submit(TabletShared
     });
 }
 
+void WriteCooldownMetaExecutors::resubmit_failed(TabletManager& 
tablet_manager) {
+    std::unordered_set<int64_t> failed_tablets;
+    {
+        // The swap is protected from concurrent inserts. Failures reported 
after it stay
+        // in _failed_tablets for the next round.
+        std::unique_lock<std::mutex> lck {_latch};
+        failed_tablets.swap(_failed_tablets);
+    }
+    // Submit after releasing _latch because submit() takes it to update 
_pending_tablets.
+    for (int64_t tablet_id : failed_tablets) {
+        // `tablet` is nullptr if the tablet has been dropped since its write 
failed.
+        if (auto tablet = tablet_manager.get_tablet(tablet_id); tablet != 
nullptr) {
+            submit(std::move(tablet));
+        }
+    }
+}
+
 Tablet::Tablet(StorageEngine& engine, TabletMetaSharedPtr tablet_meta, 
DataDir* data_dir,
                const std::string_view& cumulative_compaction_type)
         : BaseTablet(std::move(tablet_meta)),
diff --git a/be/src/storage/tablet/tablet.h b/be/src/storage/tablet/tablet.h
index 0fd70de3a6c..9639cd4a156 100644
--- a/be/src/storage/tablet/tablet.h
+++ b/be/src/storage/tablet/tablet.h
@@ -63,6 +63,7 @@ class Adder;
 namespace doris {
 
 class Tablet;
+class TabletManager;
 class CumulativeCompactionPolicy;
 class CompactionMixin;
 class RowsetWriter;
@@ -94,10 +95,15 @@ static inline constexpr auto TRACE_TABLET_LOCK_THRESHOLD = 
std::chrono::seconds(
 
 struct WriteCooldownMetaExecutors {
     WriteCooldownMetaExecutors(size_t executor_nums = 5);
+    ~WriteCooldownMetaExecutors();
 
     void stop();
 
     void submit(TabletSharedPtr tablet);
+    // Submits again the tablets with a write that failed with anything but 
ABORTED since the last
+    // call. A failed write does not resubmit itself: StorageEngine's cooldown 
producer calls this
+    // once a round, which spaces the attempts of a write that keeps failing.
+    void resubmit_failed(TabletManager& tablet_manager);
     size_t _get_executor_pos(int64_t tablet_id) const {
         return std::hash<int64_t>()(tablet_id) % _executor_nums;
     };
@@ -109,6 +115,8 @@ struct WriteCooldownMetaExecutors {
     // StackTraceCache which would then result in heap use after free like 
#23834
     std::vector<std::unique_ptr<PriorityThreadPool>> _executors;
     std::unordered_set<int64_t> _pending_tablets;
+    // Tablets with a write that failed since the last resubmit_failed(). 
Guarded by _latch.
+    std::unordered_set<int64_t> _failed_tablets;
     std::mutex _latch;
     size_t _executor_nums;
 };
diff --git a/be/test/cloud/cloud_tablet_test.cpp 
b/be/test/cloud/cloud_tablet_test.cpp
index a5869d2ca24..86da48eba12 100644
--- a/be/test/cloud/cloud_tablet_test.cpp
+++ b/be/test/cloud/cloud_tablet_test.cpp
@@ -37,7 +37,6 @@
 #include "storage/rowset/rowset.h"
 #include "storage/rowset/rowset_factory.h"
 #include "storage/rowset/rowset_meta.h"
-#include "storage/rowset/unique_rowset_id_generator.h"
 #include "storage/tablet/tablet_meta.h"
 #include "util/countdown_latch.h"
 #include "util/defer_op.h"
@@ -450,15 +449,7 @@ INSTANTIATE_TEST_SUITE_P(SequenceModes, 
CloudTabletDeleteBitmapCheckTest, testin
 
 class CloudTabletDeleteBitmapPrefillTest
         : public CloudTabletWarmUpStateTest,
-          public testing::WithParamInterface<std::tuple<bool, bool>> {
-public:
-    void SetUp() override {
-        CloudTabletWarmUpStateTest::SetUp();
-        // The aggregate cache is global, so rowset IDs must be unique across 
test instances.
-        _engine._rowset_id_generator =
-                std::make_unique<UniqueRowsetIdGenerator>(UniqueId::gen_uid());
-    }
-};
+          public testing::WithParamInterface<std::tuple<bool, bool>> {};
 
 TEST_P(CloudTabletDeleteBitmapPrefillTest, WaitForSchemaChangeDeleteBitmap) {
     const auto old_prefill_output = 
config::enable_prefill_output_dbm_agg_cache_after_compaction;
diff --git a/be/test/io/cache/block_file_cache_test.cpp 
b/be/test/io/cache/block_file_cache_test.cpp
index ede9bedec02..098f0d67be5 100644
--- a/be/test/io/cache/block_file_cache_test.cpp
+++ b/be/test/io/cache/block_file_cache_test.cpp
@@ -2675,6 +2675,65 @@ TEST_F(BlockFileCacheTest, fd_cache_evict) {
     }
 }
 
+// The capacity of the FD cache is a mutable config. A cache that holds more 
readers than a
+// lowered capacity has to shrink to it, not keep growing.
+TEST(FDCacheTest, evicts_down_to_a_lowered_capacity) {
+    const int64_t saved_capacity = 
config::file_cache_max_file_reader_cache_size;
+    Defer restore_capacity {
+            [&] { config::file_cache_max_file_reader_cache_size = 
saved_capacity; }};
+    config::file_cache_max_file_reader_cache_size = 4;
+
+    io::FDCache fd_cache;
+    const auto key = io::BlockFileCache::hash("fd_cache_lowered_capacity");
+    for (size_t offset = 0; offset < 4; ++offset) {
+        fd_cache.insert_file_reader(std::make_pair(key, offset), nullptr);
+    }
+    ASSERT_EQ(fd_cache.file_reader_cache_size(), 4);
+
+    config::file_cache_max_file_reader_cache_size = 2;
+    fd_cache.insert_file_reader(std::make_pair(key, 4), nullptr);
+    EXPECT_EQ(fd_cache.file_reader_cache_size(), 2);
+    // The readers inserted last stay.
+    EXPECT_TRUE(fd_cache.contains_file_reader(std::make_pair(key, 4)));
+    EXPECT_TRUE(fd_cache.contains_file_reader(std::make_pair(key, 3)));
+
+    fd_cache.insert_file_reader(std::make_pair(key, 5), nullptr);
+    EXPECT_EQ(fd_cache.file_reader_cache_size(), 2);
+}
+
+// The FD cache evicts while it holds at least `capacity` readers, comparing 
with the capacity cast
+// to size_t. A negative capacity is never reached: the cache would keep every 
reader and its open
+// file. The config rejects it, at startup and at runtime; 0 still disables 
the cache.
+TEST(FDCacheTest, rejects_a_negative_capacity) {
+    const int64_t saved_capacity = 
config::file_cache_max_file_reader_cache_size;
+    auto* saved_config_map = config::full_conf_map;
+    Defer restore_config {[&] {
+        config::file_cache_max_file_reader_cache_size = saved_capacity;
+        config::full_conf_map = saved_config_map;
+    }};
+    // Exercise the runtime update without changing the config dump used by 
other tests.
+    config::full_conf_map = nullptr;
+
+    const auto status = 
config::set_config("file_cache_max_file_reader_cache_size", "-1");
+    EXPECT_TRUE(status.is<ErrorCode::INVALID_ARGUMENT>()) << status;
+    EXPECT_EQ(config::file_cache_max_file_reader_cache_size, saved_capacity);
+    EXPECT_TRUE(config::set_config("file_cache_max_file_reader_cache_size", 
"0").ok());
+    EXPECT_EQ(config::file_cache_max_file_reader_cache_size, 0);
+
+    // The same check runs on the values BE reads from be.conf at startup.
+    const fs::path conf_file =
+            fs::temp_directory_path() / 
fmt::format("fd_cache_capacity_{}.conf", getpid());
+    Defer remove_conf {[&] { fs::remove(conf_file); }};
+    {
+        std::ofstream conf(conf_file);
+        conf << "file_cache_max_file_reader_cache_size = -1\n";
+        conf.close();
+        ASSERT_TRUE(conf);
+    }
+    EXPECT_FALSE(config::init(conf_file.c_str(), false, true, false));
+    EXPECT_EQ(config::file_cache_max_file_reader_cache_size, 0);
+}
+
 template <std::size_t N>
 int get_disk_info(const char* const (&argv)[N], int* percent) {
     assert((N > 0) && (argv[N - 1] == nullptr));
diff --git a/be/test/io/cache/block_file_cache_ttl_mgr_test.cpp 
b/be/test/io/cache/block_file_cache_ttl_mgr_test.cpp
index c398626d1e6..7c277ae4727 100644
--- a/be/test/io/cache/block_file_cache_ttl_mgr_test.cpp
+++ b/be/test/io/cache/block_file_cache_ttl_mgr_test.cpp
@@ -757,4 +757,19 @@ TEST_F(BlockFileCacheTtlMgrTest, 
TtlClearedAfterExpiryStopsTrackingTablet) {
     EXPECT_EQ(FileCacheType::NORMAL, block->cache_type());
 }
 
+// Destroying a BlockFileCache stops its TTL manager. With the default 180 s 
intervals, stop()
+// used to wait until every background thread had slept out its interval.
+TEST_F(BlockFileCacheTtlMgrTest, StopDoesNotWaitOutTheBackgroundIntervals) {
+    config::file_cache_background_ttl_info_update_interval_ms = 60000;
+    config::file_cache_background_ttl_gc_interval_ms = 60000;
+    config::file_cache_background_tablet_id_flush_interval_ms = 60000;
+    _ttl_mgr = std::make_unique<BlockFileCacheTtlMgr>(_cache.get(), 
_meta_store.get());
+    // Each thread finishes its first round right away and then waits for its 
interval.
+    std::this_thread::sleep_for(std::chrono::milliseconds(200));
+
+    auto start = std::chrono::steady_clock::now();
+    _ttl_mgr->stop();
+    EXPECT_LT(std::chrono::steady_clock::now() - start, 
std::chrono::seconds(5));
+}
+
 } // namespace doris::io
diff --git a/be/test/io/cache/fs_file_cache_storage_leak_cleaner_test.cpp 
b/be/test/io/cache/fs_file_cache_storage_leak_cleaner_test.cpp
index 0ab9953cb54..47e62e8da21 100644
--- a/be/test/io/cache/fs_file_cache_storage_leak_cleaner_test.cpp
+++ b/be/test/io/cache/fs_file_cache_storage_leak_cleaner_test.cpp
@@ -22,6 +22,7 @@
 #include <cstring>
 #include <filesystem>
 #include <fstream>
+#include <future>
 #include <stdexcept>
 #include <string>
 #include <thread>
@@ -37,6 +38,7 @@
 #include "io/cache/block_file_cache.h"
 #include "io/cache/block_file_cache_test_common.h"
 #include "io/cache/fs_file_cache_storage.h"
+#include "util/defer_op.h"
 
 namespace doris::io {
 
@@ -348,7 +350,6 @@ TEST_F(FSFileCacheLeakCleanerTest, 
snapshot_metadata_for_hash_offsets_handles_mi
     BlockFileCache mgr(dir.string(), settings);
     FSFileCacheStorage storage;
     setup_storage(storage, mgr, dir);
-    config::file_cache_leak_scan_interval_seconds = 1;
 
     auto missing_hash = BlockFileCache::hash("missing_hash_case");
     auto offsets = storage.snapshot_metadata_for_hash_offsets(&mgr, 
missing_hash);
@@ -364,6 +365,62 @@ TEST_F(FSFileCacheLeakCleanerTest, 
snapshot_metadata_for_hash_offsets_handles_mi
     EXPECT_EQ(7u, offsets[1]);
 }
 
+// The loop checks the stop flag under its mutex right before it waits, and 
stop_leak_cleaner() sets
+// the flag and notifies. Here the stop comes exactly between that check and 
the wait. The flag is
+// set under the same mutex, so the stop waits until the loop waits and the 
notification is not
+// lost; a lost one would leave the loop asleep for the whole scan interval 
(20s here), and the
+// stop waiting in join() with it.
+TEST_F(FSFileCacheLeakCleanerTest, stop_between_flag_check_and_wait) {
+    auto dir = prepare_test_dir();
+    FileCacheSettings settings = default_settings();
+    BlockFileCache mgr(dir.string(), settings);
+
+    FSFileCacheStorage storage;
+    setup_storage(storage, mgr, dir);
+
+    std::promise<void> checked;
+    std::promise<void> notified;
+    auto notified_future = notified.get_future();
+    std::atomic<bool> first_check {true};
+    std::atomic<bool> first_notify {true};
+    auto* sp = SyncPoint::get_instance();
+    sp->set_call_back("FSFileCacheStorage::leak_cleaner_loop::initial_delay",
+                      [](auto&& args) { *try_any_cast<int64_t*>(args[0]) = 0; 
});
+    sp->set_call_back("FSFileCacheStorage::leak_cleaner_loop::interval",
+                      [](auto&& args) { *try_any_cast<int64_t*>(args[0]) = 20; 
});
+    sp->set_call_back("FSFileCacheStorage::leak_cleaner_loop::stop_checked", 
[&](auto&& args) {
+        if (*try_any_cast<bool*>(args[0]) || !first_check.exchange(false)) {
+            return;
+        }
+        checked.set_value();
+        // The loop holds its mutex and has seen no stop. A stop that sets the 
flag without the
+        // mutex notifies now, before the loop waits; one that takes the mutex 
blocks until the
+        // loop waits, and this times out.
+        notified_future.wait_for(std::chrono::milliseconds(500));
+    });
+    sp->set_call_back("FSFileCacheStorage::stop_leak_cleaner::notified", 
[&](auto&&) {
+        if (first_notify.exchange(false)) {
+            notified.set_value();
+        }
+    });
+    sp->enable_processing();
+    Defer defer {[sp] {
+        sp->disable_processing();
+        
sp->clear_call_back("FSFileCacheStorage::leak_cleaner_loop::initial_delay");
+        sp->clear_call_back("FSFileCacheStorage::leak_cleaner_loop::interval");
+        
sp->clear_call_back("FSFileCacheStorage::leak_cleaner_loop::stop_checked");
+        sp->clear_call_back("FSFileCacheStorage::stop_leak_cleaner::notified");
+    }};
+
+    storage.start_leak_cleaner(&mgr);
+    ASSERT_TRUE(storage._cache_leak_cleaner_thread.joinable());
+    checked.get_future().wait();
+    const auto start = std::chrono::steady_clock::now();
+    storage.stop_leak_cleaner();
+    EXPECT_LT(std::chrono::steady_clock::now() - start, 
std::chrono::seconds(10));
+    EXPECT_FALSE(storage._cache_leak_cleaner_thread.joinable());
+}
+
 TEST_F(FSFileCacheLeakCleanerTest, leak_cleaner_loop_catches_std_exception) {
     ScopedLeakCleanerConfig guard;
     config::file_cache_leak_scan_interval_seconds = 1;
@@ -597,7 +654,6 @@ TEST_F(FSFileCacheLeakCleanerTest, 
cleanup_flush_candidates_remove_directories)
 
 TEST_F(FSFileCacheLeakCleanerTest, 
estimate_file_count_handles_statvfs_failure) {
     ScopedInodeTestHooks hooks_guard;
-    config::file_cache_leak_scan_interval_seconds = 1;
     hooks_guard.hooks.statvfs_override = [](const std::string&, struct 
statvfs* vfs) {
         *vfs = {};
         errno = EIO;
@@ -611,7 +667,6 @@ TEST_F(FSFileCacheLeakCleanerTest, 
estimate_file_count_handles_statvfs_failure)
 
 TEST_F(FSFileCacheLeakCleanerTest, 
estimate_file_count_handles_zero_total_inodes) {
     ScopedInodeTestHooks hooks_guard;
-    config::file_cache_leak_scan_interval_seconds = 1;
     hooks_guard.hooks.statvfs_override = [](const std::string&, struct 
statvfs* vfs) {
         *vfs = {};
         vfs->f_files = 0;
@@ -630,7 +685,6 @@ TEST_F(FSFileCacheLeakCleanerTest, 
estimate_file_count_handles_zero_total_inodes
 
 TEST_F(FSFileCacheLeakCleanerTest, estimate_file_count_handles_lstat_failure) {
     ScopedInodeTestHooks hooks_guard;
-    config::file_cache_leak_scan_interval_seconds = 1;
     hooks_guard.hooks.statvfs_override = [](const std::string&, struct 
statvfs* vfs) {
         *vfs = {};
         vfs->f_files = 100;
@@ -649,7 +703,6 @@ TEST_F(FSFileCacheLeakCleanerTest, 
estimate_file_count_handles_lstat_failure) {
 
 TEST_F(FSFileCacheLeakCleanerTest, estimate_file_count_handles_underflow) {
     ScopedInodeTestHooks hooks_guard;
-    config::file_cache_leak_scan_interval_seconds = 1;
     hooks_guard.hooks.statvfs_override = [](const std::string&, struct 
statvfs* vfs) {
         *vfs = {};
         vfs->f_files = 200;
@@ -671,7 +724,6 @@ TEST_F(FSFileCacheLeakCleanerTest, 
estimate_file_count_handles_underflow) {
 
 TEST_F(FSFileCacheLeakCleanerTest, estimate_file_count_combines_counts) {
     ScopedInodeTestHooks hooks_guard;
-    config::file_cache_leak_scan_interval_seconds = 1;
     hooks_guard.hooks.statvfs_override = [](const std::string&, struct 
statvfs* vfs) {
         *vfs = {};
         vfs->f_files = 500;
diff --git a/be/test/storage/index/index_builder_test.cpp 
b/be/test/storage/index/index_builder_test.cpp
index c57b9917de1..4259c3676e0 100644
--- a/be/test/storage/index/index_builder_test.cpp
+++ b/be/test/storage/index/index_builder_test.cpp
@@ -1044,24 +1044,24 @@ TEST_F(IndexBuilderTest, DropInvertedIndexTest) {
     bool dir_exists = false;
     EXPECT_TRUE(io::global_local_filesystem()->list(tablet_path, true, &files, 
&dir_exists).ok());
     EXPECT_TRUE(dir_exists);
+    ASSERT_EQ(builder._output_rowsets.size(), 1);
+    const std::string new_rowset_id = 
builder._output_rowsets[0]->rowset_id().to_string();
     int new_idx_file_count = 0;
     int new_dat_file_count = 0;
     int old_idx_file_count = 0;
     int old_dat_file_count = 0;
     for (const auto& file : files) {
-        std::string filename = file.file_name;
-        if (filename.find("15676_0.idx") != std::string::npos) {
+        const std::string& filename = file.file_name;
+        if (filename == "15676_0.idx") {
             old_idx_file_count++;
         }
-        if (filename.find("15676_0.dat") != std::string::npos) {
+        if (filename == "15676_0.dat") {
             old_dat_file_count++;
         }
-        if 
(filename.find("020000000000000100000000000000000000000000000000_0.idx") !=
-            std::string::npos) {
+        if (filename == new_rowset_id + "_0.idx") {
             new_idx_file_count++;
         }
-        if 
(filename.find("020000000000000100000000000000000000000000000000_0.dat") !=
-            std::string::npos) {
+        if (filename == new_rowset_id + "_0.dat") {
             new_dat_file_count++;
         }
     }
@@ -1209,24 +1209,24 @@ TEST_F(IndexBuilderTest, DropAnnIndexTest) {
     bool dir_exists = false;
     EXPECT_TRUE(io::global_local_filesystem()->list(tablet_path, true, &files, 
&dir_exists).ok());
     EXPECT_TRUE(dir_exists);
+    ASSERT_EQ(builder._output_rowsets.size(), 1);
+    const std::string new_rowset_id = 
builder._output_rowsets[0]->rowset_id().to_string();
     int new_idx_file_count = 0;
     int new_dat_file_count = 0;
     int old_idx_file_count = 0;
     int old_dat_file_count = 0;
     for (const auto& file : files) {
-        std::string filename = file.file_name;
-        if (filename.find("15676_0.idx") != std::string::npos) {
+        const std::string& filename = file.file_name;
+        if (filename == "15676_0.idx") {
             old_idx_file_count++;
         }
-        if (filename.find("15676_0.dat") != std::string::npos) {
+        if (filename == "15676_0.dat") {
             old_dat_file_count++;
         }
-        if 
(filename.find("020000000000000100000000000000000000000000000000_0.idx") !=
-            std::string::npos) {
+        if (filename == new_rowset_id + "_0.idx") {
             new_idx_file_count++;
         }
-        if 
(filename.find("020000000000000100000000000000000000000000000000_0.dat") !=
-            std::string::npos) {
+        if (filename == new_rowset_id + "_0.dat") {
             new_dat_file_count++;
         }
     }
@@ -3076,24 +3076,24 @@ TEST_F(IndexBuilderTest, DropIndexV1FormatTest) {
     EXPECT_TRUE(dir_exists);
 
     // Verify no index files in the new directory
+    ASSERT_EQ(builder._output_rowsets.size(), 1);
+    const std::string new_rowset_id = 
builder._output_rowsets[0]->rowset_id().to_string();
     int new_idx_file_count = 0;
     int new_dat_file_count = 0;
     int old_idx_file_count = 0;
     int old_dat_file_count = 0;
     for (const auto& file : files) {
-        std::string filename = file.file_name;
-        if (filename.find("15683_0_1.idx") != std::string::npos) {
+        const std::string& filename = file.file_name;
+        if (filename == "15683_0_1.idx") {
             old_idx_file_count++;
         }
-        if (filename.find("15683_0.dat") != std::string::npos) {
+        if (filename == "15683_0.dat") {
             old_dat_file_count++;
         }
-        if 
(filename.find("020000000000000100000000000000000000000000000000_0_1.idx") !=
-            std::string::npos) {
+        if (filename == new_rowset_id + "_0_1.idx") {
             new_idx_file_count++;
         }
-        if 
(filename.find("020000000000000100000000000000000000000000000000_0.dat") !=
-            std::string::npos) {
+        if (filename == new_rowset_id + "_0.dat") {
             new_dat_file_count++;
         }
     }
@@ -3215,8 +3215,9 @@ TEST_F(IndexBuilderTest, ResourceCleanupTest) {
     EXPECT_TRUE(io::global_local_filesystem()->exists(tablet_path, 
&exists).ok());
     EXPECT_TRUE(exists);
 
-    auto rowset_id = 
extract_rowset_id("020000000000000100000000000000000000000000000000_0.dat");
-    EXPECT_TRUE(_engine_ref->check_rowset_id_in_unused_rowsets(rowset_id))
+    ASSERT_EQ(builder._output_rowsets.size(), 1);
+    EXPECT_TRUE(
+            
_engine_ref->check_rowset_id_in_unused_rowsets(builder._output_rowsets[0]->rowset_id()))
             << "Rowset id should be in unused rowsets";
 }
 
@@ -3344,10 +3345,9 @@ TEST_F(IndexBuilderTest, ArrayTypeIndexTest) {
     EXPECT_TRUE(status.ok()) << status.to_string();
 
     // 10. Verify that the index has been created
+    ASSERT_EQ(builder._output_rowsets.size(), 1);
     std::string segment_path = local_segment_path(
-            tablet->tablet_path(),
-            
extract_rowset_id("020000000000000100000000000000000000000000000000_0.dat").to_string(),
-            0);
+            tablet->tablet_path(), 
builder._output_rowsets[0]->rowset_id().to_string(), 0);
 
     if (tablet_schema->get_inverted_index_storage_format() == 
InvertedIndexStorageFormatPB::V1) {
         // V1 format
@@ -3802,10 +3802,9 @@ TEST_F(IndexBuilderTest, UniqueKeysTableIndexTest) {
     EXPECT_TRUE(status.ok()) << status.to_string();
 
     // 9. Verify that the index was created successfully
+    ASSERT_EQ(builder._output_rowsets.size(), 1);
     std::string segment_path = local_segment_path(
-            _tablet->tablet_path(),
-            
extract_rowset_id("020000000000000100000000000000000000000000000000_0.dat").to_string(),
-            0);
+            _tablet->tablet_path(), 
builder._output_rowsets[0]->rowset_id().to_string(), 0);
 
     if (_tablet_schema->get_inverted_index_storage_format() == 
InvertedIndexStorageFormatPB::V1) {
         auto index_path = InvertedIndexDescriptor::get_index_file_path_v1(
diff --git a/be/test/storage/rowset/unique_rowset_id_generator_test.cpp 
b/be/test/storage/rowset/unique_rowset_id_generator_test.cpp
index 2d35b1fb5c6..1dc7fc7ccda 100644
--- a/be/test/storage/rowset/unique_rowset_id_generator_test.cpp
+++ b/be/test/storage/rowset/unique_rowset_id_generator_test.cpp
@@ -26,6 +26,8 @@
 #include "common/status.h"
 #include "gtest/gtest_pred_impl.h"
 #include "runtime/runtime_profile.h"
+#include "storage/options.h"
+#include "storage/storage_engine.h"
 #include "testutil/test_util.h"
 #include "util/threadpool.h"
 
@@ -93,6 +95,21 @@ TEST_F(UniqueRowsetIdGeneratorTest, GenerateIdTest) {
     EXPECT_EQ(rowset_mid_str, backend_mid_str);
 }
 
+// A process can build many engines (a unit test builds one per case), and the 
segment cache and
+// the page cache outlive them, keyed on rowset ids and on the file names made 
from them. If two
+// engines from default options shared a uid, both would name their first 
rowset
+// 020000000000000100000000000000000000000000000000, and the second would be 
handed the segment
+// the first one cached under that id.
+TEST_F(UniqueRowsetIdGeneratorTest, 
EnginesFromDefaultOptionsGenerateDistinctIds) {
+    RowsetId first_id;
+    {
+        StorageEngine engine {EngineOptions {}};
+        first_id = engine.next_rowset_id();
+    }
+    StorageEngine engine {EngineOptions {}};
+    EXPECT_NE(first_id, engine.next_rowset_id());
+}
+
 TEST_F(UniqueRowsetIdGeneratorTest, GenerateIdBenchmark) {
     const int kNumThreads = 8;
     const int kIdPerThread = LOOP_LESS_OR_MORE(1000, 1000000);
diff --git a/be/test/storage/tablet/tablet_cooldown_test.cpp 
b/be/test/storage/tablet/tablet_cooldown_test.cpp
index b0144bc7de6..c23727938a4 100644
--- a/be/test/storage/tablet/tablet_cooldown_test.cpp
+++ b/be/test/storage/tablet/tablet_cooldown_test.cpp
@@ -26,10 +26,15 @@
 #include <stdint.h>
 #include <unistd.h>
 
+#include <atomic>
+#include <chrono>
+#include <filesystem>
+#include <future>
 #include <iostream>
 #include <map>
 #include <memory>
 #include <string>
+#include <thread>
 #include <utility>
 #include <vector>
 
@@ -41,6 +46,7 @@
 #include "core/column/column.h"
 #include "core/data_type/define_primitive_type.h"
 #include "core/value/vdatetime_value.h"
+#include "cpp/sync_point.h"
 #include "exprs/function/cast/cast_to_date_or_datetime_impl.hpp"
 #include "gtest/gtest_pred_impl.h"
 #include "io/fs/file_reader.h"
@@ -64,6 +70,8 @@
 #include "storage/tablet_info.h"
 #include "storage/task/engine_publish_version_task.h"
 #include "storage/txn/txn_manager.h"
+#include "util/defer_op.h"
+#include "util/uid_util.h"
 
 namespace doris {
 class OlapMeta;
@@ -201,6 +209,10 @@ private:
 class TabletCooldownTest : public testing::Test {
 public:
     static void SetUpTestSuite() {
+        // The fixture reads cooled-down rowsets from its mock remote 
filesystem and has no cache.
+        _saved_enable_file_cache = config::enable_file_cache;
+        config::enable_file_cache = false;
+
         s_fs.reset(new RemoteFileSystemMock("", std::to_string(kResourceId),
                                             
io::FileSystemType::OBJECT_STORAGE));
         StorageResource resource {s_fs};
@@ -239,12 +251,23 @@ public:
 
     static void TearDownTestSuite() {
         ExecEnv* exec_env = doris::ExecEnv::GetInstance();
+        // cooldown() queues cooldown meta writes on these executors, and each 
write holds its
+        // tablet and needs the storage policy. Destroy the executors first, 
which joins their
+        // workers and frees the queued writes while the engine and the policy 
still exist.
+        // Left in ExecEnv, a write that runs after the policy is deleted 
below fails with
+        // NOT_FOUND and resubmits itself through every later suite of the 
process, and its
+        // tablet is destroyed at process exit, after DorisMetrics, which 
aborts the process.
+        exec_env->_write_cooldown_meta_executors.reset();
         engine_ref = nullptr;
         exec_env->set_storage_engine(nullptr);
         exec_env->set_memtable_memory_limiter(nullptr);
         delete_storage_policy(kStoragePolicyId);
         delete_storage_resource(kResourceId);
+        config::enable_file_cache = _saved_enable_file_cache;
     }
+
+private:
+    inline static bool _saved_enable_file_cache = false;
 };
 
 static void create_tablet_request_with_sequence_col(int64_t tablet_id, int32_t 
schema_hash,
@@ -491,4 +514,128 @@ TEST_F(TabletCooldownTest, cooldown_data) {
     ASSERT_EQ(Status::OK(), st);
 }
 
+// Makes `tablet` the cooldown replica with a cooldown meta id, as cooldown() 
would, so that
+// WriteCooldownMetaExecutors::submit() accepts it, and gives it a storage 
policy id.
+static void prepare_cooldown_meta_write(const TabletSharedPtr& tablet, int64_t 
replica_id,
+                                        int64_t storage_policy_id) {
+    ASSERT_TRUE(tablet->update_cooldown_conf(1, replica_id));
+    tablet->tablet_meta()->set_cooldown_meta_id(UniqueId::gen_uid());
+    tablet->set_storage_policy_id(storage_policy_id);
+}
+
+// Counts the cooldown meta writes of one tablet, through a sync point in the 
write task.
+class CooldownMetaWriteCounter {
+public:
+    explicit CooldownMetaWriteCounter(const Tablet* tablet) {
+        auto* sp = SyncPoint::get_instance();
+        sp->set_call_back(kPoint, [this, tablet](auto&& args) {
+            if (try_any_cast<Tablet*>(args[0]) == tablet) {
+                _writes.fetch_add(1);
+            }
+        });
+        sp->enable_processing();
+    }
+    ~CooldownMetaWriteCounter() {
+        auto* sp = SyncPoint::get_instance();
+        sp->disable_processing();
+        sp->clear_call_back(kPoint);
+    }
+
+    int writes() const { return _writes.load(); }
+
+    // Waits until the tablet has been written `n` times, then settles.
+    void wait_for_writes(int n) const {
+        for (int i = 0; i < 1000 && writes() < n; ++i) {
+            std::this_thread::sleep_for(std::chrono::milliseconds(5));
+        }
+        settle();
+    }
+
+    // Long enough for a write resubmitted right away to show up as one more.
+    static void settle() { 
std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
+
+private:
+    static constexpr const char* kPoint = 
"WriteCooldownMetaExecutors::write_cooldown_meta";
+    std::atomic<int> _writes {0};
+};
+
+// A write that fails with anything but ABORTED (here: its storage policy does 
not exist) must not
+// resubmit itself right away, or it keeps the only thread of its executor 
retrying for as long as
+// it fails. It waits for resubmit_failed(), which the cooldown producer calls 
once a round, and a
+// write that succeeds is not resubmitted.
+TEST_F(TabletCooldownTest, failed_write_is_retried_once_a_round) {
+    constexpr int64_t policy_id = kStoragePolicyId + 2;
+    TabletSharedPtr tablet;
+    createTablet(&tablet, kReplicaId + 4, kSchemaHash + 4, kTabletId + 4, 
kTxnId + 5,
+                 kPartitionId + 4, false);
+    prepare_cooldown_meta_write(tablet, kReplicaId + 4, policy_id);
+    CooldownMetaWriteCounter counter(tablet.get());
+
+    WriteCooldownMetaExecutors executors(1);
+    executors.submit(tablet);
+    counter.wait_for_writes(1);
+    EXPECT_EQ(counter.writes(), 1);
+
+    executors.resubmit_failed(*engine_ref->tablet_manager());
+    counter.wait_for_writes(2);
+    EXPECT_EQ(counter.writes(), 2);
+
+    // The policy exists now: the next round writes the meta (the tablet has 
no cooled down
+    // rowset, so there is nothing to upload) and the write is not retried 
again.
+    auto storage_policy = std::make_shared<StoragePolicy>();
+    storage_policy->name = 
"TabletCooldownTest.failed_write_is_retried_once_a_round";
+    storage_policy->version = 1;
+    storage_policy->resource_id = kResourceId;
+    storage_policy->cooldown_datetime = UnixSeconds() - 1;
+    put_storage_policy(policy_id, storage_policy);
+    Defer delete_policy {[&] { delete_storage_policy(policy_id); }};
+    executors.resubmit_failed(*engine_ref->tablet_manager());
+    counter.wait_for_writes(3);
+    EXPECT_EQ(counter.writes(), 3);
+    executors.resubmit_failed(*engine_ref->tablet_manager());
+    CooldownMetaWriteCounter::settle();
+    EXPECT_EQ(counter.writes(), 3);
+}
+
+// A write task locks the executors' _latch: when it starts, and again when 
its write fails, to
+// record the tablet for resubmit_failed(). Destroying the executors while 
such a write runs must
+// stop and join the worker before those members are freed; otherwise the 
worker locks a destroyed
+// mutex (libc++: "mutex lock failed: Invalid argument") or writes into a 
freed set.
+TEST_F(TabletCooldownTest, destroy_executors_while_a_failed_write_runs) {
+    TabletSharedPtr tablet;
+    createTablet(&tablet, kReplicaId + 3, kSchemaHash + 3, kTabletId + 3, 
kTxnId + 4,
+                 kPartitionId + 3, false);
+    // No storage policy has this id: the write can neither succeed nor be 
aborted.
+    prepare_cooldown_meta_write(tablet, kReplicaId + 3, kStoragePolicyId + 1);
+    Status st = tablet->write_cooldown_meta();
+    ASSERT_TRUE(st.is<ErrorCode::NOT_FOUND>()) << st;
+
+    std::promise<void> write_failed;
+    std::atomic<bool> destroying {false};
+    auto* sp = SyncPoint::get_instance();
+    Defer clear {[sp] {
+        sp->disable_processing();
+        sp->clear_call_back("WriteCooldownMetaExecutors::write_cooldown_meta");
+    }};
+    sp->set_call_back("WriteCooldownMetaExecutors::write_cooldown_meta", 
[&](auto&& args) {
+        if (try_any_cast<Tablet*>(args[0]) != tablet.get()) {
+            return;
+        }
+        // Hold the failed write until the executors are being destroyed, then 
let the destructor
+        // reach the join before the task records the failure.
+        write_failed.set_value();
+        while (!destroying.load()) {
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
+        }
+        std::this_thread::sleep_for(std::chrono::milliseconds(50));
+    });
+    sp->enable_processing();
+
+    auto executors = std::make_unique<WriteCooldownMetaExecutors>(1);
+    executors->submit(tablet);
+    write_failed.get_future().wait();
+    destroying = true;
+    executors.reset();
+}
+
 } // namespace doris


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to