hello-stephen commented on code in PR #69619:
URL: https://github.com/apache/doris/pull/69619#discussion_r4787246391


##########
be/src/io/cache/block_file_cache.cpp:
##########
@@ -2095,17 +2104,21 @@ void BlockFileCache::remove(FileBlockSPtr file_block, 
T& cache_lock, U& block_lo
         key.meta.type = type;
         key.meta.expiration_time = expiration_time;
         key.meta.tablet_id = tablet_id;
-        if (sync) {
-            int64_t duration_ns = 0;
-            Status st;
-            {
-                SCOPED_RAW_TIMER(&duration_ns);
-                st = _storage->remove(key);
-            }
-            *_storage_sync_remove_latency_us << (duration_ns / 1000);
-            if (!st.ok()) {
-                LOG_WARNING("").error(st);
-            }
+        // The recorder travels with the pending entry, so the latency lands 
in this path's metric
+        // even when GC or a replacement block's downloader is the one that 
runs the removal.
+        _pending_storage_removes.mark(key, sync ? 
_storage_sync_remove_latency_us.get()
+                                                : 
_storage_async_remove_latency_us.get());
+        DeferredStorageRemoveScope* deferred_scope = 
DeferredStorageRemoveScope::current();
+        // Every cache-lock holder that can reach here took the lock with 
SCOPED_CACHE_LOCK, which
+        // opens the scope. A missing or foreign scope (another cache's lock 
is the innermost)
+        // falls back to removing inline, as before.
+        const bool can_defer = deferred_scope != nullptr && 
deferred_scope->owned_by(this);
+        if (sync && can_defer) {
+            // Runs once the cache lock is released, before the evicting 
caller continues, so
+            // the space is still freed on the caller's own thread.
+            deferred_scope->add(key);

Review Comment:
   [P2] Preserve the eviction dependency for a competing downloader of the 
admitted block
   
   The evicting caller waits for its own storage removals, but the newly 
admitted EMPTY block is already visible when this scope releases the cache 
mutex. If A reserves Y by evicting X on a disk with no free inodes or blocks, B 
can look up Y while A is still unlinking X, become Y’s downloader, and append. 
B’s lookup hits the existing cell and does not reserve again, even in 
disk-resource-limit mode; `appendv`/`append_iobuf` only drain removals at Y, 
not the victim X. Its cache write can therefore fail with ENOSPC before the 
synchronous eviction makes room. Previously B could not obtain Y until X’s 
unlink under the cache mutex finished. Please associate the reservation’s 
reclaim-completion dependency with the admitted block and wait outside the 
cache lock before writing. Test a second holder of Y while X’s unlink is 
stalled. This is distinct from waiting for competing owners of X in the 
original evictor.



##########
be/src/io/cache/block_file_cache.cpp:
##########
@@ -1433,6 +1433,15 @@ FileBlockCell* BlockFileCache::add_cell(const 
UInt128Wrapper& hash, const CacheC
         return nullptr;
     }
 
+    // A block loaded back from storage (DOWNLOADED) at a position whose 
removal is still pending
+    // is the evicted block itself: its file and meta are deleted right after 
the evicting thread
+    // releases the cache lock. E.g. at startup, a lookup lazily loads hash H 
from the meta store
+    // between the eviction of (H, 0) and its deferred removal; without this 
check (H, 0) would be
+    // cached with no file behind it.
+    if (state == FileBlock::State::DOWNLOADED && 
_pending_storage_removes.contains(hash, offset)) {

Review Comment:
   [P2] Keep the eviction guard valid across the startup metadata read
   
   This check can miss the removal it is intended to exclude. Before async open 
finishes, `get_impl` calls `load_file_blocks_directly_unlocked` under the cache 
mutex. The loader can acquire its RocksDB iterator while an evicted block is 
still pending; the deferred evictor can then unlink the file and erase the 
pending entry in `finish()` while the loader still holds that mutex. When the 
loader reaches `add_cell`, the iterator still describes the old block but 
`contains()` is false, so it publishes a DOWNLOADED block with no file. The old 
async metadata-delete lag already existed, but releasing the cache lock before 
synchronous unlink introduces this additional overlap with the lock-held direct 
load. Please coordinate the guard with the lifetime of the metadata view 
(including the queued metadata delete), or revalidate the loaded generation 
safely. The current synthetic pending-marker test never lets the removal finish 
before insertion.



##########
be/test/io/cache/block_file_cache_evict_io_test.cpp:
##########
@@ -0,0 +1,666 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Storage removal of evicted file cache blocks: it must run outside the cache 
lock, must never
+// delete a block re-created at the same position, and must treat missing 
files as removed.
+
+#include <atomic>
+#include <future>
+
+#include "io/cache/block_file_cache_test_common.h"
+#include "util/defer_op.h"
+
+namespace doris::io {
+
+namespace {
+
+constexpr size_t kBlockSize = 10;
+
+std::string evict_io_cache_path(const std::string& name) {
+    return (caches_dir / ("evict_io_" + name) / "").string();
+}
+
+FileCacheSettings normal_only_settings(size_t capacity, size_t block_size) {
+    FileCacheSettings settings;
+    settings.index_queue_elements = 0;
+    settings.index_queue_size = 0;
+    settings.disposable_queue_size = 0;
+    settings.disposable_queue_elements = 0;
+    settings.ttl_queue_size = 0;
+    settings.ttl_queue_elements = 0;
+    settings.query_queue_size = capacity;
+    settings.query_queue_elements = capacity / block_size + 1;
+    settings.max_file_block_size = block_size;
+    settings.max_query_cache_size = capacity;
+    settings.capacity = capacity;
+    return settings;
+}
+
+std::string block_path(const std::string& base, const UInt128Wrapper& hash, 
size_t offset) {
+    auto key_str = hash.to_string();
+    return (fs::path(base) / key_str.substr(0, 3) / (key_str + "_0") / 
std::to_string(offset))
+            .string();
+}
+
+// Inserts [offset, offset + size) of hash, downloads it with `fill` and 
releases the holder.
+void insert_block(BlockFileCache& cache, const UInt128Wrapper& hash, size_t 
offset, size_t size,
+                  char fill = '0') {
+    CacheContext context;
+    ReadStatistics rstats;
+    context.stats = &rstats;
+    context.cache_type = FileCacheType::NORMAL;
+    auto holder = cache.get_or_set(hash, offset, size, context);
+    for (auto& block : holder.file_blocks) {
+        if (block->state() != FileBlock::State::EMPTY ||
+            block->get_or_set_downloader() != FileBlock::get_caller_id()) {
+            continue;
+        }
+        std::string data(block->range().size(), fill);
+        ASSERT_TRUE(block->append(Slice(data.data(), data.size())).ok());
+        ASSERT_TRUE(block->finalize().ok());
+    }
+}
+
+// Whether `mutex` stays held for a whole 200 ms window, as it is when the 
thread calling this
+// is parked in a sync point while holding it. The cache's monitor and GC 
threads take the same
+// mutex too, but only briefly, so one failed try_lock would not prove the 
caller holds it.
+// try_lock from the owning thread is undefined, so the probe runs on its own 
thread.
+bool is_held_throughout(std::mutex& mutex) {
+    bool acquired = false;
+    std::thread probe([&] {
+        const auto deadline = std::chrono::steady_clock::now() + 
std::chrono::milliseconds(200);
+        while (std::chrono::steady_clock::now() < deadline) {
+            if (mutex.try_lock()) {
+                mutex.unlock();
+                acquired = true;
+                return;
+            }
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
+        }
+    });
+    probe.join();
+    return !acquired;
+}
+
+// Evicts one block and checks that its storage removal runs, with the cache 
lock not held.
+void run_eviction_lock_probe() {
+    auto base = evict_io_cache_path("lock_probe");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(3 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key1 = BlockFileCache::hash("evict_io_lock_key1");
+    auto key2 = BlockFileCache::hash("evict_io_lock_key2");
+    insert_block(cache, key1, 0, 3 * kBlockSize);
+    ASSERT_TRUE(fs::exists(block_path(base, key1, 0)));
+
+    std::atomic<int> removes {0};
+    std::atomic<int> removes_under_lock {0};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != key1) {
+                    return;
+                }
+                ++removes;
+                if (is_held_throughout(cache._mutex)) {
+                    ++removes_under_lock;
+                }
+            },
+            &guard);
+
+    // The cache is full: reserving the new block evicts key1's LRU head 
synchronously.
+    insert_block(cache, key2, 0, kBlockSize);
+
+    EXPECT_EQ(removes.load(), 1);
+    EXPECT_EQ(removes_under_lock.load(), 0);
+    // The removal still completes on the evicting thread: it is done when 
get_or_set returns.
+    EXPECT_FALSE(fs::exists(block_path(base, key1, 0)));
+    EXPECT_TRUE(fs::exists(block_path(base, key1, kBlockSize)));
+    EXPECT_EQ(cache._pending_storage_removes.size(), 0U);
+}
+
+} // namespace
+
+TEST_F(BlockFileCacheTest, 
evict_io_storage_remove_runs_after_cache_lock_released) {
+    run_eviction_lock_probe();
+}
+
+// Negative control for is_held_throughout(), which the lock checks in these 
tests rely on.
+TEST(BlockFileCacheEvictIoProbeTest, lock_probe_detects_held_lock) {
+    std::mutex mutex;
+    EXPECT_FALSE(is_held_throughout(mutex));
+    std::lock_guard lock(mutex);
+    EXPECT_TRUE(is_held_throughout(mutex));
+}
+
+TEST_F(BlockFileCacheTest, evict_io_remove_if_cached_removes_after_unlock) {
+    auto base = evict_io_cache_path("remove_if_cached");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+    auto key = BlockFileCache::hash("evict_io_remove_if_cached");
+    insert_block(cache, key, 0, 3 * kBlockSize);
+
+    std::atomic<int> removes_under_lock {0};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&&) {
+                if (is_held_throughout(cache._mutex)) {
+                    ++removes_under_lock;
+                }
+            },
+            &guard);
+
+    cache.remove_if_cached(key);
+    EXPECT_EQ(removes_under_lock.load(), 0);
+    for (size_t offset = 0; offset < 3 * kBlockSize; offset += kBlockSize) {
+        EXPECT_FALSE(fs::exists(block_path(base, key, offset))) << offset;
+    }
+    auto key_str = key.to_string();
+    EXPECT_FALSE(fs::exists(fs::path(base) / key_str.substr(0, 3) / (key_str + 
"_0")));
+}
+
+// While an evicted block's storage removal is stalled, unrelated cache 
lookups do not wait for
+// it: the removal runs after the cache lock is released.
+TEST_F(BlockFileCacheTest, evict_io_lookup_proceeds_while_remove_stalls) {
+    auto base = evict_io_cache_path("stalled_remove");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(2 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto victim = BlockFileCache::hash("evict_io_stall_victim");
+    auto other = BlockFileCache::hash("evict_io_stall_other");
+    auto newcomer = BlockFileCache::hash("evict_io_stall_newcomer");
+    insert_block(cache, victim, 0, kBlockSize);
+    insert_block(cache, other, 0, kBlockSize);
+
+    std::promise<void> remove_entered;
+    std::promise<void> release_remove;
+    auto release_future = release_remove.get_future().share();
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != victim) {
+                    return;
+                }
+                remove_entered.set_value();
+                release_future.wait();
+            },
+            &guard);
+
+    // Declared before the Defer that releases the evictor, so on a failure 
path the evictor is
+    // released before this future's destructor waits for the lookup.
+    std::future<bool> lookup;
+    // Inserting into the full cache evicts the victim; its removal then 
stalls on this thread.
+    std::thread evictor([&] { insert_block(cache, newcomer, 0, kBlockSize); });
+    Defer join_evictor {[&] {
+        release_remove.set_value();
+        evictor.join();
+    }};
+    ASSERT_EQ(remove_entered.get_future().wait_for(std::chrono::seconds(10)),
+              std::future_status::ready);
+
+    lookup = std::async(std::launch::async, [&] {
+        CacheContext context;
+        ReadStatistics rstats;
+        context.stats = &rstats;
+        context.cache_type = FileCacheType::NORMAL;
+        auto holder = cache.get_or_set(other, 0, kBlockSize, context);
+        return holder.file_blocks.size() == 1 &&
+               holder.file_blocks.front()->state() == 
FileBlock::State::DOWNLOADED;
+    });
+    ASSERT_EQ(lookup.wait_for(std::chrono::seconds(10)), 
std::future_status::ready);
+    EXPECT_TRUE(lookup.get());
+    EXPECT_FALSE(is_held_throughout(cache._mutex));
+}
+
+// A block evicted while its removal is still pending is not brought back by 
loading the hash's
+// blocks from storage (lazy load at startup, async load, LRU restore), which 
would leave a cached
+// block whose file the pending removal then deletes.
+TEST_F(BlockFileCacheTest, evict_io_load_skips_block_pending_removal) {
+    auto base = evict_io_cache_path("load_pending");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_io_load_pending");
+    FileCacheKey pending;
+    pending.hash = key;
+    pending.offset = 0;
+    cache._pending_storage_removes.mark(pending, 
cache._storage_sync_remove_latency_us.get());
+
+    CacheContext context;
+    context.cache_type = FileCacheType::NORMAL;
+    std::lock_guard cache_lock(cache._mutex);
+    EXPECT_EQ(cache.add_cell(key, context, 0, kBlockSize, 
FileBlock::State::DOWNLOADED, cache_lock),
+              nullptr);
+    EXPECT_FALSE(cache._files.contains(key));
+    // Another offset of the same hash, and a new block at the pending 
position, are added: the
+    // new block's downloader drains the pending removal before it writes.
+    EXPECT_NE(cache.add_cell(key, context, kBlockSize, kBlockSize, 
FileBlock::State::DOWNLOADED,
+                             cache_lock),
+              nullptr);
+    EXPECT_NE(cache.add_cell(key, context, 0, kBlockSize, 
FileBlock::State::EMPTY, cache_lock),
+              nullptr);
+}
+
+// A synchronous removal whose position another thread (a replacement block's 
downloader, or GC)
+// is already removing waits for that owner, so the file is gone when it 
returns. Driven through
+// remove_if_cached, whose lock scope runs the removal after the cache lock is 
released.
+TEST_F(BlockFileCacheTest, evict_io_sync_remove_waits_for_competing_owner) {
+    auto base = evict_io_cache_path("competing_owner");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_io_competing_owner");
+    insert_block(cache, key, 0, kBlockSize);
+    auto path = block_path(base, key, 0);
+    ASSERT_TRUE(fs::exists(path));
+
+    // Another thread is mid-removal at (key, 0) and has not unlinked the file 
yet.
+    FileCacheKey other;
+    other.hash = key;
+    other.offset = 0;
+    cache._pending_storage_removes.mark(other, 
cache._storage_async_remove_latency_us.get());
+    PendingStorageRemoves::Removal claimed;
+    ASSERT_TRUE(cache._pending_storage_removes.claim(key, 0, &claimed));
+
+    auto sync_remove = std::async(std::launch::async, [&] { 
cache.remove_if_cached(key); });
+    // remove_if_cached marks the position again and erases the cell in one 
cache lock hold, and
+    // only then waits for the owner. Wait for the cell to go rather than for 
a fixed time, so a
+    // slow thread start cannot reach finish() below before the position was 
marked again.
+    auto deadline = std::chrono::steady_clock::now() + 
std::chrono::seconds(10);
+    while (true) {
+        {
+            std::lock_guard lock(cache._mutex);
+            if (!cache._files.contains(key)) {
+                break;
+            }
+        }
+        ASSERT_LT(std::chrono::steady_clock::now(), deadline);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
+    }
+    EXPECT_EQ(sync_remove.wait_for(std::chrono::milliseconds(0)), 
std::future_status::timeout);
+    EXPECT_TRUE(fs::exists(path));
+    // GC does not wait: it leaves a removal someone else is running.
+    cache.run_storage_remove(key, 0, /*wait_for_owner=*/false);
+
+    // The other owner finishes without deleting. remove_if_cached marked the 
position again while
+    // it ran, so the waiting caller claims it and deletes the file itself 
before returning.
+    EXPECT_TRUE(cache._pending_storage_removes.finish(key, 0));
+    ASSERT_EQ(sync_remove.wait_for(std::chrono::seconds(10)), 
std::future_status::ready);
+    EXPECT_FALSE(fs::exists(path));
+    EXPECT_FALSE(cache._pending_storage_removes.contains(key, 0));
+}
+
+// A block is evicted and its removal stalls; meanwhile the same position is 
downloaded again.
+// The new download must wait for the stale removal, so the new file survives.
+TEST_F(BlockFileCacheTest, evict_io_recreated_block_survives_stale_remove) {
+    auto base = evict_io_cache_path("recreate");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(2 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto victim = BlockFileCache::hash("evict_io_victim");
+    auto other = BlockFileCache::hash("evict_io_other");
+    auto newcomer = BlockFileCache::hash("evict_io_newcomer");
+    insert_block(cache, victim, 0, kBlockSize, 'a');
+    insert_block(cache, other, 0, kBlockSize, 'b');
+
+    std::promise<void> remove_entered;
+    std::promise<void> release_remove;
+    auto release_future = release_remove.get_future().share();
+    std::atomic<bool> entered_once {false};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != victim || entered_once.exchange(true)) {
+                    return;
+                }
+                remove_entered.set_value();
+                release_future.wait();
+            },
+            &guard);
+
+    // Evicts the victim; its storage removal blocks in the sync point after 
the lock is released.
+    auto evictor = std::async(std::launch::async, [&] {
+        SCOPED_INIT_THREAD_CONTEXT();
+        insert_block(cache, newcomer, 0, kBlockSize, 'c');
+    });
+    remove_entered.get_future().wait();
+
+    // Download the victim position again while the stale removal is in flight.
+    std::atomic<bool> recreated {false};
+    auto recreator = std::async(std::launch::async, [&] {
+        SCOPED_INIT_THREAD_CONTEXT();
+        insert_block(cache, victim, 0, kBlockSize, 'd');
+        recreated = true;
+    });
+    std::this_thread::sleep_for(std::chrono::milliseconds(200));
+    EXPECT_FALSE(recreated.load()) << "the new download must wait for the 
stale removal";
+
+    release_remove.set_value();
+    evictor.get();
+    recreator.get();
+    ASSERT_TRUE(recreated.load());
+
+    auto path = block_path(base, victim, 0);
+    ASSERT_TRUE(fs::exists(path));
+    std::ifstream in(path);
+    std::string content((std::istreambuf_iterator<char>(in)), 
std::istreambuf_iterator<char>());
+    EXPECT_EQ(content, std::string(kBlockSize, 'd'));
+    EXPECT_EQ(cache._pending_storage_removes.size(), 0U);
+}
+
+// A removal that is queued but not yet claimed is run by the downloader of 
the replacement
+// block before it writes, so the queued item later finds nothing to do.
+TEST_F(BlockFileCacheTest, evict_io_queued_remove_drained_by_new_download) {
+    auto base = evict_io_cache_path("queued");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    auto old_interval = config::file_cache_background_gc_interval_ms;
+    // Keep the background GC thread from draining the queue during the test.
+    config::file_cache_background_gc_interval_ms = 3600 * 1000;
+    Defer restore {[&] { config::file_cache_background_gc_interval_ms = 
old_interval; }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+    auto key = BlockFileCache::hash("evict_io_queued");
+    insert_block(cache, key, 0, kBlockSize, 'a');
+
+    cache.remove_if_cached_async(key);
+    ASSERT_TRUE(cache._pending_storage_removes.contains(key, 0));
+    ASSERT_TRUE(fs::exists(block_path(base, key, 0)));
+
+    insert_block(cache, key, 0, kBlockSize, 'b');
+    EXPECT_FALSE(cache._pending_storage_removes.contains(key, 0));
+
+    // The queued item no longer owns the position.
+    FileCacheKey queued;
+    ASSERT_TRUE(cache._recycle_keys.try_dequeue(queued));
+    cache.run_storage_remove(queued.hash, queued.offset, 
/*wait_for_owner=*/false);
+    auto path = block_path(base, key, 0);
+    ASSERT_TRUE(fs::exists(path));
+    std::ifstream in(path);
+    std::string content((std::istreambuf_iterator<char>(in)), 
std::istreambuf_iterator<char>());
+    EXPECT_EQ(content, std::string(kBlockSize, 'b'));
+}
+
+// A pending removal run by a replacement block's downloader still records its 
latency, into the
+// recorder of the path that marked it: an async removal drained before GC 
reaches it is sampled
+// by the async recorder exactly once, and GC later skips the key without a 
second sample.
+TEST_F(BlockFileCacheTest, evict_io_drained_remove_records_latency) {
+    auto base = evict_io_cache_path("drain_latency");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    auto old_interval = config::file_cache_background_gc_interval_ms;
+    // Keep the background GC thread from draining the queue during the test.
+    config::file_cache_background_gc_interval_ms = 3600 * 1000;
+    Defer restore {[&] { config::file_cache_background_gc_interval_ms = 
old_interval; }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+    auto key = BlockFileCache::hash("evict_io_drain_latency");
+    insert_block(cache, key, 0, kBlockSize);
+    auto path = block_path(base, key, 0);
+    ASSERT_TRUE(fs::exists(path));
+
+    const int64_t async_before = 
cache._storage_async_remove_latency_us->count();
+    const int64_t sync_before = cache._storage_sync_remove_latency_us->count();
+    cache.remove_if_cached_async(key);
+    ASSERT_TRUE(cache._pending_storage_removes.contains(key, 0));
+
+    cache.drain_pending_storage_remove(key, 0);
+    EXPECT_FALSE(cache._pending_storage_removes.contains(key, 0));
+    EXPECT_FALSE(fs::exists(path));
+    EXPECT_EQ(cache._storage_async_remove_latency_us->count(), async_before + 
1);
+
+    FileCacheKey queued;
+    ASSERT_TRUE(cache._recycle_keys.try_dequeue(queued));
+    cache.run_storage_remove(queued.hash, queued.offset, 
/*wait_for_owner=*/false);
+    EXPECT_EQ(cache._storage_async_remove_latency_us->count(), async_before + 
1);
+    EXPECT_EQ(cache._storage_sync_remove_latency_us->count(), sync_before);
+}
+
+// Many threads reserve, evict and re-insert a small set of hot positions. 
Every block the cache
+// believes is downloaded must still have its file once all removals have 
drained.
+TEST_F(BlockFileCacheTest, evict_io_concurrent_reserve_evict_reinsert) {
+    auto base = evict_io_cache_path("concurrent");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    constexpr size_t kBlocksInCache = 8;
+    BlockFileCache cache(base, normal_only_settings(kBlocksInCache * 
kBlockSize, kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    constexpr int kThreads = 16;
+    constexpr int kIterations = 400;
+    constexpr int kKeys = 6;
+    constexpr int kOffsets = 4;
+    std::vector<UInt128Wrapper> keys;
+    for (int i = 0; i < kKeys; ++i) {
+        keys.push_back(BlockFileCache::hash("evict_io_concurrent_" + 
std::to_string(i)));
+    }
+    // Reads populate the process-wide FDCache; later tests assert on its size.
+    Defer clear_fd_cache {[&] {
+        for (const auto& hash : keys) {
+            for (int o = 0; o < kOffsets; ++o) {
+                FDCache::instance()->remove_file_reader(std::make_pair(hash, o 
* kBlockSize));
+            }
+        }
+    }};
+    std::atomic<int> read_failures {0};
+    std::vector<std::thread> threads;
+    for (int t = 0; t < kThreads; ++t) {
+        threads.emplace_back([&, t] {
+            SCOPED_INIT_THREAD_CONTEXT();
+            std::mt19937 rng(t);
+            for (int i = 0; i < kIterations; ++i) {
+                const auto& hash = keys[rng() % kKeys];
+                size_t offset = (rng() % kOffsets) * kBlockSize;
+                CacheContext context;
+                ReadStatistics rstats;
+                context.stats = &rstats;
+                context.cache_type = FileCacheType::NORMAL;
+                auto holder = cache.get_or_set(hash, offset, kBlockSize, 
context);
+                for (auto& block : holder.file_blocks) {
+                    if (block->state() == FileBlock::State::EMPTY &&
+                        block->get_or_set_downloader() == 
FileBlock::get_caller_id()) {
+                        std::string data(block->range().size(), 'x');
+                        if (!block->append(Slice(data.data(), 
data.size())).ok() ||

Review Comment:
   [P2] Check cache write outcomes in the concurrent reinsert test
   
   The stress case exercises precisely the directory-removal versus writer-open 
race handled by the new retries. But append/finalize failures here are 
discarded, and only reads of cells that reached DOWNLOADED contribute to 
read_failures. The test can pass even if a large fraction of admitted cache 
writes fail, provided one downloaded cell survives at the end. Track and assert 
unexpected write failures separately from legitimate SKIP_CACHE admissions, and 
verify successful reads contain the expected payload, so the test detects 
regressions in the writer/recreate path rather than masking them.



##########
be/test/io/cache/block_file_cache_evict_io_test.cpp:
##########
@@ -0,0 +1,666 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Storage removal of evicted file cache blocks: it must run outside the cache 
lock, must never
+// delete a block re-created at the same position, and must treat missing 
files as removed.
+
+#include <atomic>
+#include <future>
+
+#include "io/cache/block_file_cache_test_common.h"
+#include "util/defer_op.h"
+
+namespace doris::io {
+
+namespace {
+
+constexpr size_t kBlockSize = 10;
+
+std::string evict_io_cache_path(const std::string& name) {
+    return (caches_dir / ("evict_io_" + name) / "").string();
+}
+
+FileCacheSettings normal_only_settings(size_t capacity, size_t block_size) {
+    FileCacheSettings settings;
+    settings.index_queue_elements = 0;
+    settings.index_queue_size = 0;
+    settings.disposable_queue_size = 0;
+    settings.disposable_queue_elements = 0;
+    settings.ttl_queue_size = 0;
+    settings.ttl_queue_elements = 0;
+    settings.query_queue_size = capacity;
+    settings.query_queue_elements = capacity / block_size + 1;
+    settings.max_file_block_size = block_size;
+    settings.max_query_cache_size = capacity;
+    settings.capacity = capacity;
+    return settings;
+}
+
+std::string block_path(const std::string& base, const UInt128Wrapper& hash, 
size_t offset) {
+    auto key_str = hash.to_string();
+    return (fs::path(base) / key_str.substr(0, 3) / (key_str + "_0") / 
std::to_string(offset))
+            .string();
+}
+
+// Inserts [offset, offset + size) of hash, downloads it with `fill` and 
releases the holder.
+void insert_block(BlockFileCache& cache, const UInt128Wrapper& hash, size_t 
offset, size_t size,
+                  char fill = '0') {
+    CacheContext context;
+    ReadStatistics rstats;
+    context.stats = &rstats;
+    context.cache_type = FileCacheType::NORMAL;
+    auto holder = cache.get_or_set(hash, offset, size, context);
+    for (auto& block : holder.file_blocks) {
+        if (block->state() != FileBlock::State::EMPTY ||
+            block->get_or_set_downloader() != FileBlock::get_caller_id()) {
+            continue;
+        }
+        std::string data(block->range().size(), fill);
+        ASSERT_TRUE(block->append(Slice(data.data(), data.size())).ok());
+        ASSERT_TRUE(block->finalize().ok());
+    }
+}
+
+// Whether `mutex` stays held for a whole 200 ms window, as it is when the 
thread calling this
+// is parked in a sync point while holding it. The cache's monitor and GC 
threads take the same
+// mutex too, but only briefly, so one failed try_lock would not prove the 
caller holds it.
+// try_lock from the owning thread is undefined, so the probe runs on its own 
thread.
+bool is_held_throughout(std::mutex& mutex) {
+    bool acquired = false;
+    std::thread probe([&] {
+        const auto deadline = std::chrono::steady_clock::now() + 
std::chrono::milliseconds(200);
+        while (std::chrono::steady_clock::now() < deadline) {
+            if (mutex.try_lock()) {
+                mutex.unlock();
+                acquired = true;
+                return;
+            }
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
+        }
+    });
+    probe.join();
+    return !acquired;
+}
+
+// Evicts one block and checks that its storage removal runs, with the cache 
lock not held.
+void run_eviction_lock_probe() {
+    auto base = evict_io_cache_path("lock_probe");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(3 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key1 = BlockFileCache::hash("evict_io_lock_key1");
+    auto key2 = BlockFileCache::hash("evict_io_lock_key2");
+    insert_block(cache, key1, 0, 3 * kBlockSize);
+    ASSERT_TRUE(fs::exists(block_path(base, key1, 0)));
+
+    std::atomic<int> removes {0};
+    std::atomic<int> removes_under_lock {0};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != key1) {
+                    return;
+                }
+                ++removes;
+                if (is_held_throughout(cache._mutex)) {
+                    ++removes_under_lock;
+                }
+            },
+            &guard);
+
+    // The cache is full: reserving the new block evicts key1's LRU head 
synchronously.
+    insert_block(cache, key2, 0, kBlockSize);
+
+    EXPECT_EQ(removes.load(), 1);
+    EXPECT_EQ(removes_under_lock.load(), 0);
+    // The removal still completes on the evicting thread: it is done when 
get_or_set returns.
+    EXPECT_FALSE(fs::exists(block_path(base, key1, 0)));
+    EXPECT_TRUE(fs::exists(block_path(base, key1, kBlockSize)));
+    EXPECT_EQ(cache._pending_storage_removes.size(), 0U);
+}
+
+} // namespace
+
+TEST_F(BlockFileCacheTest, 
evict_io_storage_remove_runs_after_cache_lock_released) {
+    run_eviction_lock_probe();
+}
+
+// Negative control for is_held_throughout(), which the lock checks in these 
tests rely on.
+TEST(BlockFileCacheEvictIoProbeTest, lock_probe_detects_held_lock) {
+    std::mutex mutex;
+    EXPECT_FALSE(is_held_throughout(mutex));
+    std::lock_guard lock(mutex);
+    EXPECT_TRUE(is_held_throughout(mutex));
+}
+
+TEST_F(BlockFileCacheTest, evict_io_remove_if_cached_removes_after_unlock) {
+    auto base = evict_io_cache_path("remove_if_cached");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+    auto key = BlockFileCache::hash("evict_io_remove_if_cached");
+    insert_block(cache, key, 0, 3 * kBlockSize);
+
+    std::atomic<int> removes_under_lock {0};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&&) {
+                if (is_held_throughout(cache._mutex)) {
+                    ++removes_under_lock;
+                }
+            },
+            &guard);
+
+    cache.remove_if_cached(key);
+    EXPECT_EQ(removes_under_lock.load(), 0);
+    for (size_t offset = 0; offset < 3 * kBlockSize; offset += kBlockSize) {
+        EXPECT_FALSE(fs::exists(block_path(base, key, offset))) << offset;
+    }
+    auto key_str = key.to_string();
+    EXPECT_FALSE(fs::exists(fs::path(base) / key_str.substr(0, 3) / (key_str + 
"_0")));
+}
+
+// While an evicted block's storage removal is stalled, unrelated cache 
lookups do not wait for
+// it: the removal runs after the cache lock is released.
+TEST_F(BlockFileCacheTest, evict_io_lookup_proceeds_while_remove_stalls) {
+    auto base = evict_io_cache_path("stalled_remove");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(2 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto victim = BlockFileCache::hash("evict_io_stall_victim");
+    auto other = BlockFileCache::hash("evict_io_stall_other");
+    auto newcomer = BlockFileCache::hash("evict_io_stall_newcomer");
+    insert_block(cache, victim, 0, kBlockSize);
+    insert_block(cache, other, 0, kBlockSize);
+
+    std::promise<void> remove_entered;
+    std::promise<void> release_remove;
+    auto release_future = release_remove.get_future().share();
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != victim) {
+                    return;
+                }
+                remove_entered.set_value();
+                release_future.wait();
+            },
+            &guard);
+
+    // Declared before the Defer that releases the evictor, so on a failure 
path the evictor is
+    // released before this future's destructor waits for the lookup.
+    std::future<bool> lookup;
+    // Inserting into the full cache evicts the victim; its removal then 
stalls on this thread.
+    std::thread evictor([&] { insert_block(cache, newcomer, 0, kBlockSize); });
+    Defer join_evictor {[&] {
+        release_remove.set_value();
+        evictor.join();
+    }};
+    ASSERT_EQ(remove_entered.get_future().wait_for(std::chrono::seconds(10)),
+              std::future_status::ready);
+
+    lookup = std::async(std::launch::async, [&] {
+        CacheContext context;
+        ReadStatistics rstats;
+        context.stats = &rstats;
+        context.cache_type = FileCacheType::NORMAL;
+        auto holder = cache.get_or_set(other, 0, kBlockSize, context);
+        return holder.file_blocks.size() == 1 &&
+               holder.file_blocks.front()->state() == 
FileBlock::State::DOWNLOADED;
+    });
+    ASSERT_EQ(lookup.wait_for(std::chrono::seconds(10)), 
std::future_status::ready);
+    EXPECT_TRUE(lookup.get());
+    EXPECT_FALSE(is_held_throughout(cache._mutex));
+}
+
+// A block evicted while its removal is still pending is not brought back by 
loading the hash's
+// blocks from storage (lazy load at startup, async load, LRU restore), which 
would leave a cached
+// block whose file the pending removal then deletes.
+TEST_F(BlockFileCacheTest, evict_io_load_skips_block_pending_removal) {
+    auto base = evict_io_cache_path("load_pending");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_io_load_pending");
+    FileCacheKey pending;
+    pending.hash = key;
+    pending.offset = 0;
+    cache._pending_storage_removes.mark(pending, 
cache._storage_sync_remove_latency_us.get());
+
+    CacheContext context;
+    context.cache_type = FileCacheType::NORMAL;
+    std::lock_guard cache_lock(cache._mutex);
+    EXPECT_EQ(cache.add_cell(key, context, 0, kBlockSize, 
FileBlock::State::DOWNLOADED, cache_lock),
+              nullptr);
+    EXPECT_FALSE(cache._files.contains(key));
+    // Another offset of the same hash, and a new block at the pending 
position, are added: the
+    // new block's downloader drains the pending removal before it writes.
+    EXPECT_NE(cache.add_cell(key, context, kBlockSize, kBlockSize, 
FileBlock::State::DOWNLOADED,
+                             cache_lock),
+              nullptr);
+    EXPECT_NE(cache.add_cell(key, context, 0, kBlockSize, 
FileBlock::State::EMPTY, cache_lock),
+              nullptr);
+}
+
+// A synchronous removal whose position another thread (a replacement block's 
downloader, or GC)
+// is already removing waits for that owner, so the file is gone when it 
returns. Driven through
+// remove_if_cached, whose lock scope runs the removal after the cache lock is 
released.
+TEST_F(BlockFileCacheTest, evict_io_sync_remove_waits_for_competing_owner) {
+    auto base = evict_io_cache_path("competing_owner");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_io_competing_owner");
+    insert_block(cache, key, 0, kBlockSize);
+    auto path = block_path(base, key, 0);
+    ASSERT_TRUE(fs::exists(path));
+
+    // Another thread is mid-removal at (key, 0) and has not unlinked the file 
yet.
+    FileCacheKey other;
+    other.hash = key;
+    other.offset = 0;
+    cache._pending_storage_removes.mark(other, 
cache._storage_async_remove_latency_us.get());
+    PendingStorageRemoves::Removal claimed;
+    ASSERT_TRUE(cache._pending_storage_removes.claim(key, 0, &claimed));
+
+    auto sync_remove = std::async(std::launch::async, [&] { 
cache.remove_if_cached(key); });
+    // remove_if_cached marks the position again and erases the cell in one 
cache lock hold, and
+    // only then waits for the owner. Wait for the cell to go rather than for 
a fixed time, so a
+    // slow thread start cannot reach finish() below before the position was 
marked again.
+    auto deadline = std::chrono::steady_clock::now() + 
std::chrono::seconds(10);
+    while (true) {
+        {
+            std::lock_guard lock(cache._mutex);
+            if (!cache._files.contains(key)) {
+                break;
+            }
+        }
+        ASSERT_LT(std::chrono::steady_clock::now(), deadline);

Review Comment:
   [P2] Release the synthetic removal owner on test failure
   
   If this deadline assertion fails (for example, the async worker has not 
started in time), the test returns before calling `finish()` below. The future 
destructor waits for the worker, which will wait for the still-running manual 
claim forever. Also, if the implementation regresses to waiting for a competing 
owner under the cache mutex, the blocking lock acquisition in this loop 
prevents reaching the deadline at all. Use bounded/nonblocking observation and 
a failure-safe guard that releases the manual claim before the future is 
destroyed. The nearby stalled-lookup test uses a release guard for this reason. 
The recreated-block test should similarly bound its callback wait and put 
release/join cleanup on all exits.



##########
be/test/io/cache/block_file_cache_evict_io_test.cpp:
##########
@@ -0,0 +1,666 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Storage removal of evicted file cache blocks: it must run outside the cache 
lock, must never
+// delete a block re-created at the same position, and must treat missing 
files as removed.
+
+#include <atomic>
+#include <future>
+
+#include "io/cache/block_file_cache_test_common.h"
+#include "util/defer_op.h"
+
+namespace doris::io {
+
+namespace {
+
+constexpr size_t kBlockSize = 10;
+
+std::string evict_io_cache_path(const std::string& name) {
+    return (caches_dir / ("evict_io_" + name) / "").string();
+}
+
+FileCacheSettings normal_only_settings(size_t capacity, size_t block_size) {
+    FileCacheSettings settings;
+    settings.index_queue_elements = 0;
+    settings.index_queue_size = 0;
+    settings.disposable_queue_size = 0;
+    settings.disposable_queue_elements = 0;
+    settings.ttl_queue_size = 0;
+    settings.ttl_queue_elements = 0;
+    settings.query_queue_size = capacity;
+    settings.query_queue_elements = capacity / block_size + 1;
+    settings.max_file_block_size = block_size;
+    settings.max_query_cache_size = capacity;
+    settings.capacity = capacity;
+    return settings;
+}
+
+std::string block_path(const std::string& base, const UInt128Wrapper& hash, 
size_t offset) {
+    auto key_str = hash.to_string();
+    return (fs::path(base) / key_str.substr(0, 3) / (key_str + "_0") / 
std::to_string(offset))
+            .string();
+}
+
+// Inserts [offset, offset + size) of hash, downloads it with `fill` and 
releases the holder.
+void insert_block(BlockFileCache& cache, const UInt128Wrapper& hash, size_t 
offset, size_t size,
+                  char fill = '0') {
+    CacheContext context;
+    ReadStatistics rstats;
+    context.stats = &rstats;
+    context.cache_type = FileCacheType::NORMAL;
+    auto holder = cache.get_or_set(hash, offset, size, context);
+    for (auto& block : holder.file_blocks) {
+        if (block->state() != FileBlock::State::EMPTY ||
+            block->get_or_set_downloader() != FileBlock::get_caller_id()) {
+            continue;
+        }
+        std::string data(block->range().size(), fill);
+        ASSERT_TRUE(block->append(Slice(data.data(), data.size())).ok());
+        ASSERT_TRUE(block->finalize().ok());
+    }
+}
+
+// Whether `mutex` stays held for a whole 200 ms window, as it is when the 
thread calling this
+// is parked in a sync point while holding it. The cache's monitor and GC 
threads take the same
+// mutex too, but only briefly, so one failed try_lock would not prove the 
caller holds it.
+// try_lock from the owning thread is undefined, so the probe runs on its own 
thread.
+bool is_held_throughout(std::mutex& mutex) {
+    bool acquired = false;
+    std::thread probe([&] {
+        const auto deadline = std::chrono::steady_clock::now() + 
std::chrono::milliseconds(200);
+        while (std::chrono::steady_clock::now() < deadline) {
+            if (mutex.try_lock()) {
+                mutex.unlock();
+                acquired = true;
+                return;
+            }
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
+        }
+    });
+    probe.join();
+    return !acquired;
+}
+
+// Evicts one block and checks that its storage removal runs, with the cache 
lock not held.
+void run_eviction_lock_probe() {
+    auto base = evict_io_cache_path("lock_probe");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(3 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key1 = BlockFileCache::hash("evict_io_lock_key1");
+    auto key2 = BlockFileCache::hash("evict_io_lock_key2");
+    insert_block(cache, key1, 0, 3 * kBlockSize);
+    ASSERT_TRUE(fs::exists(block_path(base, key1, 0)));
+
+    std::atomic<int> removes {0};
+    std::atomic<int> removes_under_lock {0};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != key1) {
+                    return;
+                }
+                ++removes;
+                if (is_held_throughout(cache._mutex)) {
+                    ++removes_under_lock;
+                }
+            },
+            &guard);
+
+    // The cache is full: reserving the new block evicts key1's LRU head 
synchronously.
+    insert_block(cache, key2, 0, kBlockSize);
+
+    EXPECT_EQ(removes.load(), 1);
+    EXPECT_EQ(removes_under_lock.load(), 0);
+    // The removal still completes on the evicting thread: it is done when 
get_or_set returns.
+    EXPECT_FALSE(fs::exists(block_path(base, key1, 0)));
+    EXPECT_TRUE(fs::exists(block_path(base, key1, kBlockSize)));
+    EXPECT_EQ(cache._pending_storage_removes.size(), 0U);
+}
+
+} // namespace
+
+TEST_F(BlockFileCacheTest, 
evict_io_storage_remove_runs_after_cache_lock_released) {
+    run_eviction_lock_probe();
+}
+
+// Negative control for is_held_throughout(), which the lock checks in these 
tests rely on.
+TEST(BlockFileCacheEvictIoProbeTest, lock_probe_detects_held_lock) {
+    std::mutex mutex;
+    EXPECT_FALSE(is_held_throughout(mutex));
+    std::lock_guard lock(mutex);
+    EXPECT_TRUE(is_held_throughout(mutex));
+}
+
+TEST_F(BlockFileCacheTest, evict_io_remove_if_cached_removes_after_unlock) {
+    auto base = evict_io_cache_path("remove_if_cached");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+    auto key = BlockFileCache::hash("evict_io_remove_if_cached");
+    insert_block(cache, key, 0, 3 * kBlockSize);
+
+    std::atomic<int> removes_under_lock {0};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&&) {
+                if (is_held_throughout(cache._mutex)) {
+                    ++removes_under_lock;
+                }
+            },
+            &guard);
+
+    cache.remove_if_cached(key);
+    EXPECT_EQ(removes_under_lock.load(), 0);
+    for (size_t offset = 0; offset < 3 * kBlockSize; offset += kBlockSize) {
+        EXPECT_FALSE(fs::exists(block_path(base, key, offset))) << offset;
+    }
+    auto key_str = key.to_string();
+    EXPECT_FALSE(fs::exists(fs::path(base) / key_str.substr(0, 3) / (key_str + 
"_0")));
+}
+
+// While an evicted block's storage removal is stalled, unrelated cache 
lookups do not wait for
+// it: the removal runs after the cache lock is released.
+TEST_F(BlockFileCacheTest, evict_io_lookup_proceeds_while_remove_stalls) {
+    auto base = evict_io_cache_path("stalled_remove");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(2 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto victim = BlockFileCache::hash("evict_io_stall_victim");
+    auto other = BlockFileCache::hash("evict_io_stall_other");
+    auto newcomer = BlockFileCache::hash("evict_io_stall_newcomer");
+    insert_block(cache, victim, 0, kBlockSize);
+    insert_block(cache, other, 0, kBlockSize);
+
+    std::promise<void> remove_entered;
+    std::promise<void> release_remove;
+    auto release_future = release_remove.get_future().share();
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != victim) {
+                    return;
+                }
+                remove_entered.set_value();
+                release_future.wait();
+            },
+            &guard);
+
+    // Declared before the Defer that releases the evictor, so on a failure 
path the evictor is
+    // released before this future's destructor waits for the lookup.
+    std::future<bool> lookup;
+    // Inserting into the full cache evicts the victim; its removal then 
stalls on this thread.
+    std::thread evictor([&] { insert_block(cache, newcomer, 0, kBlockSize); });
+    Defer join_evictor {[&] {
+        release_remove.set_value();
+        evictor.join();
+    }};
+    ASSERT_EQ(remove_entered.get_future().wait_for(std::chrono::seconds(10)),
+              std::future_status::ready);
+
+    lookup = std::async(std::launch::async, [&] {
+        CacheContext context;
+        ReadStatistics rstats;
+        context.stats = &rstats;
+        context.cache_type = FileCacheType::NORMAL;
+        auto holder = cache.get_or_set(other, 0, kBlockSize, context);
+        return holder.file_blocks.size() == 1 &&
+               holder.file_blocks.front()->state() == 
FileBlock::State::DOWNLOADED;
+    });
+    ASSERT_EQ(lookup.wait_for(std::chrono::seconds(10)), 
std::future_status::ready);
+    EXPECT_TRUE(lookup.get());
+    EXPECT_FALSE(is_held_throughout(cache._mutex));
+}
+
+// A block evicted while its removal is still pending is not brought back by 
loading the hash's
+// blocks from storage (lazy load at startup, async load, LRU restore), which 
would leave a cached
+// block whose file the pending removal then deletes.
+TEST_F(BlockFileCacheTest, evict_io_load_skips_block_pending_removal) {
+    auto base = evict_io_cache_path("load_pending");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_io_load_pending");
+    FileCacheKey pending;
+    pending.hash = key;
+    pending.offset = 0;
+    cache._pending_storage_removes.mark(pending, 
cache._storage_sync_remove_latency_us.get());
+
+    CacheContext context;
+    context.cache_type = FileCacheType::NORMAL;
+    std::lock_guard cache_lock(cache._mutex);
+    EXPECT_EQ(cache.add_cell(key, context, 0, kBlockSize, 
FileBlock::State::DOWNLOADED, cache_lock),
+              nullptr);
+    EXPECT_FALSE(cache._files.contains(key));
+    // Another offset of the same hash, and a new block at the pending 
position, are added: the
+    // new block's downloader drains the pending removal before it writes.
+    EXPECT_NE(cache.add_cell(key, context, kBlockSize, kBlockSize, 
FileBlock::State::DOWNLOADED,
+                             cache_lock),
+              nullptr);
+    EXPECT_NE(cache.add_cell(key, context, 0, kBlockSize, 
FileBlock::State::EMPTY, cache_lock),
+              nullptr);
+}
+
+// A synchronous removal whose position another thread (a replacement block's 
downloader, or GC)
+// is already removing waits for that owner, so the file is gone when it 
returns. Driven through
+// remove_if_cached, whose lock scope runs the removal after the cache lock is 
released.
+TEST_F(BlockFileCacheTest, evict_io_sync_remove_waits_for_competing_owner) {
+    auto base = evict_io_cache_path("competing_owner");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_io_competing_owner");
+    insert_block(cache, key, 0, kBlockSize);
+    auto path = block_path(base, key, 0);
+    ASSERT_TRUE(fs::exists(path));
+
+    // Another thread is mid-removal at (key, 0) and has not unlinked the file 
yet.
+    FileCacheKey other;
+    other.hash = key;
+    other.offset = 0;
+    cache._pending_storage_removes.mark(other, 
cache._storage_async_remove_latency_us.get());
+    PendingStorageRemoves::Removal claimed;
+    ASSERT_TRUE(cache._pending_storage_removes.claim(key, 0, &claimed));
+
+    auto sync_remove = std::async(std::launch::async, [&] { 
cache.remove_if_cached(key); });
+    // remove_if_cached marks the position again and erases the cell in one 
cache lock hold, and
+    // only then waits for the owner. Wait for the cell to go rather than for 
a fixed time, so a
+    // slow thread start cannot reach finish() below before the position was 
marked again.
+    auto deadline = std::chrono::steady_clock::now() + 
std::chrono::seconds(10);
+    while (true) {
+        {
+            std::lock_guard lock(cache._mutex);
+            if (!cache._files.contains(key)) {
+                break;
+            }
+        }
+        ASSERT_LT(std::chrono::steady_clock::now(), deadline);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
+    }
+    EXPECT_EQ(sync_remove.wait_for(std::chrono::milliseconds(0)), 
std::future_status::timeout);
+    EXPECT_TRUE(fs::exists(path));
+    // GC does not wait: it leaves a removal someone else is running.
+    cache.run_storage_remove(key, 0, /*wait_for_owner=*/false);
+
+    // The other owner finishes without deleting. remove_if_cached marked the 
position again while
+    // it ran, so the waiting caller claims it and deletes the file itself 
before returning.
+    EXPECT_TRUE(cache._pending_storage_removes.finish(key, 0));
+    ASSERT_EQ(sync_remove.wait_for(std::chrono::seconds(10)), 
std::future_status::ready);
+    EXPECT_FALSE(fs::exists(path));
+    EXPECT_FALSE(cache._pending_storage_removes.contains(key, 0));
+}
+
+// A block is evicted and its removal stalls; meanwhile the same position is 
downloaded again.
+// The new download must wait for the stale removal, so the new file survives.
+TEST_F(BlockFileCacheTest, evict_io_recreated_block_survives_stale_remove) {
+    auto base = evict_io_cache_path("recreate");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(2 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto victim = BlockFileCache::hash("evict_io_victim");
+    auto other = BlockFileCache::hash("evict_io_other");
+    auto newcomer = BlockFileCache::hash("evict_io_newcomer");
+    insert_block(cache, victim, 0, kBlockSize, 'a');
+    insert_block(cache, other, 0, kBlockSize, 'b');
+
+    std::promise<void> remove_entered;
+    std::promise<void> release_remove;
+    auto release_future = release_remove.get_future().share();
+    std::atomic<bool> entered_once {false};
+    auto* sp = SyncPoint::get_instance();
+    sp->enable_processing();
+    Defer disable_sp {[&] { sp->disable_processing(); }};
+    SyncPoint::CallbackGuard guard;
+    sp->set_call_back(
+            "BlockFileCache::run_storage_remove",
+            [&](auto&& args) {
+                auto* key = try_any_cast<FileCacheKey*>(args[0]);
+                if (key->hash != victim || entered_once.exchange(true)) {
+                    return;
+                }
+                remove_entered.set_value();
+                release_future.wait();
+            },
+            &guard);
+
+    // Evicts the victim; its storage removal blocks in the sync point after 
the lock is released.
+    auto evictor = std::async(std::launch::async, [&] {
+        SCOPED_INIT_THREAD_CONTEXT();
+        insert_block(cache, newcomer, 0, kBlockSize, 'c');
+    });
+    remove_entered.get_future().wait();
+
+    // Download the victim position again while the stale removal is in flight.
+    std::atomic<bool> recreated {false};
+    auto recreator = std::async(std::launch::async, [&] {
+        SCOPED_INIT_THREAD_CONTEXT();
+        insert_block(cache, victim, 0, kBlockSize, 'd');
+        recreated = true;
+    });
+    std::this_thread::sleep_for(std::chrono::milliseconds(200));
+    EXPECT_FALSE(recreated.load()) << "the new download must wait for the 
stale removal";
+
+    release_remove.set_value();
+    evictor.get();
+    recreator.get();
+    ASSERT_TRUE(recreated.load());
+
+    auto path = block_path(base, victim, 0);
+    ASSERT_TRUE(fs::exists(path));
+    std::ifstream in(path);
+    std::string content((std::istreambuf_iterator<char>(in)), 
std::istreambuf_iterator<char>());
+    EXPECT_EQ(content, std::string(kBlockSize, 'd'));
+    EXPECT_EQ(cache._pending_storage_removes.size(), 0U);
+}
+
+// A removal that is queued but not yet claimed is run by the downloader of 
the replacement
+// block before it writes, so the queued item later finds nothing to do.
+TEST_F(BlockFileCacheTest, evict_io_queued_remove_drained_by_new_download) {
+    auto base = evict_io_cache_path("queued");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    auto old_interval = config::file_cache_background_gc_interval_ms;
+    // Keep the background GC thread from draining the queue during the test.
+    config::file_cache_background_gc_interval_ms = 3600 * 1000;
+    Defer restore {[&] { config::file_cache_background_gc_interval_ms = 
old_interval; }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+    auto key = BlockFileCache::hash("evict_io_queued");
+    insert_block(cache, key, 0, kBlockSize, 'a');
+
+    cache.remove_if_cached_async(key);
+    ASSERT_TRUE(cache._pending_storage_removes.contains(key, 0));
+    ASSERT_TRUE(fs::exists(block_path(base, key, 0)));
+
+    insert_block(cache, key, 0, kBlockSize, 'b');
+    EXPECT_FALSE(cache._pending_storage_removes.contains(key, 0));
+
+    // The queued item no longer owns the position.
+    FileCacheKey queued;
+    ASSERT_TRUE(cache._recycle_keys.try_dequeue(queued));
+    cache.run_storage_remove(queued.hash, queued.offset, 
/*wait_for_owner=*/false);
+    auto path = block_path(base, key, 0);
+    ASSERT_TRUE(fs::exists(path));
+    std::ifstream in(path);
+    std::string content((std::istreambuf_iterator<char>(in)), 
std::istreambuf_iterator<char>());
+    EXPECT_EQ(content, std::string(kBlockSize, 'b'));
+}
+
+// A pending removal run by a replacement block's downloader still records its 
latency, into the
+// recorder of the path that marked it: an async removal drained before GC 
reaches it is sampled
+// by the async recorder exactly once, and GC later skips the key without a 
second sample.
+TEST_F(BlockFileCacheTest, evict_io_drained_remove_records_latency) {
+    auto base = evict_io_cache_path("drain_latency");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    auto old_interval = config::file_cache_background_gc_interval_ms;
+    // Keep the background GC thread from draining the queue during the test.
+    config::file_cache_background_gc_interval_ms = 3600 * 1000;
+    Defer restore {[&] { config::file_cache_background_gc_interval_ms = 
old_interval; }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+    auto key = BlockFileCache::hash("evict_io_drain_latency");
+    insert_block(cache, key, 0, kBlockSize);
+    auto path = block_path(base, key, 0);
+    ASSERT_TRUE(fs::exists(path));
+
+    const int64_t async_before = 
cache._storage_async_remove_latency_us->count();
+    const int64_t sync_before = cache._storage_sync_remove_latency_us->count();
+    cache.remove_if_cached_async(key);
+    ASSERT_TRUE(cache._pending_storage_removes.contains(key, 0));
+
+    cache.drain_pending_storage_remove(key, 0);
+    EXPECT_FALSE(cache._pending_storage_removes.contains(key, 0));
+    EXPECT_FALSE(fs::exists(path));
+    EXPECT_EQ(cache._storage_async_remove_latency_us->count(), async_before + 
1);
+
+    FileCacheKey queued;
+    ASSERT_TRUE(cache._recycle_keys.try_dequeue(queued));
+    cache.run_storage_remove(queued.hash, queued.offset, 
/*wait_for_owner=*/false);
+    EXPECT_EQ(cache._storage_async_remove_latency_us->count(), async_before + 
1);
+    EXPECT_EQ(cache._storage_sync_remove_latency_us->count(), sync_before);
+}
+
+// Many threads reserve, evict and re-insert a small set of hot positions. 
Every block the cache
+// believes is downloaded must still have its file once all removals have 
drained.
+TEST_F(BlockFileCacheTest, evict_io_concurrent_reserve_evict_reinsert) {
+    auto base = evict_io_cache_path("concurrent");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    constexpr size_t kBlocksInCache = 8;
+    BlockFileCache cache(base, normal_only_settings(kBlocksInCache * 
kBlockSize, kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    constexpr int kThreads = 16;
+    constexpr int kIterations = 400;
+    constexpr int kKeys = 6;
+    constexpr int kOffsets = 4;
+    std::vector<UInt128Wrapper> keys;
+    for (int i = 0; i < kKeys; ++i) {
+        keys.push_back(BlockFileCache::hash("evict_io_concurrent_" + 
std::to_string(i)));
+    }
+    // Reads populate the process-wide FDCache; later tests assert on its size.
+    Defer clear_fd_cache {[&] {
+        for (const auto& hash : keys) {
+            for (int o = 0; o < kOffsets; ++o) {
+                FDCache::instance()->remove_file_reader(std::make_pair(hash, o 
* kBlockSize));
+            }
+        }
+    }};
+    std::atomic<int> read_failures {0};
+    std::vector<std::thread> threads;
+    for (int t = 0; t < kThreads; ++t) {
+        threads.emplace_back([&, t] {
+            SCOPED_INIT_THREAD_CONTEXT();
+            std::mt19937 rng(t);
+            for (int i = 0; i < kIterations; ++i) {
+                const auto& hash = keys[rng() % kKeys];
+                size_t offset = (rng() % kOffsets) * kBlockSize;
+                CacheContext context;
+                ReadStatistics rstats;
+                context.stats = &rstats;
+                context.cache_type = FileCacheType::NORMAL;
+                auto holder = cache.get_or_set(hash, offset, kBlockSize, 
context);
+                for (auto& block : holder.file_blocks) {
+                    if (block->state() == FileBlock::State::EMPTY &&
+                        block->get_or_set_downloader() == 
FileBlock::get_caller_id()) {
+                        std::string data(block->range().size(), 'x');
+                        if (!block->append(Slice(data.data(), 
data.size())).ok() ||
+                            !block->finalize().ok()) {
+                            continue;
+                        }
+                    }
+                    if (block->state() == FileBlock::State::DOWNLOADED) {
+                        std::string buf(block->range().size(), '\0');
+                        if (!block->read(Slice(buf.data(), buf.size()), 
0).ok()) {
+                            ++read_failures;
+                        }
+                    }
+                }
+            }
+        });
+    }
+    for (auto& thread : threads) {
+        thread.join();
+    }
+    EXPECT_EQ(read_failures.load(), 0);
+
+    // Drain whatever the background GC has not reached yet.
+    FileCacheKey queued;
+    while (cache._recycle_keys.try_dequeue(queued)) {
+        cache.run_storage_remove(queued.hash, queued.offset, 
/*wait_for_owner=*/false);
+    }
+    EXPECT_EQ(cache._pending_storage_removes.size(), 0U);
+
+    std::lock_guard lock(cache._mutex);
+    size_t downloaded = 0;
+    for (const auto& [hash, cells] : cache._files) {
+        for (const auto& [offset, cell] : cells) {
+            if (cell.file_block->state_unsafe() == 
FileBlock::State::DOWNLOADED) {
+                ++downloaded;
+                EXPECT_TRUE(fs::exists(block_path(base, hash, offset)))
+                        << hash.to_string() << " " << offset;
+            }
+        }
+    }
+    EXPECT_GT(downloaded, 0U);
+}
+
+TEST_F(BlockFileCacheTest, evict_io_remove_missing_file_is_ok) {
+    auto base = evict_io_cache_path("missing");
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+
+    BlockFileCache cache(base, normal_only_settings(10 * kBlockSize, 
kBlockSize));
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    // Never written: neither the file nor its directory exists.
+    FileCacheKey key;
+    key.hash = BlockFileCache::hash("evict_io_never_written");
+    key.offset = 0;
+    key.meta.type = FileCacheType::NORMAL;
+    key.meta.expiration_time = 0;
+    EXPECT_TRUE(cache._storage->remove(key).ok());
+
+    // Written, then the file disappears behind the cache's back before 
eviction.
+    auto hash = BlockFileCache::hash("evict_io_vanished");
+    insert_block(cache, hash, 0, 2 * kBlockSize);
+    ASSERT_TRUE(fs::remove(block_path(base, hash, 0)));
+    cache.remove_if_cached(hash);
+    EXPECT_FALSE(fs::exists(block_path(base, hash, kBlockSize)));
+    EXPECT_EQ(cache._pending_storage_removes.size(), 0U);
+    EXPECT_EQ(cache.get_used_cache_size(FileCacheType::NORMAL), 0U);
+
+    // Removing it again finds nothing and still succeeds.
+    key.hash = hash;
+    EXPECT_TRUE(cache._storage->remove(key).ok());
+    key.offset = kBlockSize;
+    EXPECT_TRUE(cache._storage->remove(key).ok());
+}
+
+TEST(PendingStorageRemovesTest, mark_claim_finish) {
+    PendingStorageRemoves pending;
+    FileCacheKey key;

Review Comment:
   [P3] Initialize the complete synthetic cache keys
   
   `FileCacheKey key;` leaves `KeyMeta::expiration_time` and `type` 
indeterminate (file_cache_common.h:149–159). The new `mark()` copies the whole 
key into a Removal, and `claim()` copies it again even though this test only 
checks the offset. That is not a valid initialized key. The same pattern occurs 
in evict_io_load_skips_block_pending_removal, 
evict_io_sync_remove_waits_for_competing_owner and 
wait_and_claim_waits_for_running_remove. Value-initialize these test keys (and 
set the intended type/TTL), so the tests do not depend on uninitialized 
metadata.



##########
be/src/io/cache/block_file_cache.cpp:
##########
@@ -2156,6 +2172,154 @@ void BlockFileCache::remove(FileBlockSPtr file_block, 
T& cache_lock, U& block_lo
     *_num_removed_blocks << 1;
 }
 
+void BlockFileCache::run_storage_remove(const UInt128Wrapper& hash, size_t 
offset,
+                                        bool wait_for_owner) const {
+    PendingStorageRemoves::Removal removal;
+    // wait_and_claim returns false once the entry is gone, i.e. after a 
competing owner finished
+    // the removal; claim returns false right away while that owner is still 
running.
+    auto claim = [&] {
+        return wait_for_owner ? _pending_storage_removes.wait_and_claim(hash, 
offset, &removal)
+                              : _pending_storage_removes.claim(hash, offset, 
&removal);
+    };
+    bool again = claim();
+    while (again) {
+        TEST_SYNC_POINT_CALLBACK("BlockFileCache::run_storage_remove", 
&removal.key);
+        remove_claimed_storage(removal);
+        again = _pending_storage_removes.finish(hash, offset) && claim();
+    }
+}
+
+void BlockFileCache::drain_pending_storage_remove(const UInt128Wrapper& hash, 
size_t offset) const {
+    PendingStorageRemoves::Removal removal;
+    while (_pending_storage_removes.wait_and_claim(hash, offset, &removal)) {
+        
TEST_SYNC_POINT_CALLBACK("BlockFileCache::drain_pending_storage_remove", 
&removal.key);
+        remove_claimed_storage(removal);
+        _pending_storage_removes.finish(hash, offset);
+    }
+}
+
+void BlockFileCache::remove_claimed_storage(const 
PendingStorageRemoves::Removal& removal) const {
+    int64_t duration_ns = 0;
+    Status st;
+    {
+        SCOPED_RAW_TIMER(&duration_ns);
+        st = _storage->remove(removal.key);

Review Comment:
   [P2] Make storage-removal completion exception-safe
   
   This call is now reached from the implicitly noexcept 
`DeferredStorageRemoveScope` destructor. Storage is not guaranteed to be 
nonthrowing: for example, `LocalFileSystem::delete_file_impl` calls the 
throwing `std::filesystem::is_regular_file(file)` overload after the 
status-returning existence check. A filesystem I/O error on that second stat 
can throw. Before this change, a synchronous eviction in 
`AsyncCacheWriteManager::_persist_task` could propagate to the worker’s 
exception boundary (async_cache_write_manager.cpp:309–323); now it terminates 
the process. Also, if a replacement downloader encounters an exception in 
`drain_pending_storage_remove`, it bypasses `finish()` and leaves the entry 
running permanently, so later owners wait indefinitely. Convert storage 
exceptions to the existing cache-removal error policy and make claim 
completion/notification failure-safe, including the destructor path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to