matanper commented on code in PR #69619:
URL: https://github.com/apache/doris/pull/69619#discussion_r4788661969


##########
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:
   The interleaving is real, but the outcome is not new with this PR. The 
removal deletes the block meta through `CacheBlockMetaStore::delete_key`, which 
only queues the delete, so on master a lazy load that reads the meta store 
shortly after an eviction can already cache a DOWNLOADED block whose file is 
gone. The guard narrows that window (it covers the time the file is still on 
disk and the removal is pending); it does not close it. Closing it needs the 
loader to be coordinated with the queued meta delete, which I would rather do 
separately than widen this PR. The reader already repairs such a block on 
NOT_FOUND (drops the hash and reads from remote). I documented the limit at the 
guard in ed385f2d0c6.



##########
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:
   Agreed on the mechanics: the admitted block is visible as soon as the lock 
is released, so another thread can become its downloader and write before the 
evictor has unlinked the victim. The cache size accounting is not affected (the 
victim was released under the lock), so this only matters on a disk that is 
physically out of blocks or inodes during that one unlink, and the result is a 
failed cache write: the block is not cached and the reader serves the data it 
already read from remote. Making the new block wait on the reclaim adds a wait 
to every cache write path for that case, so I left the behavior as is and 
documented it at the deferred removal in ed385f2d0c6. Happy to revisit if you 
think the full-disk case needs strict parity.



##########
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:
   Fixed in ed385f2d0c6. `remove_claimed_storage` now catches anything 
`_storage->remove()` throws and handles it as a failed removal (logged, latency 
recorded), so nothing escapes `~DeferredStorageRemoveScope` and the claim is 
always finished in both `run_storage_remove` and 
`drain_pending_storage_remove`. New test 
`evict_io_throwing_storage_remove_is_contained` covers the lock scope path and 
the drain path.



##########
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:
   Fixed in ed385f2d0c6. The manual claim is released by a guard on every exit, 
before the future is destroyed, and the polling loop uses `try_lock` with a 
deadline, so a remover that waited under the cache lock fails the assertion 
instead of blocking the loop. The recreated-block test now bounds its wait for 
the sync point and releases the stalled removal on every exit.



##########
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:
   Fixed in ed385f2d0c6. The test counts append/finalize failures of admitted 
(EMPTY) blocks and asserts there are none, asserts that writes actually 
happened, and checks that every successful read returns the written payload.



-- 
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