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

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


The following commit(s) were added to refs/heads/master by this push:
     new b3c45419178 [improvement](file cache) Bound eviction scans under the 
cache lock and rotate in-use entries (#69587)
b3c45419178 is described below

commit b3c45419178eb2eb970e66419f8fc8b121200a93
Author: matanper <[email protected]>
AuthorDate: Thu Dec 3 15:39:31 2026 +0200

    [improvement](file cache) Bound eviction scans under the cache lock and 
rotate in-use entries (#69587)
    
    ### What problem does this PR solve?
    
    Issue Number: close #68892
    
    Related PR: None
    
    Problem Summary:
    
    An eviction scan walks an LRU queue from the head while holding the file
    cache lock
    (`find_evict_candidates`, the loop in
    `try_reserve_from_other_queue_by_time_interval`, and the
    query-limit walk in `try_reserve`). It skips entries that are not
    releasable (held or
    downloading) and stops only when enough space is freed or the queue
    ends. Nothing bounds how
    many entries a reservation examines, and the skipped entries stay at the
    head, so every later
    reservation walks over them again.
    
    With a full cache and many held blocks (concurrent reads plus
    write-through from S3 file
    writers, one reservation per block), lock hold time grows with the
    number of held entries at
    the queue head, and every cache operation queues behind it. In
    production on 4.1.4 (cloud mode)
    we measured cache lock waits averaging hundreds of ms with p99 in
    seconds; S3 upload threads that
    copy into the cache backed up on the lock and Stream Loads stalled. With
    an earlier version of
    this change (bound and rotation in the own-queue scan only), on the same
    load, lock waits dropped
    to about 80 us on average.
---
 be/benchmark/benchmark_file_cache_evict_scan.hpp   | 155 ++++++
 be/benchmark/benchmark_main.cpp                    |   1 +
 be/src/common/config.cpp                           |   1 +
 be/src/common/config.h                             |   8 +
 be/src/io/cache/block_file_cache.cpp               | 107 ++++-
 be/src/io/cache/block_file_cache.h                 |  33 +-
 .../io/cache/block_file_cache_evict_scan_test.cpp  | 525 +++++++++++++++++++++
 7 files changed, 814 insertions(+), 16 deletions(-)

diff --git a/be/benchmark/benchmark_file_cache_evict_scan.hpp 
b/be/benchmark/benchmark_file_cache_evict_scan.hpp
new file mode 100644
index 00000000000..96018193a87
--- /dev/null
+++ b/be/benchmark/benchmark_file_cache_evict_scan.hpp
@@ -0,0 +1,155 @@
+// 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.
+
+#pragma once
+
+#include <benchmark/benchmark.h>
+
+#include <chrono>
+#include <memory>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "common/config.h"
+#include "io/cache/block_file_cache.h"
+#include "io/cache/file_cache_common.h"
+
+namespace doris {
+
+// One reservation into a full file cache whose LRU head is held (in use), as 
when concurrent
+// reads and write-through keep many blocks pinned. Each iteration inserts a 
new block through
+// get_or_set, which evicts one released block under the cache lock, downloads 
it and releases
+// it, so the queue keeps its shape: `held` pinned blocks plus 
kEvictFileCacheReleased released
+// ones.
+//
+// In-use entries a scan skips are always moved to the end of their queue.
+// Arg 0: number of held blocks. Arg 1: file_cache_evict_max_scan_entries (0 = 
unbounded,
+// 4096 = the default).
+// Counters per reservation: scanned (LRU entries examined under the lock), 
truncated (scans
+// that hit the bound) and skip_cache (reservations that failed, so the block 
was not cached).
+
+constexpr size_t kEvictFileCacheBlock = 1024;
+constexpr size_t kEvictFileCacheReleased = 1024;
+
+class EvictFileCacheBench {
+public:
+    EvictFileCacheBench(size_t held, int64_t max_scan)
+            : _max_scan(config::file_cache_evict_max_scan_entries),
+              _in_advance(config::enable_evict_file_cache_in_advance),
+              
_async_touch(config::enable_file_cache_async_touch_on_get_or_set) {
+        config::file_cache_evict_max_scan_entries = max_scan;
+        config::enable_evict_file_cache_in_advance = false;
+        config::enable_file_cache_async_touch_on_get_or_set = false;
+
+        const size_t blocks = held + kEvictFileCacheReleased;
+        io::FileCacheSettings settings;
+        settings.storage = "memory";
+        settings.capacity = blocks * kEvictFileCacheBlock;
+        settings.max_file_block_size = kEvictFileCacheBlock;
+        settings.max_query_cache_size = 0;
+        settings.query_queue_size = settings.capacity;
+        settings.query_queue_elements = blocks + 1;
+        settings.index_queue_size = 0;
+        settings.index_queue_elements = 0;
+        settings.disposable_queue_size = 0;
+        settings.disposable_queue_elements = 0;
+        settings.ttl_queue_size = 0;
+        settings.ttl_queue_elements = 0;
+        _cache = std::make_unique<io::BlockFileCache>("memory", settings);
+        CHECK(_cache->initialize().ok());
+        while (!_cache->get_async_open_success()) {
+            std::this_thread::sleep_for(std::chrono::milliseconds(1));
+        }
+
+        // Held blocks first, so they sit at the LRU head.
+        for (size_t i = 0; i < held; ++i) {
+            _held.push_back(insert(io::BlockFileCache::hash("held_" + 
std::to_string(i))));
+        }
+        for (size_t i = 0; i < kEvictFileCacheReleased; ++i) {
+            insert(io::BlockFileCache::hash("released_" + std::to_string(i)));
+        }
+    }
+
+    ~EvictFileCacheBench() {
+        _held.clear();
+        _cache.reset();
+        config::file_cache_evict_max_scan_entries = _max_scan;
+        config::enable_evict_file_cache_in_advance = _in_advance;
+        config::enable_file_cache_async_touch_on_get_or_set = _async_touch;
+    }
+
+    // Reserves, downloads and releases one new block. Returns false if the 
reservation failed.
+    bool insert_one() {
+        auto holder = insert(io::BlockFileCache::hash("new_" + 
std::to_string(_next++)));
+        CHECK_EQ(holder.file_blocks.size(), 1);
+        return holder.file_blocks.front()->state() != 
io::FileBlock::State::SKIP_CACHE;
+    }
+
+    uint64_t scanned() const { return 
_cache->_evict_scanned_entries_metrics->get_value(); }
+    uint64_t truncated() const { return 
_cache->_evict_scan_truncated_metrics->get_value(); }
+
+private:
+    io::FileBlocksHolder insert(const io::UInt128Wrapper& hash) {
+        io::CacheContext context;
+        io::ReadStatistics stats;
+        context.stats = &stats;
+        context.cache_type = io::FileCacheType::NORMAL;
+        auto holder = _cache->get_or_set(hash, 0, kEvictFileCacheBlock, 
context);
+        for (auto& block : holder.file_blocks) {
+            if (block->state() == io::FileBlock::State::EMPTY &&
+                block->get_or_set_downloader() == 
io::FileBlock::get_caller_id()) {
+                CHECK(block->append(Slice(_payload.data(), 
_payload.size())).ok());
+                CHECK(block->finalize().ok());
+            }
+        }
+        return holder;
+    }
+
+    int64_t _max_scan;
+    bool _in_advance;
+    bool _async_touch;
+    std::string _payload = std::string(kEvictFileCacheBlock, 'x');
+    std::unique_ptr<io::BlockFileCache> _cache;
+    std::vector<io::FileBlocksHolder> _held;
+    size_t _next = 0;
+};
+
+static void BM_FileCacheReserveWithHeldHead(benchmark::State& state) {
+    const auto held = static_cast<size_t>(state.range(0));
+    const int64_t max_scan = state.range(1);
+    EvictFileCacheBench bench(held, max_scan);
+
+    const uint64_t scanned_before = bench.scanned();
+    const uint64_t truncated_before = bench.truncated();
+    int64_t skipped = 0;
+    for (auto _ : state) {
+        skipped += bench.insert_one() ? 0 : 1;
+    }
+    const auto per_op = benchmark::Counter::kAvgIterations;
+    state.counters["scanned"] =
+            benchmark::Counter(static_cast<double>(bench.scanned() - 
scanned_before), per_op);
+    state.counters["truncated"] =
+            benchmark::Counter(static_cast<double>(bench.truncated() - 
truncated_before), per_op);
+    state.counters["skip_cache"] = 
benchmark::Counter(static_cast<double>(skipped), per_op);
+}
+
+BENCHMARK(BM_FileCacheReserveWithHeldHead)
+        ->ArgsProduct({{1024, 8192, 65536}, {0, 4096}})
+        ->Unit(benchmark::kMicrosecond);
+
+} // namespace doris
diff --git a/be/benchmark/benchmark_main.cpp b/be/benchmark/benchmark_main.cpp
index 475eaed28f7..f9297587eb7 100644
--- a/be/benchmark/benchmark_main.cpp
+++ b/be/benchmark/benchmark_main.cpp
@@ -36,6 +36,7 @@
 #include "benchmark_column_array_view.hpp"
 #include "benchmark_column_array_view_distance.hpp"
 #include "benchmark_fastunion.hpp"
+#include "benchmark_file_cache_evict_scan.hpp"
 #include "benchmark_fmod.hpp"
 #include "benchmark_gram_extractor.hpp"
 #include "benchmark_hll_merge.hpp"
diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index f7f4f285800..2de16efe78b 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -1295,6 +1295,7 @@ 
DEFINE_mInt32(file_cache_exit_need_evict_cache_in_advance_percent, "85");
 DEFINE_mInt32(file_cache_evict_in_advance_interval_ms, "1000");
 DEFINE_mInt64(file_cache_evict_in_advance_batch_bytes, "31457280"); // 30MB
 DEFINE_mInt64(file_cache_evict_in_advance_recycle_keys_num_threshold, "1000");
+DEFINE_mInt64(file_cache_evict_max_scan_entries, "4096");
 
 DEFINE_mBool(enable_read_cache_file_directly, "true");
 DEFINE_mBool(file_cache_enable_evict_from_other_queue_by_size, "true");
diff --git a/be/src/common/config.h b/be/src/common/config.h
index 65518f7ea0e..69e37be240b 100644
--- a/be/src/common/config.h
+++ b/be/src/common/config.h
@@ -1349,6 +1349,14 @@ 
DECLARE_mInt32(file_cache_exit_need_evict_cache_in_advance_percent);
 DECLARE_mInt32(file_cache_evict_in_advance_interval_ms);
 DECLARE_mInt64(file_cache_evict_in_advance_batch_bytes);
 DECLARE_mInt64(file_cache_evict_in_advance_recycle_keys_num_threshold);
+// Max LRU entries one cache reservation examines while holding the cache 
lock, across all of its
+// eviction scans (the other queues by time and by size, its own queue, and 
the query's own queue
+// under enable_file_cache_query_limit); evict-in-advance passes are 
reservations too. When the
+// budget runs out before enough space is found, the reservation fails and the 
block is not
+// cached. A get_or_set over several blocks reserves, and gets a budget, per 
block. <= 0 means
+// unbounded. The startup async-load path is not bounded by it. Entries a scan 
skips because
+// they are in use are moved to the end of their queue, so later reservations 
get past them.
+DECLARE_mInt64(file_cache_evict_max_scan_entries);
 DECLARE_mBool(enable_read_cache_file_directly);
 DECLARE_Bool(file_cache_enable_evict_from_other_queue_by_size);
 DECLARE_mBool(enbale_dump_error_file);
diff --git a/be/src/io/cache/block_file_cache.cpp 
b/be/src/io/cache/block_file_cache.cpp
index 3fb960c6c0d..e78e1891889 100644
--- a/be/src/io/cache/block_file_cache.cpp
+++ b/be/src/io/cache/block_file_cache.cpp
@@ -242,6 +242,12 @@ BlockFileCache::BlockFileCache(const std::string& 
cache_base_path,
                                                                     
"file_cache_gc_evict_bytes");
     _gc_evict_count_metrics = 
std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
                                                                     
"file_cache_gc_evict_count");
+    _evict_scanned_entries_metrics = std::make_shared<bvar::Adder<size_t>>(
+            _cache_base_path.c_str(), "file_cache_evict_scanned_entries");
+    _evict_rotated_in_use_metrics = std::make_shared<bvar::Adder<size_t>>(
+            _cache_base_path.c_str(), "file_cache_evict_rotated_in_use");
+    _evict_scan_truncated_metrics = std::make_shared<bvar::Adder<size_t>>(
+            _cache_base_path.c_str(), "file_cache_evict_scan_truncated");
 
     
_evict_by_time_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::NORMAL] 
=
             std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
