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


##########
be/src/io/cache/block_file_cache.cpp:
##########
@@ -1228,6 +1228,10 @@ FileBlocks BlockFileCache::split_range_into_cells(const 
UInt128Wrapper& hash,
         current_size = std::min(remaining_size, _max_file_block_size);
         remaining_size -= current_size;
         auto block_state = state;
+        if (block_state != FileBlock::State::SKIP_CACHE &&
+            has_pending_async_remove(hash, current_pos)) {

Review Comment:
   [P2] Keep the fence drainable at low positive GC rates. With 
`file_cache_remove_block_qps_limit=5` and the default 100 ms interval, 
`run_background_gc()` calculates a batch of zero on every wakeup. After an 
async clear, the removed offsets stay in `_pending_async_removes` and all later 
refills return `SKIP_CACHE` until the configuration changes or the cache 
restarts. The rounding existed before, but the new fence turns it into a 
persistent cache bypass. Carry fractional budget across ticks so positive rates 
still make progress.



##########
be/test/io/cache/block_file_cache_test.cpp:
##########
@@ -11493,4 +11493,891 @@ TEST_F(BlockFileCacheTest,
     EXPECT_FALSE(read_stats.from_peer_cache);
 }
 
+TEST_F(BlockFileCacheTest, remove_prevents_resurrection_during_async_open) {
+    // Reopen a persistent cache without waiting for async restore to finish:
+    // 1. Lazy restore must NOT resurrect a removed DOWNLOADED block as a 
zombie DOWNLOADED cell
+    //    while its async disk unlink is still pending (so non-overwrite seed 
retry rebuilds it).
+    // 2. The background DB loader snapshot taken before removal must NOT 
resurrect deleted blocks
+    //    or clobber blocks re-seeded during async open, while untouched 
persisted blocks still
+    //    restore cleanly.
+    std::string my_cache_path = cache_base_path + "_async_open_resurrection";
+    if (fs::exists(my_cache_path)) {
+        fs::remove_all(my_cache_path);
+    }
+    fs::create_directories(my_cache_path);
+    Defer remove_dir {[&] {
+        if (fs::exists(my_cache_path)) {
+            fs::remove_all(my_cache_path);
+        }
+    }};
+
+    constexpr size_t block_size = 64;
+    constexpr int64_t tablet_id = 1001;
+    io::FileCacheSettings settings;
+    settings.query_queue_size = 4096;
+    settings.query_queue_elements = 64;
+    settings.index_queue_size = 4096;
+    settings.index_queue_elements = 64;
+    settings.disposable_queue_size = 4096;
+    settings.disposable_queue_elements = 64;
+    settings.capacity = 4096;
+    settings.max_file_block_size = block_size;
+    settings.max_query_cache_size = 4096;
+
+    int64_t origin_interval = config::file_cache_background_gc_interval_ms;
+    int64_t origin_qps = config::file_cache_remove_block_qps_limit;
+    int64_t origin_lru_dump = 
config::file_cache_background_lru_dump_tail_record_num;
+    config::file_cache_background_gc_interval_ms = 20;
+    config::file_cache_remove_block_qps_limit = 1000;
+    config::file_cache_background_lru_dump_tail_record_num = 0;
+    Defer restore_cfg {[&] {
+        config::file_cache_background_gc_interval_ms = origin_interval;
+        config::file_cache_remove_block_qps_limit = origin_qps;
+        config::file_cache_background_lru_dump_tail_record_num = 
origin_lru_dump;
+    }};
+
+    const auto hash_p = io::BlockFileCache::hash("async_open_pinned_retire");
+    const auto hash_reseed = io::BlockFileCache::hash("async_open_reseeded");
+    const auto hash_healthy = io::BlockFileCache::hash("async_open_healthy");
+
+    // Step 1: Persist three NORMAL blocks in an initial cache instance and 
shut it down cleanly.
+    {
+        io::BlockFileCache initial_cache(my_cache_path, settings);
+        ASSERT_TRUE(initial_cache.initialize());
+        wait_until_cache_ready(initial_cache);
+
+        auto write_block = [&](const io::UInt128Wrapper& h, char fill) {
+            io::ReadStatistics stats;
+            io::CacheContext ctx;
+            ctx.stats = &stats;
+            ctx.cache_type = io::FileCacheType::NORMAL;
+            ctx.tablet_id = tablet_id;
+            auto holder = initial_cache.get_or_set(h, 0, block_size, ctx);
+            ASSERT_EQ(holder.file_blocks.size(), 1);
+            auto& fb = holder.file_blocks.front();
+            ASSERT_EQ(fb->get_or_set_downloader(), 
io::FileBlock::get_caller_id());
+            std::string payload(block_size, fill);
+            ASSERT_TRUE(fb->append(Slice(payload.data(), 
payload.size())).ok());
+            ASSERT_TRUE(fb->finalize().ok());
+        };
+        write_block(hash_p, 'O');
+        write_block(hash_reseed, 'O');
+        write_block(hash_healthy, 'H');
+    }
+
+    // Step 2: Reopen the same persistent directory with background DB restore 
paused AFTER taking
+    // its RocksDB snapshot (so !get_async_open_success() and the snapshot 
already sees all 3 keys).
+    std::mutex gate_mtx;
+    std::condition_variable gate_cv;
+    bool loader_paused = false;
+    bool loader_release = false;
+    bool gc_paused = false;
+    bool gc_release = false;
+
+    auto sp = SyncPoint::get_instance();
+    SyncPoint::CallbackGuard loader_guard;
+    SyncPoint::CallbackGuard gc_guard;
+    sp->set_call_back(
+            
"FSFileCacheStorage::load_cache_info_into_memory_from_db:after_snapshot",
+            [&](auto&&) {
+                std::unique_lock lk(gate_mtx);
+                loader_paused = true;
+                gate_cv.notify_all();
+                gate_cv.wait(lk, [&]() { return loader_release; });
+            },
+            &loader_guard);
+    sp->set_call_back(
+            "FSFileCacheStorage::remove",
+            [&](auto&& args) {
+                const auto* key = try_any_cast<const 
io::FileCacheKey*>(args[0]);
+                if (key == nullptr || key->hash != hash_p) {
+                    return;
+                }
+                std::unique_lock lk(gate_mtx);
+                gc_paused = true;
+                gate_cv.notify_all();
+                gate_cv.wait(lk, [&]() { return gc_release; });
+            },
+            &gc_guard);
+    sp->enable_processing();
+
+    std::unique_ptr<io::BlockFileCache> cache;
+    Defer cleanup {[&] {
+        {
+            std::lock_guard lk(gate_mtx);
+            loader_release = true;
+            gc_release = true;
+        }
+        gate_cv.notify_all();
+        cache.reset();
+        sp->disable_processing();
+        sp->clear_all_call_backs();
+    }};
+
+    cache = std::make_unique<io::BlockFileCache>(my_cache_path, settings);
+    ASSERT_TRUE(cache->initialize());
+    // Do NOT call wait_until_cache_ready(*cache); wait only until the 
snapshot gate is reached.
+    {
+        std::unique_lock lk(gate_mtx);
+        ASSERT_TRUE(gate_cv.wait_for(lk, std::chrono::seconds(5), [&]() { 
return loader_paused; }));
+    }
+    ASSERT_FALSE(cache->get_async_open_success());
+    ASSERT_TRUE(cache->dump_structure(hash_p).empty());
+    ASSERT_TRUE(cache->dump_structure(hash_reseed).empty());
+    ASSERT_TRUE(cache->dump_structure(hash_healthy).empty());
+
+    // Step 3: Plain peer read lazily restores hash_p and holds a plain 
FileBlockSPtr pin.
+    io::FileBlockSPtr peer_pin;
+    {
+        io::ReadStatistics stats;
+        io::CacheContext ctx;
+        ctx.stats = &stats;
+        ctx.cache_type = io::FileCacheType::NORMAL;
+        ctx.tablet_id = tablet_id;
+        auto holder = cache->get_or_set(hash_p, 0, block_size, ctx);
+        ASSERT_EQ(holder.file_blocks.size(), 1);
+        peer_pin = holder.file_blocks.front();
+        ASSERT_EQ(peer_pin->state(), io::FileBlock::State::DOWNLOADED);
+        std::string buf(block_size, '\0');
+        ASSERT_TRUE(peer_pin->read(Slice(buf.data(), buf.size()), 0).ok());
+        ASSERT_EQ(buf, std::string(block_size, 'O'));
+    }
+
+    // Default async clear marks the pinned block deleting until its pin is 
released.
+    cache->clear_file_cache_async();
+    EXPECT_TRUE(cache->is_block_deleting(peer_pin));
+
+    // Peer releases its pin; GC retires hash_p and pauses BEFORE unlinking 
disk file & metadata.
+    peer_pin.reset();
+    {
+        std::unique_lock lk(gate_mtx);
+        ASSERT_TRUE(gate_cv.wait_for(lk, std::chrono::seconds(5), [&]() { 
return gc_paused; }));
+    }
+    ASSERT_FALSE(cache->get_async_open_success());
+    EXPECT_TRUE(cache->dump_structure(hash_p).empty());
+
+    // Step 4: Lookup/admission runs while !_async_open_done and the older 
queued unlink is still
+    // pending. Lazy restore MUST NOT resurrect hash_p as DOWNLOADED, and 
admission MUST degrade
+    // to SKIP_CACHE so a refill cannot finalize to the same v3 path before 
the old unlink runs.
+    const int64_t async_remove_count_before = 
cache->_storage_async_remove_latency_us->count();
+    EXPECT_TRUE(cache->has_pending_async_remove(hash_p, 0));
+    {
+        io::ReadStatistics stats;
+        io::CacheContext ctx;
+        ctx.stats = &stats;
+        ctx.cache_type = io::FileCacheType::NORMAL;
+        ctx.tablet_id = tablet_id;
+        auto holder = cache->get_or_set(hash_p, 0, block_size, ctx);
+        ASSERT_EQ(holder.file_blocks.size(), 1);
+        auto& fb = holder.file_blocks.front();
+        EXPECT_EQ(fb->state(), io::FileBlock::State::SKIP_CACHE);
+    }
+    EXPECT_TRUE(cache->dump_structure(hash_p).empty());
+
+    // Release old unlink and wait until background GC completes 
_storage->remove(key).
+    {
+        std::lock_guard lk(gate_mtx);
+        gc_release = true;
+    }
+    gate_cv.notify_all();
+    const auto gc_deadline = std::chrono::steady_clock::now() + 
std::chrono::seconds(5);
+    while (cache->_storage_async_remove_latency_us->count() <= 
async_remove_count_before &&
+           std::chrono::steady_clock::now() < gc_deadline) {
+        std::this_thread::sleep_for(std::chrono::milliseconds(10));
+    }
+    ASSERT_GT(cache->_storage_async_remove_latency_us->count(), 
async_remove_count_before);
+    EXPECT_FALSE(cache->has_pending_async_remove(hash_p, 0));
+    EXPECT_TRUE(cache->dump_structure(hash_p).empty());
+
+    // Step 5: While STILL !_async_open_done, lazy-load, synchronously remove, 
and immediately
+    // re-seed hash_reseed with new content 'R' so we also verify the stale DB 
snapshot will not
+    // overwrite or resurrect it.
+    {
+        io::ReadStatistics stats;
+        io::CacheContext ctx;
+        ctx.stats = &stats;
+        ctx.cache_type = io::FileCacheType::NORMAL;
+        ctx.tablet_id = tablet_id;
+        {
+            auto old_holder = cache->get_or_set(hash_reseed, 0, block_size, 
ctx);
+            ASSERT_EQ(old_holder.file_blocks.size(), 1);
+            ASSERT_EQ(old_holder.file_blocks.front()->state(), 
io::FileBlock::State::DOWNLOADED);
+        }
+        cache->remove_if_cached(hash_reseed);
+        ASSERT_TRUE(cache->dump_structure(hash_reseed).empty());
+
+        auto new_holder = cache->get_or_set(hash_reseed, 0, block_size, ctx);
+        ASSERT_EQ(new_holder.file_blocks.size(), 1);
+        auto& fb = new_holder.file_blocks.front();
+        ASSERT_EQ(fb->state(), io::FileBlock::State::EMPTY);
+        ASSERT_EQ(fb->get_or_set_downloader(), io::FileBlock::get_caller_id());
+        std::string reseed_payload(block_size, 'R');
+        ASSERT_TRUE(fb->append(Slice(reseed_payload.data(), 
reseed_payload.size())).ok());
+        ASSERT_TRUE(fb->finalize().ok());
+    }
+
+    // Verify tombstones were recorded during IN_PROGRESS before releasing the 
loader.
+    const size_t empty_tombstone_buckets =
+            std::unordered_set<io::AccessKeyAndOffset, 
io::KeyAndOffsetHash>().bucket_count();
+    {
+        std::lock_guard lock(cache->_mutex);
+        ASSERT_GE(cache->_removed_during_async_open.size(), 2);
+    }
+
+    // Step 6: Release the background DB loader whose snapshot predates both 
removals and wait for
+    // async open to finish.
+    {
+        std::lock_guard lk(gate_mtx);
+        loader_release = true;
+    }
+    gate_cv.notify_all();
+    wait_until_cache_ready(*cache);
+
+    {
+        std::lock_guard lock(cache->_mutex);
+        EXPECT_TRUE(cache->_removed_during_async_open.empty());
+        EXPECT_LE(cache->_removed_during_async_open.bucket_count(), 
empty_tombstone_buckets);
+    }
+
+    // Pre-unlink snapshot MUST NOT have resurrected hash_p as a zombie 
DOWNLOADED cell.
+    EXPECT_TRUE(cache->dump_structure(hash_p).empty());
+
+    // Non-overwrite seed retry now allocates EMPTY, writes 'N', and reads 
back 'N' from disk.
+    {
+        io::ReadStatistics stats;
+        io::CacheContext ctx;
+        ctx.stats = &stats;
+        ctx.cache_type = io::FileCacheType::NORMAL;
+        ctx.tablet_id = tablet_id;
+        auto holder = cache->get_or_set(hash_p, 0, block_size, ctx);
+        ASSERT_EQ(holder.file_blocks.size(), 1);
+        auto& fb = holder.file_blocks.front();
+        ASSERT_EQ(fb->state(), io::FileBlock::State::EMPTY);
+        ASSERT_EQ(fb->get_or_set_downloader(), io::FileBlock::get_caller_id());
+        std::string new_payload(block_size, 'N');
+        ASSERT_TRUE(fb->append(Slice(new_payload.data(), 
new_payload.size())).ok());
+        ASSERT_TRUE(fb->finalize().ok());
+    }
+    auto verify_read = [&](const io::UInt128Wrapper& h, char expected) {
+        io::ReadStatistics stats;
+        io::CacheContext ctx;
+        ctx.stats = &stats;
+        ctx.cache_type = io::FileCacheType::NORMAL;
+        ctx.tablet_id = tablet_id;
+        auto holder = cache->get_or_set(h, 0, block_size, ctx);
+        ASSERT_EQ(holder.file_blocks.size(), 1);
+        ASSERT_EQ(holder.file_blocks.front()->state(), 
io::FileBlock::State::DOWNLOADED);
+        std::string buf(block_size, '\0');
+        ASSERT_TRUE(holder.file_blocks.front()->read(Slice(buf.data(), 
buf.size()), 0).ok());
+        EXPECT_EQ(buf, std::string(block_size, expected));
+    };
+    verify_read(hash_p, 'N');
+    verify_read(hash_reseed, 'R');
+    verify_read(hash_healthy, 'H');
+
+    // Step 7: Also verify after async open SUCCEEDED that an in-flight async 
unlink still fences
+    // refill via SKIP_CACHE until GC completes, after which refill succeeds 
and survives.
+    {
+        std::lock_guard lk(gate_mtx);
+        gc_paused = false;
+        gc_release = false;
+    }
+    const int64_t post_open_remove_count = 
cache->_storage_async_remove_latency_us->count();
+    cache->remove_if_cached_async(hash_p);
+    {
+        std::unique_lock lk(gate_mtx);
+        ASSERT_TRUE(gate_cv.wait_for(lk, std::chrono::seconds(5), [&]() { 
return gc_paused; }));
+    }
+    EXPECT_TRUE(cache->has_pending_async_remove(hash_p, 0));
+    {
+        io::ReadStatistics stats;
+        io::CacheContext ctx;
+        ctx.stats = &stats;
+        ctx.cache_type = io::FileCacheType::NORMAL;
+        ctx.tablet_id = tablet_id;
+        auto holder = cache->get_or_set(hash_p, 0, block_size, ctx);
+        ASSERT_EQ(holder.file_blocks.size(), 1);
+        EXPECT_EQ(holder.file_blocks.front()->state(), 
io::FileBlock::State::SKIP_CACHE);
+    }
+    {
+        std::lock_guard lk(gate_mtx);
+        gc_release = true;
+    }
+    gate_cv.notify_all();
+    const auto post_open_deadline = std::chrono::steady_clock::now() + 
std::chrono::seconds(5);
+    while (cache->_storage_async_remove_latency_us->count() <= 
post_open_remove_count &&
+           std::chrono::steady_clock::now() < post_open_deadline) {
+        std::this_thread::sleep_for(std::chrono::milliseconds(10));
+    }
+    ASSERT_GT(cache->_storage_async_remove_latency_us->count(), 
post_open_remove_count);
+    EXPECT_FALSE(cache->has_pending_async_remove(hash_p, 0));
+    {
+        io::ReadStatistics stats;
+        io::CacheContext ctx;
+        ctx.stats = &stats;
+        ctx.cache_type = io::FileCacheType::NORMAL;
+        ctx.tablet_id = tablet_id;
+        auto holder = cache->get_or_set(hash_p, 0, block_size, ctx);
+        ASSERT_EQ(holder.file_blocks.size(), 1);
+        auto& fb = holder.file_blocks.front();
+        ASSERT_EQ(fb->state(), io::FileBlock::State::EMPTY);
+        ASSERT_EQ(fb->get_or_set_downloader(), io::FileBlock::get_caller_id());
+        std::string payload(block_size, 'P');
+        ASSERT_TRUE(fb->append(Slice(payload.data(), payload.size())).ok());
+        ASSERT_TRUE(fb->finalize().ok());
+    }
+    verify_read(hash_p, 'P');
+}
+
+TEST_F(BlockFileCacheTest, 
async_open_failure_closes_restore_epoch_and_bounds_tombstones) {
+    // When the background async-open loader terminates with an IO error (e.g. 
unreadable version
+    // file with ignore_file_cache_dir_upgrade_failure=false), the cache must 
transition to a
+    // terminal FAILED state that:
+    // 1. Keeps get_async_open_success() == false and sets 
is_async_open_failed() == true.
+    // 2. Releases _removed_during_async_open and stops collecting tombstones 
on subsequent
+    //    write/finalize/remove churn (preventing unbounded memory growth).
+    // 3. Preserves lazy recovery for intact on-disk blocks (so they remain 
readable and evictable
+    //    under disk pressure) while preventing resurrection of removed blocks 
via pending-remove
+    //    fencing and on-disk file existence checks.
+    std::string my_cache_path = cache_base_path + "_async_open_failure";
+    if (fs::exists(my_cache_path)) {
+        fs::remove_all(my_cache_path);
+    }
+    fs::create_directories(my_cache_path);
+    Defer remove_dir {[&] {
+        if (fs::exists(my_cache_path)) {
+            fs::remove_all(my_cache_path);
+        }
+    }};
+
+    constexpr size_t block_size = 64;
+    constexpr int64_t tablet_id = 1001;
+    io::FileCacheSettings settings;
+    settings.query_queue_size = 4096;
+    settings.query_queue_elements = 64;
+    settings.index_queue_size = 4096;
+    settings.index_queue_elements = 64;
+    settings.disposable_queue_size = 4096;
+    settings.disposable_queue_elements = 64;
+    settings.capacity = 4096;
+    settings.max_file_block_size = block_size;
+    settings.max_query_cache_size = 4096;
+
+    int64_t origin_interval = config::file_cache_background_gc_interval_ms;
+    int64_t origin_qps = config::file_cache_remove_block_qps_limit;
+    int64_t origin_lru_dump = 
config::file_cache_background_lru_dump_tail_record_num;
+    bool origin_ignore_upgrade = config::ignore_file_cache_dir_upgrade_failure;
+    bool origin_evict_in_advance = config::enable_evict_file_cache_in_advance;
+    int32_t origin_enter_limit = 
config::file_cache_enter_disk_resource_limit_mode_percent;
+    int32_t origin_exit_limit = 
config::file_cache_exit_disk_resource_limit_mode_percent;
+    config::file_cache_background_gc_interval_ms = 20;
+    config::file_cache_remove_block_qps_limit = 1000;
+    config::file_cache_background_lru_dump_tail_record_num = 0;
+    config::ignore_file_cache_dir_upgrade_failure = false;
+    config::enable_evict_file_cache_in_advance = false;
+    config::file_cache_enter_disk_resource_limit_mode_percent = 85;
+    config::file_cache_exit_disk_resource_limit_mode_percent = 80;
+    Defer restore_cfg {[&] {
+        config::file_cache_background_gc_interval_ms = origin_interval;
+        config::file_cache_remove_block_qps_limit = origin_qps;
+        config::file_cache_background_lru_dump_tail_record_num = 
origin_lru_dump;
+        config::ignore_file_cache_dir_upgrade_failure = origin_ignore_upgrade;
+        config::enable_evict_file_cache_in_advance = origin_evict_in_advance;
+        config::file_cache_enter_disk_resource_limit_mode_percent = 
origin_enter_limit;
+        config::file_cache_exit_disk_resource_limit_mode_percent = 
origin_exit_limit;
+    }};
+
+    const auto hash_persisted = 
io::BlockFileCache::hash("async_open_fail_persisted");
+    const auto hash_removed_pre_fail = 
io::BlockFileCache::hash("async_open_fail_removed_pre");
+    const auto hash_eisdir_persisted = 
io::BlockFileCache::hash("async_open_fail_eisdir_persisted");
+    const size_t empty_tombstone_buckets =
+            std::unordered_set<io::AccessKeyAndOffset, 
io::KeyAndOffsetHash>().bucket_count();
+
+    // Step 1: Persist valid NORMAL blocks in an initial cache instance and 
shut it down cleanly.
+    {
+        io::BlockFileCache initial_cache(my_cache_path, settings);
+        ASSERT_TRUE(initial_cache.initialize());
+        wait_until_cache_ready(initial_cache);
+
+        auto seed = [&](const io::UInt128Wrapper& h, char fill) {
+            io::ReadStatistics stats;
+            io::CacheContext ctx;
+            ctx.stats = &stats;
+            ctx.cache_type = io::FileCacheType::NORMAL;
+            ctx.tablet_id = tablet_id;
+            auto holder = initial_cache.get_or_set(h, 0, block_size, ctx);
+            ASSERT_EQ(holder.file_blocks.size(), 1);
+            auto& fb = holder.file_blocks.front();
+            ASSERT_EQ(fb->get_or_set_downloader(), 
io::FileBlock::get_caller_id());
+            std::string payload(block_size, fill);
+            ASSERT_TRUE(fb->append(Slice(payload.data(), 
payload.size())).ok());
+            ASSERT_TRUE(fb->finalize().ok());
+        };
+        seed(hash_persisted, 'O');
+        seed(hash_removed_pre_fail, 'X');
+        seed(hash_eisdir_persisted, 'E');
+    }
+
+    // Step 2: Pause the real background loader in IN_PROGRESS, accumulate 
tombstones (and grow
+    // bucket storage), then fail the loader so FAILED must release the 
non-empty tombstone set.
+    {
+        std::mutex gate_mtx;
+        std::condition_variable gate_cv;
+        bool loader_paused = false;
+        bool loader_release = false;
+        bool monitor_paused = false;
+        bool monitor_release = false;
+        std::atomic<int> injected_disk_usage_pct {10};
+
+        auto* sp = SyncPoint::get_instance();
+        SyncPoint::CallbackGuard loader_guard;
+        SyncPoint::CallbackGuard monitor_guard;
+        SyncPoint::CallbackGuard disk_usage_guard;
+        sp->set_call_back(
+                "BlockFileCache::TmpFile1",
+                [&](auto&&) {
+                    {
+                        std::unique_lock lk(gate_mtx);
+                        loader_paused = true;
+                        gate_cv.notify_all();
+                        gate_cv.wait(lk, [&]() { return loader_release; });
+                    }
+                    throw doris::Exception(Status::IOError("injected loader 
failure"));
+                },
+                &loader_guard);
+        sp->set_call_back(
+                "BlockFileCache::set_sleep_time",
+                [&](auto&&) {
+                    std::unique_lock lk(gate_mtx);
+                    monitor_paused = true;
+                    gate_cv.notify_all();
+                    gate_cv.wait(lk, [&]() { return monitor_release; });
+                },
+                &monitor_guard);
+        sp->set_call_back(
+                "BlockFileCache::disk_used_percentage:1",
+                [&](auto&& values) {
+                    auto* percent = try_any_cast<std::pair<int, 
int>*>(values.back());
+                    const int pct = 
injected_disk_usage_pct.load(std::memory_order_acquire);
+                    *percent = {pct, pct};
+                },
+                &disk_usage_guard);
+        sp->enable_processing();
+
+        std::unique_ptr<io::BlockFileCache> cache;
+        Defer cleanup {[&] {
+            {
+                std::lock_guard lk(gate_mtx);
+                loader_release = true;
+                monitor_release = true;
+            }
+            gate_cv.notify_all();
+            cache.reset();
+            sp->disable_processing();
+            sp->clear_all_call_backs();
+        }};
+
+        cache = std::make_unique<io::BlockFileCache>(my_cache_path, settings);
+        ASSERT_TRUE(cache->initialize());
+        {
+            std::unique_lock lk(gate_mtx);
+            ASSERT_TRUE(gate_cv.wait_for(lk, std::chrono::seconds(5),
+                                         [&]() { return loader_paused && 
monitor_paused; }));
+        }
+        ASSERT_FALSE(cache->get_async_open_success());
+        ASSERT_FALSE(cache->is_async_open_failed());
+
+        // Lazily load and remove a pre-existing persisted block while 
IN_PROGRESS, and accumulate
+        // tombstones to grow hash-table bucket storage before FAILED releases 
them.
+        {
+            io::ReadStatistics stats;
+            io::CacheContext ctx;
+            ctx.stats = &stats;
+            ctx.cache_type = io::FileCacheType::NORMAL;
+            ctx.tablet_id = tablet_id;
+            auto holder = cache->get_or_set(hash_removed_pre_fail, 0, 
block_size, ctx);
+            ASSERT_EQ(holder.file_blocks.size(), 1);
+            ASSERT_EQ(holder.file_blocks.front()->state(), 
io::FileBlock::State::DOWNLOADED);
+        }
+        cache->remove_if_cached(hash_removed_pre_fail);
+        ASSERT_TRUE(cache->dump_structure(hash_removed_pre_fail).empty());
+
+        for (int i = 0; i < 16; ++i) {
+            const auto h =
+                    io::BlockFileCache::hash("async_open_pre_fail_tombstone_" 
+ std::to_string(i));
+            io::ReadStatistics stats;
+            io::CacheContext ctx;
+            ctx.stats = &stats;
+            ctx.cache_type = io::FileCacheType::NORMAL;
+            ctx.tablet_id = tablet_id;
+            {
+                auto holder = cache->get_or_set(h, 0, block_size, ctx);
+                ASSERT_EQ(holder.file_blocks.size(), 1);
+                auto& fb = holder.file_blocks.front();
+                ASSERT_EQ(fb->get_or_set_downloader(), 
io::FileBlock::get_caller_id());
+                std::string payload(block_size, static_cast<char>('a' + (i % 
26)));
+                ASSERT_TRUE(fb->append(Slice(payload.data(), 
payload.size())).ok());
+                ASSERT_TRUE(fb->finalize().ok());
+            }
+            cache->remove_if_cached(h);
+        }
+        {
+            std::lock_guard lock(cache->_mutex);
+            ASSERT_EQ(cache->_removed_during_async_open.size(), 17);
+            ASSERT_GT(cache->_removed_during_async_open.bucket_count(), 
empty_tombstone_buckets);
+        }
+
+        // Release loader to throw and transition to FAILED.
+        {
+            std::lock_guard lk(gate_mtx);
+            loader_release = true;
+        }
+        gate_cv.notify_all();
+        const auto deadline = std::chrono::steady_clock::now() + 
std::chrono::seconds(5);
+        while (!cache->is_async_open_failed() && 
std::chrono::steady_clock::now() < deadline) {
+            std::this_thread::sleep_for(std::chrono::milliseconds(10));
+        }
+        ASSERT_TRUE(cache->is_async_open_failed());
+        EXPECT_FALSE(cache->get_async_open_success());
+
+        // Pre-existing tombstones AND their hash-table buckets must be 
released on FAILED.
+        {
+            std::lock_guard lock(cache->_mutex);
+            EXPECT_TRUE(cache->_removed_during_async_open.empty());
+            EXPECT_LE(cache->_removed_during_async_open.bucket_count(), 
empty_tombstone_buckets);
+        }
+
+        // Removed block MUST NOT be resurrected after FAILED even though 
tombstones were cleared.
+        {
+            io::ReadStatistics stats;
+            io::CacheContext ctx;
+            ctx.stats = &stats;
+            ctx.cache_type = io::FileCacheType::NORMAL;
+            ctx.tablet_id = tablet_id;
+            auto holder = cache->get_or_set(hash_removed_pre_fail, 0, 
block_size, ctx);

Review Comment:
   [P3] Keep the deleted block’s RocksDB row visible for this retry. The 
metadata worker can apply DELETE during the intervening writes and loader 
transition, so this check can pass even if the new filesystem guard is removed. 
Pause the worker at `before_dequeue`, verify that unlink succeeded and the old 
row is still present, then exercise the FAILED-state lookup before releasing 
the worker.



##########
be/src/io/cache/fs_file_cache_storage.cpp:
##########
@@ -1179,6 +1193,33 @@ void 
FSFileCacheStorage::load_file_blocks_directly_unlocked(
                          << ", value_error=" << 
iterator->get_last_value_error().to_string();
             continue;
         }
+        if (mgr->is_removed_during_async_open(hash, meta_key.offset, 
cache_lock) ||
+            mgr->has_pending_async_remove(hash, meta_key.offset)) {
+            continue;
+        }
+        if (mgr->is_async_open_failed()) {
+            // After bulk restore fails, tombstones are cleared to stay 
bounded while lazy recovery
+            // stays available for intact persisted blocks. 
FSFileCacheStorage::remove() unlinks
+            // the backing file synchronously before enqueuing the async 
RocksDB delete, so verify
+            // the file still exists on disk before restoring.
+            bool block_exists = false;
+            const std::string v3_dir = get_path_in_local_cache_v3(hash);
+            const std::string v3_file = get_path_in_local_cache_v3(v3_dir, 
meta_key.offset);
+            if (!fs->exists(v3_file, &block_exists).ok()) {
+                block_exists = false;
+            }
+            if (!block_exists) {
+                const std::string v2_dir = get_path_in_local_cache_v2(hash, 
block_meta.ttl);
+                const std::string v2_file =
+                        get_path_in_local_cache_v2(v2_dir, meta_key.offset, 
block_meta.type);

Review Comment:
   [P2] Keep readable legacy v2 blocks recoverable after a failed open. With a 
persisted TTL record and a legacy `offset_ttl` file, this checks the bare 
`offset` path and skips the record, even though `get_or_open_file_reader()` 
explicitly tries `offset_ttl`. Legacy scans and metadata-only TTL updates can 
leave that file and record together across an upgrade. These blocks now miss 
and stay out of the eviction queues after a version-file failure. Use the same 
legacy path resolution for recovery, reads, and removal so an alternate 
filename is neither ignored nor accidentally restored after eviction.



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