@@ -397,6 +403,8 @@ BlockFileCache::BlockFileCache(const std::string& 
cache_base_path,
     _probe_latency_us = std::make_shared<bvar::LatencyRecorder>();
     _storage_sync_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
             _cache_base_path.c_str(), 
"file_cache_storage_sync_remove_latency_us");
+    _evict_scan_entries_per_reserve = std::make_shared<bvar::LatencyRecorder>(
+            _cache_base_path.c_str(), 
"file_cache_evict_scan_entries_per_reserve");
     _storage_retry_sync_remove_latency_us = 
std::make_shared<bvar::LatencyRecorder>(
             _cache_base_path.c_str(), 
"file_cache_storage_retry_sync_remove_latency_us");
     _storage_async_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
@@ -1546,11 +1554,18 @@ void BlockFileCache::find_evict_candidates(LRUQueue& 
queue, size_t size, size_t
                                            size_t& removed_size,
                                            std::vector<FileBlockCell*>& 
to_evict,
                                            std::lock_guard<std::mutex>& 
cache_lock,
-                                           size_t& cur_removed_size, bool 
evict_in_advance) {
+                                           size_t& cur_removed_size, bool 
evict_in_advance,
+                                           EvictScanBudget& budget) {
+    // Every scan starts at the head of the queue, so in-use entries left 
there would be examined
+    // again by each later reservation, all under the cache lock. Bounding the 
scan and rotating
+    // in-use entries keeps the lock hold short when much of the cache is in 
use.
+    std::vector<FileBlockCell*> in_use;
     for (const auto& [entry_key, entry_offset, entry_size] : queue) {
-        if (!is_overflow(removed_size, size, cur_cache_size, 
evict_in_advance)) {
+        if (!is_overflow(removed_size, size, cur_cache_size, evict_in_advance) 
||
+            budget.exhausted()) {
             break;
         }
+        ++budget.scanned;
         auto* cell = get_cell(entry_key, entry_offset, cache_lock);
 
         DCHECK(cell) << "Cache became inconsistent. key: " << 
entry_key.to_string()
@@ -1567,8 +1582,46 @@ void BlockFileCache::find_evict_candidates(LRUQueue& 
queue, size_t size, size_t
             to_evict.push_back(cell);
             removed_size += cell_size;
             cur_removed_size += cell_size;
+        } else {
+            in_use.push_back(cell);
         }
     }
+    rotate_in_use_to_end(queue, in_use, cache_lock);
+}
+
+void BlockFileCache::record_evict_scan(const EvictScanBudget& budget, bool 
reserved) {
+    // Most reservations fit without evicting anything; leaving them out keeps 
the distribution
+    // about the reservations that had to scan.
+    if (budget.scanned == 0) {
+        return;
+    }
+    *_evict_scanned_entries_metrics << budget.scanned;
+    *_evict_scan_entries_per_reserve << static_cast<int64_t>(budget.scanned);
+    if (!reserved && budget.exhausted()) {
+        *_evict_scan_truncated_metrics << 1;
+    }
+}
+
+void BlockFileCache::rotate_in_use_to_end(LRUQueue& queue,
+                                          const std::vector<FileBlockCell*>& 
in_use,
+                                          std::lock_guard<std::mutex>& 
cache_lock) {
+    // Called after the scan: moving an entry while iterating would bring it 
back to the scan.
+    // A rotated entry is in use right now, so the move counts as an access, 
as in use_cell().
+    // Updating atime keeps each queue ordered by access time, which the 
time-interval scan
+    // relies on when it stops at the first hot entry. Without it, [A cold in 
use, B cold, C hot]
+    // would become [C, A] after evicting B, and once A is released no 
time-interval scan would
+    // reach it past C.
+    for (auto* cell : in_use) {
+        // A cell taken out of the queue is never reached by a queue scan.
+        DCHECK(cell->queue_iterator);
+        const auto& file_block = cell->file_block;
+        queue.move_to_end(*cell->queue_iterator, cache_lock);
+        _lru_recorder->record_queue_event(file_block->cache_type(), 
CacheLRULogType::MOVETOBACK,
+                                          file_block->_key.hash, 
file_block->_key.offset,
+                                          cell->size());
+        cell->update_atime();
+    }
+    *_evict_rotated_in_use_metrics << in_use.size();
 }
 
 // 1. if async load file cache not finish
@@ -1616,6 +1669,12 @@ bool BlockFileCache::try_reserve(const UInt128Wrapper& 
hash, const CacheContext&
 
     std::vector<LRUQueue::Iterator> ghost;
     std::vector<FileBlockCell*> to_evict;
+    // Query-queue entries skipped because their block is in use. The query 
queue is the query's
+    // own list, which the global queues' rotation does not touch, so they are 
moved to its end
+    // here: with a budget of 3 and query blocks 0-2 held, every later miss 
would otherwise stop on
+    // 0-2 again and never reach the released blocks behind them.
+    std::vector<LRUQueue::Iterator> query_in_use;
+    EvictScanBudget budget(config::file_cache_evict_max_scan_entries);
 
     size_t max_size = queue.get_max_size();
     auto is_overflow = [&] {
@@ -1629,9 +1688,10 @@ bool BlockFileCache::try_reserve(const UInt128Wrapper& 
hash, const CacheContext&
 
     /// Select the cache from the LRU queue held by query for expulsion.
     for (auto iter = query_context->queue().begin(); iter != 
query_context->queue().end(); iter++) {
-        if (!is_overflow()) {
+        if (!is_overflow() || budget.exhausted()) {
             break;
         }
+        ++budget.scanned;
 
         auto* cell = get_cell(iter->hash, iter->offset, cache_lock);
 
@@ -1651,9 +1711,17 @@ bool BlockFileCache::try_reserve(const UInt128Wrapper& 
hash, const CacheContext&
                 DCHECK(file_block->_download_state == 
FileBlock::State::DOWNLOADED);
                 to_evict.push_back(cell);
                 removed_size += cell_size;
+            } else {
+                query_in_use.push_back(iter);
             }
         }
     }
+    // Moved after the scan, as in rotate_in_use_to_end: moving an entry while 
iterating would
+    // bring it back to the scan. splice keeps the iterators the query's 
records hold valid.
+    for (auto& iter : query_in_use) {
+        query_context->queue().move_to_end(iter, cache_lock);
+    }
+    *_evict_rotated_in_use_metrics << query_in_use.size();
 
     auto remove_file_block_if = [&](FileBlockCell* cell) {
         FileBlockSPtr file_block = cell->file_block;
@@ -1671,9 +1739,11 @@ bool BlockFileCache::try_reserve(const UInt128Wrapper& 
hash, const CacheContext&
     std::for_each(to_evict.begin(), to_evict.end(), remove_file_block_if);
 
     if (is_overflow() &&
-        !try_reserve_from_other_queue(context.cache_type, size, cur_time, 
cache_lock)) {
+        !try_reserve_from_other_queue(context.cache_type, size, cur_time, 
cache_lock, budget)) {
+        record_evict_scan(budget, false);
         return false;
     }
+    record_evict_scan(budget, true);
     query_context->reserve(hash, offset, size, cache_lock);
     return true;
 }
@@ -1805,17 +1875,21 @@ void BlockFileCache::reset_range(const UInt128Wrapper& 
hash, size_t offset, size
 
 bool BlockFileCache::try_reserve_from_other_queue_by_time_interval(
         FileCacheType cur_type, std::vector<FileCacheType> other_cache_types, 
size_t size,
-        int64_t cur_time, std::lock_guard<std::mutex>& cache_lock, bool 
evict_in_advance) {
+        int64_t cur_time, std::lock_guard<std::mutex>& cache_lock, 
EvictScanBudget& budget,
+        bool evict_in_advance) {
     size_t removed_size = 0;
     size_t cur_cache_size = _cur_cache_size;
     std::vector<FileBlockCell*> to_evict;
     for (FileCacheType cache_type : other_cache_types) {
         auto& queue = get_queue(cache_type);
         size_t remove_size_per_type = 0;
+        std::vector<FileBlockCell*> in_use;
         for (const auto& [entry_key, entry_offset, entry_size] : queue) {
-            if (!is_overflow(removed_size, size, cur_cache_size, 
evict_in_advance)) {
+            if (!is_overflow(removed_size, size, cur_cache_size, 
evict_in_advance) ||
+                budget.exhausted()) {
                 break;
             }
+            ++budget.scanned;
             auto* cell = get_cell(entry_key, entry_offset, cache_lock);
             DCHECK(cell) << "Cache became inconsistent. UInt128Wrapper: " << 
entry_key.to_string()
                          << ", offset: " << entry_offset;
@@ -1834,8 +1908,11 @@ bool 
BlockFileCache::try_reserve_from_other_queue_by_time_interval(
                 to_evict.push_back(cell);
                 removed_size += cell_size;
                 remove_size_per_type += cell_size;
+            } else {
+                in_use.push_back(cell);
             }
         }
+        rotate_in_use_to_end(queue, in_use, cache_lock);
         *(_evict_by_time_metrics_matrix[cache_type][cur_type]) << 
remove_size_per_type;
     }
     bool is_sync_removal = !evict_in_advance;
@@ -1863,7 +1940,7 @@ bool BlockFileCache::is_overflow(size_t removed_size, 
size_t need_size, size_t c
 
 bool BlockFileCache::try_reserve_from_other_queue_by_size(
         FileCacheType cur_type, std::vector<FileCacheType> other_cache_types, 
size_t size,
-        std::lock_guard<std::mutex>& cache_lock, bool evict_in_advance) {
+        std::lock_guard<std::mutex>& cache_lock, EvictScanBudget& budget, bool 
evict_in_advance) {
     size_t removed_size = 0;
     size_t cur_cache_size = _cur_cache_size;
     std::vector<FileBlockCell*> to_evict;
@@ -1880,7 +1957,7 @@ bool BlockFileCache::try_reserve_from_other_queue_by_size(
         }
         size_t cur_removed_size = 0;
         find_evict_candidates(queue, size, cur_cache_size, removed_size, 
to_evict, cache_lock,
-                              cur_removed_size, evict_in_advance);
+                              cur_removed_size, evict_in_advance, budget);
         *(_evict_by_size_metrics_matrix[cache_type][cur_type]) << 
cur_removed_size;
     }
     bool is_sync_removal = !evict_in_advance;
@@ -1893,11 +1970,12 @@ bool 
BlockFileCache::try_reserve_from_other_queue_by_size(
 bool BlockFileCache::try_reserve_from_other_queue(FileCacheType 
cur_cache_type, size_t size,
                                                   int64_t cur_time,
                                                   std::lock_guard<std::mutex>& 
cache_lock,
-                                                  bool evict_in_advance) {
+                                                  EvictScanBudget& budget, 
bool evict_in_advance) {
     // currently, TTL cache is not considered as a candidate
     auto other_cache_types = get_other_cache_type_without_ttl(cur_cache_type);
     bool reserve_success = try_reserve_from_other_queue_by_time_interval(
-            cur_cache_type, other_cache_types, size, cur_time, cache_lock, 
evict_in_advance);
+            cur_cache_type, other_cache_types, size, cur_time, cache_lock, 
budget,
+            evict_in_advance);
     if (reserve_success || 
!config::file_cache_enable_evict_from_other_queue_by_size) {
         return reserve_success;
     }
@@ -1911,7 +1989,7 @@ bool 
BlockFileCache::try_reserve_from_other_queue(FileCacheType cur_cache_type,
         return false;
     }
     return try_reserve_from_other_queue_by_size(cur_cache_type, 
other_cache_types, size, cache_lock,
-                                                evict_in_advance);
+                                                budget, evict_in_advance);
 }
 
 bool BlockFileCache::try_reserve_for_lru(const UInt128Wrapper& hash,
@@ -1920,7 +1998,8 @@ bool BlockFileCache::try_reserve_for_lru(const 
UInt128Wrapper& hash,
                                          std::lock_guard<std::mutex>& 
cache_lock,
                                          bool evict_in_advance) {
     int64_t cur_time = steady_clock_seconds();
-    if (!try_reserve_from_other_queue(context.cache_type, size, cur_time, 
cache_lock,
+    EvictScanBudget budget(config::file_cache_evict_max_scan_entries);
+    if (!try_reserve_from_other_queue(context.cache_type, size, cur_time, 
cache_lock, budget,
                                       evict_in_advance)) {
         auto& queue = get_queue(context.cache_type);
         size_t removed_size = 0;
@@ -1929,7 +2008,7 @@ bool BlockFileCache::try_reserve_for_lru(const 
UInt128Wrapper& hash,
         std::vector<FileBlockCell*> to_evict;
         size_t cur_removed_size = 0;
         find_evict_candidates(queue, size, cur_cache_size, removed_size, 
to_evict, cache_lock,
-                              cur_removed_size, evict_in_advance);
+                              cur_removed_size, evict_in_advance, budget);
         bool is_sync_removal = !evict_in_advance;
         std::string reason = std::string("try_reserve for cache type ") +
                              cache_type_to_string(context.cache_type) +
@@ -1938,9 +2017,11 @@ bool BlockFileCache::try_reserve_for_lru(const 
UInt128Wrapper& hash,
         *(_evict_by_self_lru_metrics_matrix[context.cache_type]) << 
cur_removed_size;
 
         if (is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) 
{
+            record_evict_scan(budget, false);
             return false;
         }
     }
+    record_evict_scan(budget, true);
 
     if (query_context) {
         query_context->reserve(hash, offset, size, cache_lock);
diff --git a/be/src/io/cache/block_file_cache.h 
b/be/src/io/cache/block_file_cache.h
index a82046a7ab4..d7d701f2857 100644
--- a/be/src/io/cache/block_file_cache.h
+++ b/be/src/io/cache/block_file_cache.h
@@ -469,6 +469,21 @@ private:
     void use_cell(const FileBlockCell& cell, FileBlocks* result, bool 
not_need_move,
                   std::lock_guard<std::mutex>& cache_lock);
 
+    // The LRU entries one reservation may examine under the cache lock, 
shared by all of its
+    // eviction scans so that their total is bounded, not each scan on its 
own. For example, with
+    // file_cache_evict_max_scan_entries = 4096, if the time-interval scan of 
the other queues
+    // examines 4096 in-use entries, the by-size and own-queue scans examine 
none and the
+    // reservation fails, instead of each scanning up to 4096 more.
+    struct EvictScanBudget {
+        explicit EvictScanBudget(int64_t max_entries)
+                : limit(max_entries > 0 ? static_cast<size_t>(max_entries)
+                                        : std::numeric_limits<size_t>::max()) 
{}
+        bool exhausted() const { return scanned >= limit; }
+
+        size_t limit;
+        size_t scanned = 0;
+    };
+
     bool try_reserve_for_lru(const UInt128Wrapper& hash, 
QueryFileCacheContextPtr query_context,
                              const CacheContext& context, size_t offset, 
size_t size,
                              std::lock_guard<std::mutex>& cache_lock,
@@ -481,7 +496,7 @@ private:
 
     bool try_reserve_from_other_queue(FileCacheType cur_cache_type, size_t 
offset, int64_t cur_time,
                                       std::lock_guard<std::mutex>& cache_lock,
-                                      bool evict_in_advance = false);
+                                      EvictScanBudget& budget, bool 
evict_in_advance = false);
 
     size_t get_available_cache_size(FileCacheType cache_type) const;
 
@@ -527,12 +542,13 @@ private:
                                                        
std::vector<FileCacheType> other_cache_types,
                                                        size_t size, int64_t 
cur_time,
                                                        
std::lock_guard<std::mutex>& cache_lock,
+                                                       EvictScanBudget& budget,
                                                        bool evict_in_advance);
 
     bool try_reserve_from_other_queue_by_size(FileCacheType cur_type,
                                               std::vector<FileCacheType> 
other_cache_types,
                                               size_t size, 
std::lock_guard<std::mutex>& cache_lock,
-                                              bool evict_in_advance);
+                                              EvictScanBudget& budget, bool 
evict_in_advance);
 
     bool is_overflow(size_t removed_size, size_t need_size, size_t 
cur_cache_size,
                      bool evict_in_advance) const;
@@ -543,7 +559,14 @@ private:
     void find_evict_candidates(LRUQueue& queue, size_t size, size_t 
cur_cache_size,
                                size_t& removed_size, 
std::vector<FileBlockCell*>& to_evict,
                                std::lock_guard<std::mutex>& cache_lock, 
size_t& cur_removed_size,
-                               bool evict_in_advance);
+                               bool evict_in_advance, EvictScanBudget& budget);
+
+    // Records what one reservation's eviction scans examined, once the 
reservation is decided.
+    void record_evict_scan(const EvictScanBudget& budget, bool reserved);
+
+    // Moves cells an eviction scan skipped because they were in use to the 
end of their queue.
+    void rotate_in_use_to_end(LRUQueue& queue, const 
std::vector<FileBlockCell*>& in_use,
+                              std::lock_guard<std::mutex>& cache_lock);
 
     Status check_ofstream_status(std::ofstream& out, std::string& filename);
     Status dump_one_lru_entry(std::ofstream& out, std::string& filename, const 
UInt128Wrapper& hash,
@@ -654,6 +677,9 @@ private:
     std::shared_ptr<bvar::Adder<size_t>> _evict_not_downloaded_num_metrics;
     std::shared_ptr<bvar::Adder<size_t>> _gc_evict_bytes_metrics;
     std::shared_ptr<bvar::Adder<size_t>> _gc_evict_count_metrics;
+    std::shared_ptr<bvar::Adder<size_t>> _evict_scanned_entries_metrics;
+    std::shared_ptr<bvar::Adder<size_t>> _evict_rotated_in_use_metrics;
+    std::shared_ptr<bvar::Adder<size_t>> _evict_scan_truncated_metrics;
     std::shared_ptr<bvar::Adder<size_t>> _evict_by_time_metrics_matrix[4][4];
     std::shared_ptr<bvar::Adder<size_t>> _evict_by_size_metrics_matrix[4][4];
     std::shared_ptr<bvar::Adder<size_t>> _evict_by_self_lru_metrics_matrix[4];
@@ -690,6 +716,7 @@ private:
     std::shared_ptr<bvar::LatencyRecorder> _get_or_set_latency_us;
     std::shared_ptr<bvar::LatencyRecorder> _probe_latency_us;
     std::shared_ptr<bvar::LatencyRecorder> _storage_sync_remove_latency_us;
+    std::shared_ptr<bvar::LatencyRecorder> _evict_scan_entries_per_reserve;
     std::shared_ptr<bvar::LatencyRecorder> 
_storage_retry_sync_remove_latency_us;
     std::shared_ptr<bvar::LatencyRecorder> _storage_async_remove_latency_us;
     std::shared_ptr<bvar::LatencyRecorder> _evict_in_advance_latency_us;
diff --git a/be/test/io/cache/block_file_cache_evict_scan_test.cpp 
b/be/test/io/cache/block_file_cache_evict_scan_test.cpp
new file mode 100644
index 00000000000..1322cd38d33
--- /dev/null
+++ b/be/test/io/cache/block_file_cache_evict_scan_test.cpp
@@ -0,0 +1,525 @@
+// 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.
+
+// Eviction scans under the cache lock: in-use entries an eviction skips must 
not be examined
+// again by the next reservation, and a scan must stop at 
file_cache_evict_max_scan_entries.
+
+#include <chrono>
+#include <set>
+#include <vector>
+
+#include "io/cache/block_file_cache_test_common.h"
+#include "util/defer_op.h"
+
+namespace doris::io {
+
+namespace {
+
+constexpr size_t kBlockSize = 10;
+constexpr size_t kBlocks = 10;
+
+FileCacheSettings normal_only_settings() {
+    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 = kBlocks * kBlockSize;
+    settings.query_queue_elements = kBlocks + 1;
+    settings.max_file_block_size = kBlockSize;
+    settings.max_query_cache_size = kBlocks * kBlockSize;
+    settings.capacity = kBlocks * kBlockSize;
+    return settings;
+}
+
+// Five blocks each for the disposable and normal queues; a normal reservation 
into the full cache
+// first tries to take cold disposable blocks.
+FileCacheSettings disposable_and_normal_settings() {
+    FileCacheSettings settings = normal_only_settings();
+    settings.disposable_queue_size = 5 * kBlockSize;
+    settings.disposable_queue_elements = 6;
+    settings.query_queue_size = 5 * kBlockSize;
+    settings.query_queue_elements = 6;
+    return settings;
+}
+
+// Inserts one block of `hash` at `offset`, downloads it and returns its 
holder.
+FileBlocksHolder insert_block(BlockFileCache& cache, const UInt128Wrapper& 
hash, size_t offset,
+                              FileCacheType type = FileCacheType::NORMAL) {
+    CacheContext context;
+    ReadStatistics rstats;
+    context.stats = &rstats;
+    context.cache_type = type;
+    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(), '0');
+            EXPECT_TRUE(block->append(Slice(data.data(), data.size())).ok());
+            EXPECT_TRUE(block->finalize().ok());
+        }
+    }
+    return holder;
+}
+
+class EvictScanConfigGuard {
+public:
+    explicit EvictScanConfigGuard(int64_t max_scan)
+            : _max_scan(config::file_cache_evict_max_scan_entries),
+              _in_advance(config::enable_evict_file_cache_in_advance) {
+        config::file_cache_evict_max_scan_entries = max_scan;
+        config::enable_evict_file_cache_in_advance = false;
+    }
+    ~EvictScanConfigGuard() {
+        config::file_cache_evict_max_scan_entries = _max_scan;
+        config::enable_evict_file_cache_in_advance = _in_advance;
+    }
+
+private:
+    int64_t _max_scan;
+    bool _in_advance;
+};
+
+// Fills the cache: the first `held` blocks of `key` stay held (in use, at the 
LRU head), the
+// rest are released.
+std::vector<FileBlocksHolder> fill_with_held_head(BlockFileCache& cache, const 
UInt128Wrapper& key,
+                                                  size_t held) {
+    std::vector<FileBlocksHolder> holders;
+    for (size_t i = 0; i < kBlocks; ++i) {
+        auto holder = insert_block(cache, key, i * kBlockSize);
+        if (i < held) {
+            holders.push_back(std::move(holder));
+        }
+    }
+    return holders;
+}
+
+// Fills the disposable queue with 5 blocks of `disposable_key`, the first 
`held` of them held, and
+// the normal queue with 5 released blocks of `normal_key`; then ages the 
disposable blocks past
+// their queue's hot interval so a time-interval scan may evict them.
+std::vector<FileBlocksHolder> fill_disposable_and_normal(BlockFileCache& cache,
+                                                         const UInt128Wrapper& 
disposable_key,
+                                                         const UInt128Wrapper& 
normal_key,
+                                                         size_t held) {
+    std::vector<FileBlocksHolder> holders;
+    for (size_t i = 0; i < 5; ++i) {
+        auto holder =
+                insert_block(cache, disposable_key, i * kBlockSize, 
FileCacheType::DISPOSABLE);
+        if (i < held) {
+            holders.push_back(std::move(holder));
+        }
+    }
+    for (size_t i = 0; i < 5; ++i) {
+        insert_block(cache, normal_key, i * kBlockSize);
+    }
+    std::lock_guard cache_lock(cache._mutex);
+    const int64_t now = std::chrono::duration_cast<std::chrono::seconds>(
+                                
std::chrono::steady_clock::now().time_since_epoch())
+                                .count();
+    for (auto& [offset, cell] : cache._files.at(disposable_key)) {
+        cell.atime = now - 2 * 60 * 60;
+    }
+    return holders;
+}
+
+// Offsets of `hash` that have a cell in the cache. Not get_blocks_by_key(): 
it marks every block
+// it returns as owned by a cached reader, which makes a block held by a test 
holder releasable.
+std::set<size_t> cached_offsets(BlockFileCache& cache, const UInt128Wrapper& 
hash) {
+    std::lock_guard cache_lock(cache._mutex);
+    std::set<size_t> offsets;
+    if (auto it = cache._files.find(hash); it != cache._files.end()) {
+        for (const auto& [offset, cell] : it->second) {
+            offsets.insert(offset);
+        }
+    }
+    return offsets;
+}
+
+// Counters of one cache, read through the per-cache bvars.
+struct EvictScanCounters {
+    uint64_t scanned;
+    uint64_t rotated;
+    uint64_t truncated;
+};
+
+EvictScanCounters counters(const BlockFileCache& cache) {
+    return {cache._evict_scanned_entries_metrics->get_value(),
+            cache._evict_rotated_in_use_metrics->get_value(),
+            cache._evict_scan_truncated_metrics->get_value()};
+}
+
+int64_t steady_now_seconds() {
+    return std::chrono::duration_cast<std::chrono::seconds>(
+                   std::chrono::steady_clock::now().time_since_epoch())
+            .count();
+}
+
+} // namespace
+
+TEST_F(BlockFileCacheTest, evict_scan_rotates_in_use_entries) {
+    EvictScanConfigGuard guard(/*max_scan=*/0);
+    auto base = (caches_dir / "evict_scan_rotate" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_scan_rotate_key");
+    auto held = fill_with_held_head(cache, key, /*held=*/5);
+
+    // The first eviction skips the 5 held blocks and evicts block 5.
+    auto before = counters(cache);
+    auto other1 = insert_block(cache, 
BlockFileCache::hash("evict_scan_rotate_other1"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 6);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 5);
+    auto blocks = cached_offsets(cache, key);
+    EXPECT_FALSE(blocks.contains(5 * kBlockSize));
+    for (size_t i = 0; i < 5; ++i) {
+        EXPECT_TRUE(blocks.contains(i * kBlockSize)) << i;
+    }
+
+    // The held blocks were moved behind block 6, so the next eviction 
examines one entry.
+    before = counters(cache);
+    auto other2 = insert_block(cache, 
BlockFileCache::hash("evict_scan_rotate_other2"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 1);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 0);
+    EXPECT_FALSE(cached_offsets(cache, key).contains(6 * kBlockSize));
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_stops_at_bound_and_skips_cache) {
+    EvictScanConfigGuard guard(/*max_scan=*/3);
+    auto base = (caches_dir / "evict_scan_bound" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_scan_bound_key");
+    auto held = fill_with_held_head(cache, key, /*held=*/5);
+
+    // The scan stops after held blocks 0-2, so the reservation fails and the 
block is not cached.
+    auto before = counters(cache);
+    auto other1 = insert_block(cache, 
BlockFileCache::hash("evict_scan_bound_other1"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 3);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 1);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 3);
+    ASSERT_EQ(other1.file_blocks.size(), 1);
+    EXPECT_EQ(other1.file_blocks.front()->state(), 
FileBlock::State::SKIP_CACHE);
+    EXPECT_EQ(cached_offsets(cache, key).size(), kBlocks);
+
+    // Held blocks 0-2 were moved out of the way, so the next scan gets past 
held blocks 3-4 and
+    // evicts block 5 within the bound.
+    before = counters(cache);
+    auto other2 = insert_block(cache, 
BlockFileCache::hash("evict_scan_bound_other2"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 3);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 0);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 2);
+    ASSERT_EQ(other2.file_blocks.size(), 1);
+    EXPECT_EQ(other2.file_blocks.front()->state(), 
FileBlock::State::DOWNLOADED);
+    EXPECT_FALSE(cached_offsets(cache, key).contains(5 * kBlockSize));
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_by_time_rotates_in_use_entries) {
+    EvictScanConfigGuard guard(/*max_scan=*/0);
+    auto base = (caches_dir / "evict_scan_by_time" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, disposable_and_normal_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto disposable_key = 
BlockFileCache::hash("evict_scan_by_time_disposable");
+    auto normal_key = BlockFileCache::hash("evict_scan_by_time_normal");
+    auto held = fill_disposable_and_normal(cache, disposable_key, normal_key, 
/*held=*/3);
+
+    // The time-interval scan of the disposable queue skips the 3 held blocks 
and evicts block 3.
+    const int64_t before_scan = steady_now_seconds();
+    auto before = counters(cache);
+    auto other1 = insert_block(cache, 
BlockFileCache::hash("evict_scan_by_time_other1"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 4);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 3);
+    auto blocks = cached_offsets(cache, disposable_key);
+    EXPECT_FALSE(blocks.contains(3 * kBlockSize));
+    EXPECT_EQ(cached_offsets(cache, normal_key).size(), 5);
+    {
+        // Rotation counts as an access, so the queue stays ordered by access 
time: the rotated
+        // blocks are hot now and sit behind cold block 4.
+        std::lock_guard cache_lock(cache._mutex);
+        for (size_t i = 0; i < 3; ++i) {
+            EXPECT_GE(cache._files.at(disposable_key).at(i * 
kBlockSize).atime, before_scan) << i;
+        }
+    }
+
+    // The next eviction examines one entry: cold block 4.
+    before = counters(cache);
+    auto other2 = insert_block(cache, 
BlockFileCache::hash("evict_scan_by_time_other2"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 1);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 0);
+    blocks = cached_offsets(cache, disposable_key);
+    EXPECT_FALSE(blocks.contains(4 * kBlockSize));
+    for (size_t i = 0; i < 3; ++i) {
+        EXPECT_TRUE(blocks.contains(i * kBlockSize)) << i;
+    }
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_by_time_stops_at_bound) {
+    EvictScanConfigGuard guard(/*max_scan=*/2);
+    auto base = (caches_dir / "evict_scan_by_time_bound" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, disposable_and_normal_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto disposable_key = 
BlockFileCache::hash("evict_scan_by_time_bound_disposable");
+    auto normal_key = BlockFileCache::hash("evict_scan_by_time_bound_normal");
+    auto held = fill_disposable_and_normal(cache, disposable_key, normal_key, 
/*held=*/3);
+
+    // The disposable scan uses the reservation's whole budget on held blocks 
0-1, so the own-queue
+    // scan of the normal queue examines nothing and the reservation fails.
+    auto before = counters(cache);
+    auto other1 = insert_block(cache, 
BlockFileCache::hash("evict_scan_by_time_bound_other1"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 2);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 1);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 2);
+    ASSERT_EQ(other1.file_blocks.size(), 1);
+    EXPECT_EQ(other1.file_blocks.front()->state(), 
FileBlock::State::SKIP_CACHE);
+    EXPECT_EQ(cached_offsets(cache, disposable_key).size(), 5);
+    EXPECT_EQ(cached_offsets(cache, normal_key).size(), 5);
+
+    // Held blocks 0-1 moved behind blocks 2-4, so the next scan gets past 
held block 2 and evicts
+    // cold block 3 within the budget.
+    before = counters(cache);
+    auto other2 = insert_block(cache, 
BlockFileCache::hash("evict_scan_by_time_bound_other2"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 2);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 0);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 1);
+    ASSERT_EQ(other2.file_blocks.size(), 1);
+    EXPECT_EQ(other2.file_blocks.front()->state(), 
FileBlock::State::DOWNLOADED);
+    EXPECT_FALSE(cached_offsets(cache, disposable_key).contains(3 * 
kBlockSize));
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_succeeds_at_exact_budget) {
+    EvictScanConfigGuard guard(/*max_scan=*/6);
+    auto base = (caches_dir / "evict_scan_exact_budget" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_scan_exact_budget_key");
+    auto held = fill_with_held_head(cache, key, /*held=*/5);
+
+    // The 6th and last entry the budget allows is evictable block 5, which is 
enough.
+    auto before = counters(cache);
+    auto other = insert_block(cache, 
BlockFileCache::hash("evict_scan_exact_budget_other"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 6);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 0);
+    ASSERT_EQ(other.file_blocks.size(), 1);
+    EXPECT_EQ(other.file_blocks.front()->state(), 
FileBlock::State::DOWNLOADED);
+    EXPECT_FALSE(cached_offsets(cache, key).contains(5 * kBlockSize));
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_evicts_rotated_entries_after_release) {
+    EvictScanConfigGuard guard(/*max_scan=*/0);
+    auto base = (caches_dir / "evict_scan_release" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_scan_release_key");
+    auto held = fill_with_held_head(cache, key, /*held=*/5);
+
+    // Rotates held blocks 0-4 behind blocks 6-9 and evicts block 5.
+    auto other0 = insert_block(cache, 
BlockFileCache::hash("evict_scan_release_other0"), 0);
+    held.clear();
+
+    // Blocks 6-9 go first, one entry each; then the released block 0 is 
evicted from where
+    // rotation put it, again after examining one entry.
+    std::vector<FileBlocksHolder> others;
+    for (size_t i = 1; i <= 4; ++i) {
+        auto name = "evict_scan_release_other" + std::to_string(i);
+        others.push_back(insert_block(cache, BlockFileCache::hash(name), 0));
+    }
+    EXPECT_EQ(cached_offsets(cache, key), (std::set<size_t> {0, 10, 20, 30, 
40}));
+    auto before = counters(cache);
+    auto other5 = insert_block(cache, 
BlockFileCache::hash("evict_scan_release_other5"), 0);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 1);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 0);
+    EXPECT_FALSE(cached_offsets(cache, key).contains(0));
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_budget_is_per_block_of_a_request) {
+    EvictScanConfigGuard guard(/*max_scan=*/3);
+    auto base = (caches_dir / "evict_scan_multi_block" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_scan_multi_block_key");
+    auto held = fill_with_held_head(cache, key, /*held=*/5);
+
+    // One get_or_set over three blocks reserves each block with its own 
budget: the first runs
+    // out on held blocks 0-2 and is not cached, the second gets past held 
blocks 3-4 and evicts
+    // block 5, the third evicts block 6.
+    auto before = counters(cache);
+    const int64_t reservations_before = 
cache._evict_scan_entries_per_reserve->count();
+    CacheContext context;
+    ReadStatistics rstats;
+    context.stats = &rstats;
+    context.cache_type = FileCacheType::NORMAL;
+    auto holder = 
cache.get_or_set(BlockFileCache::hash("evict_scan_multi_block_other"), 0,
+                                   3 * kBlockSize, context);
+    ASSERT_EQ(holder.file_blocks.size(), 3);
+    auto it = holder.file_blocks.begin();
+    EXPECT_EQ((*it++)->state(), FileBlock::State::SKIP_CACHE);
+    EXPECT_EQ((*it++)->state(), FileBlock::State::EMPTY);
+    EXPECT_EQ((*it++)->state(), FileBlock::State::EMPTY);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 7);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 1);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 5);
+    EXPECT_EQ(cache._evict_scan_entries_per_reserve->count() - 
reservations_before, 3);
+    auto offsets = cached_offsets(cache, key);
+    EXPECT_FALSE(offsets.contains(5 * kBlockSize));
+    EXPECT_FALSE(offsets.contains(6 * kBlockSize));
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_rotation_replays_into_lru_recorder) {
+    EvictScanConfigGuard guard(/*max_scan=*/0);
+    // The recorder logs queue events only while the LRU dump keeps a tail of 
records.
+    const int64_t tail_records = 
config::file_cache_background_lru_dump_tail_record_num;
+    config::file_cache_background_lru_dump_tail_record_num = 1000;
+    Defer restore_tail {
+            [&] { config::file_cache_background_lru_dump_tail_record_num = 
tail_records; }};
+    auto base = (caches_dir / "evict_scan_recorder" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    auto key = BlockFileCache::hash("evict_scan_recorder_key");
+    auto held = fill_with_held_head(cache, key, /*held=*/5);
+    auto other = insert_block(cache, 
BlockFileCache::hash("evict_scan_recorder_other"), 0);
+
+    // The rotation was logged as MOVETOBACK events, so the shadow queue the 
LRU dump is written
+    // from ends up in the same order as the real queue: [6, 7, 8, 9, 0, 1, 2, 
3, 4, other].
+    while (cache._lru_recorder->replay_queue_event(FileCacheType::NORMAL) > 0) 
{
+    }
+    std::string real;
+    {
+        std::lock_guard cache_lock(cache._mutex);
+        real = cache._normal_queue.to_string(cache_lock);
+    }
+    std::string shadow;
+    {
+        std::lock_guard log_lock(cache._lru_recorder->_mutex_lru_log);
+        shadow = 
cache._lru_recorder->get_shadow_queue(FileCacheType::NORMAL).to_string(log_lock);
+    }
+    EXPECT_EQ(shadow, real);
+}
+
+TEST_F(BlockFileCacheTest, evict_scan_query_limit_rotates_in_use_entries) {
+    EvictScanConfigGuard guard(/*max_scan=*/3);
+    const bool query_limit = config::enable_file_cache_query_limit;
+    config::enable_file_cache_query_limit = true;
+    Defer restore_query_limit {[&] { config::enable_file_cache_query_limit = 
query_limit; }};
+    auto base = (caches_dir / "evict_scan_query_limit" / "").string();
+    fs::remove_all(base);
+    fs::create_directories(base);
+    Defer cleanup {[&] { fs::remove_all(base); }};
+    BlockFileCache cache(base, normal_only_settings());
+    ASSERT_TRUE(cache.initialize());
+    wait_until_cache_ready(cache);
+
+    TUniqueId query_id;
+    query_id.hi = 1;
+    query_id.lo = 1;
+    // The query may use the whole cache, so a full cache is also a query at 
its limit.
+    auto query_context_holder = cache.get_query_context_holder(query_id, 100);
+    auto insert_for_query = [&](const UInt128Wrapper& hash, size_t offset) {
+        CacheContext context;
+        ReadStatistics rstats;
+        context.stats = &rstats;
+        context.cache_type = FileCacheType::NORMAL;
+        context.query_id = query_id;
+        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(), '0');
+                EXPECT_TRUE(block->append(Slice(data.data(), 
data.size())).ok());
+                EXPECT_TRUE(block->finalize().ok());
+            }
+        }
+        return holder;
+    };
+
+    // Query blocks 0-2 stay held, 3-9 are released.
+    auto key = BlockFileCache::hash("evict_scan_query_limit_key");
+    std::vector<FileBlocksHolder> held;
+    for (size_t i = 0; i < kBlocks; ++i) {
+        auto holder = insert_for_query(key, i * kBlockSize);
+        if (i < 3) {
+            held.push_back(std::move(holder));
+        }
+    }
+    {
+        std::lock_guard cache_lock(cache._mutex);
+        ASSERT_EQ(query_context_holder->context->get_cache_size(cache_lock), 
kBlocks * kBlockSize);
+    }
+
+    // The query-queue scan spends the budget on held blocks 0-2: not cached.
+    auto before = counters(cache);
+    auto other1 = 
insert_for_query(BlockFileCache::hash("evict_scan_query_limit_other1"), 0);
+    ASSERT_EQ(other1.file_blocks.size(), 1);
+    EXPECT_EQ(other1.file_blocks.front()->state(), 
FileBlock::State::SKIP_CACHE);
+    EXPECT_EQ(counters(cache).scanned - before.scanned, 3);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 1);
+    EXPECT_EQ(counters(cache).rotated - before.rotated, 3);
+
+    // Held blocks 0-2 moved to the end of the query queue, so the next miss 
reaches block 3.
+    before = counters(cache);
+    auto other2 = 
insert_for_query(BlockFileCache::hash("evict_scan_query_limit_other2"), 0);
+    ASSERT_EQ(other2.file_blocks.size(), 1);
+    EXPECT_EQ(other2.file_blocks.front()->state(), 
FileBlock::State::DOWNLOADED);
+    EXPECT_EQ(counters(cache).truncated - before.truncated, 0);
+    auto offsets = cached_offsets(cache, key);
+    EXPECT_FALSE(offsets.contains(3 * kBlockSize));
+    for (size_t i = 0; i < 3; ++i) {
+        EXPECT_TRUE(offsets.contains(i * kBlockSize)) << i;
+    }
+}
+
+} // namespace doris::io


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

Reply via email to