This is an automated email from the ASF dual-hosted git repository.
yiguolei 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 27bb8aab747 [improvement](ann) Share the page cache for IVF inverted
lists (#71179)
27bb8aab747 is described below
commit 27bb8aab747f48fdc61d6148674bd7ec52eb23e4
Author: yiguolei <[email protected]>
AuthorDate: Wed Dec 2 11:29:44 2026 +0800
[improvement](ann) Share the page cache for IVF inverted lists (#71179)
### Background
IVF_ON_DISK ANN indexes read vector codes and row IDs from `ann.ivfdata`
during searches. These ranges currently use a dedicated cache, while
column data uses the storage page cache.
### What problem does this PR solve?
Issue Number: None
Related PR: #67024 (preserves the direct-read fallback)
PR Type: Enhancement
Problem Summary:
IVF list caching has a separate memory budget and is exempt from dynamic
cache capacity adjustment. Route these ranges through the existing
data-page cache so ANN and column reads share its budget and eviction
policy. Remove the separate cache, configuration and lifecycle code, and
migrate the affected test fixtures. After upgrading, IVF list caching
follows the storage page cache settings.
### Details
- **Change map:** 258 changed production lines: 35 for routing and key
namespacing, 223 removing the dedicated cache and its configuration,
lifecycle and allocator overloads. 424 changed test lines migrate
fixtures, extend shared-cache checks and remove 238 lines of obsolete
dedicated-cache tests. No generated files or documentation changes.
- **Before and after:** Replace the dedicated LRU with
`StoragePageCache` data pages and LRU-K admission. Keep list-sized
entries, pinned zero-copy reads, the I/O mutex and double-checked
lookup. IVF entries now participate in page-cache capacity adjustment
and stale pruning.
- **Configs and defaults:** Remove `ann_index_ivf_list_cache_limit`
(previously `70%`) and `ann_index_ivf_list_cache_stale_sweep_time_sec`
(previously `3600`). Reuse `storage_page_cache_limit` (`20%`),
`index_page_cache_percentage` (`10%`), `storage_page_cache_shard_size`
(`256`) and `data_page_cache_stale_sweep_time_sec` (`300`). The dynamic
`disable_storage_page_cache` switch (default `false`) now also bypasses
IVF caching. No new settings.
- **Impact on existing users:** SQL, query results and index files
retain their formats. ANN and column pages now compete for data-page
capacity, so hit rates and I/O can change; no performance benchmark was
run. Existing page-cache overrides apply after upgrading.
- **Behavior change:** Clearing `DataPageCache` now clears IVF lists.
The dedicated `AnnIndexIVFListCache` cache name is removed.
- **Migration:** Remove the two obsolete IVF cache settings and tune the
existing page-cache budget if needed. Old settings in BE configuration
files are ignored with the existing unknown-config warning; they no
longer tune IVF caching. Reverting this PR restores the separate cache
without changing index files.
### Testing
- Local static checks: `build-support/clang-format.sh`,
`build-support/check-format.sh`, `build-support/check-build-hygiene.sh`
and `git diff --check`.
- Updated BE unit tests cover shared data-page accounting, warm hits,
eviction and reload, disabled/unavailable cache reads, and concurrent
searches. Existing range-read and index-lifetime fixtures now use
isolated page caches. These tests are linked into `doris_be_test`; they
were not run.
- Updated `ann_empty_array_queries` to clear `DataPageCache`; the P0
configuration includes this suite. Existing IVF-on-disk regression
results are unchanged. Regression tests were not run.
- Compilation, unit tests, regression tests and clang-tidy were not run,
per the author's preference to defer builds and tests.
### Notes for Reviewers
The `ann.ivfdata` key suffix separates IVF ranges from other page-cache
entries. Cache-policy enum values after the removed entry retain their
numeric values. The shared test fixture restores both the runner's cache
pointer and cache-manager registrations.
### Release note
IVF_ON_DISK list data now shares the storage data-page cache. Use
storage page cache settings instead of the removed
`ann_index_ivf_list_cache_limit` and
`ann_index_ivf_list_cache_stale_sweep_time_sec` settings.
### Check List (For Author)
- Behavior changed: Yes (see Details)
- Does this need documentation: Yes (update the ANN IVF_ON_DISK and BE
cache configuration documentation in apache/doris-website to describe
the shared budget and removed settings; documentation PR pending).
- Pre-submission status: Partially verified: static checks only;
compilation, runtime behavior and performance are unverified.
### AI Disclosure
- Tool: Codex (GPT-6)
- Generated: Code, test changes and this description.
- Human review: Not stated.
---
be/src/common/config.cpp | 7 -
be/src/common/config.h | 5 -
be/src/runtime/exec_env.h | 6 -
be/src/runtime/exec_env_init.cpp | 16 --
be/src/runtime/memory/cache_manager.cpp | 9 -
be/src/runtime/memory/cache_policy.h | 4 -
be/src/storage/cache/ann_index_ivf_list_cache.cpp | 61 ------
be/src/storage/cache/ann_index_ivf_list_cache.h | 95 --------
be/src/storage/cache/page_cache.cpp | 15 --
be/src/storage/cache/page_cache.h | 5 -
be/src/storage/index/ann/faiss_ann_index.cpp | 35 ++-
.../cache/ann_index_ivf_list_cache_test.cpp | 238 ---------------------
.../index/ann/ann_index_range_read_test.cpp | 15 +-
.../storage/index/ann/ann_index_reader_test.cpp | 14 +-
.../storage/index/ann/faiss_vector_index_test.cpp | 76 ++++---
.../inverted/snii/snii_ann_container_test.cpp | 20 +-
be/test/testutil/scoped_storage_page_cache.h | 59 +++++
.../ann_index_p0/ann_empty_array_queries.groovy | 2 +-
18 files changed, 130 insertions(+), 552 deletions(-)
diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index f2c2a92cd56..4819145d1fa 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -2163,13 +2163,6 @@ DEFINE_mInt32(max_segment_partial_column_cache_size,
"100");
DEFINE_mBool(enable_prefill_output_dbm_agg_cache_after_compaction, "true");
DEFINE_mBool(enable_prefill_all_dbm_agg_cache_after_compaction, "true");
-// Cache for ANN index IVF on-disk list data.
-// "70%" means 70% of the process available memory, not 70% of total machine
memory.
-// With default mem_limit="90%", this is effectively about 63% (90% * 70%) of
physical memory
-// visible to the process (considering cgroup limits).
-DEFINE_String(ann_index_ivf_list_cache_limit, "70%");
-// Stale sweep time for ANN index IVF list cache in seconds. 3600s is 1 hour.
-DEFINE_mInt32(ann_index_ivf_list_cache_stale_sweep_time_sec, "3600");
// Minimum segment rows required to persist an ANN index. 0 keeps the default
behavior.
DEFINE_mInt64(ann_index_build_min_segment_rows, "0");
DEFINE_Validator(ann_index_build_min_segment_rows,
diff --git a/be/src/common/config.h b/be/src/common/config.h
index 9431162c7d4..140ab9d334a 100644
--- a/be/src/common/config.h
+++ b/be/src/common/config.h
@@ -2109,11 +2109,6 @@ DECLARE_Int32(omp_threads_limit);
DECLARE_Int32(ann_index_build_threads_per_task);
// The capacity of segment partial column cache, used to cache column readers
for each segment.
DECLARE_mInt32(max_segment_partial_column_cache_size);
-// Cache for ANN index IVF on-disk list data.
-// Default "70%" means 70% of total physical memory.
-DECLARE_String(ann_index_ivf_list_cache_limit);
-// Stale sweep time for ANN index IVF list cache in seconds.
-DECLARE_mInt32(ann_index_ivf_list_cache_stale_sweep_time_sec);
// Minimum segment rows required to persist an ANN index.
DECLARE_mInt64(ann_index_build_min_segment_rows);
DECLARE_mBool(enable_ann_index_empty_array);
diff --git a/be/src/runtime/exec_env.h b/be/src/runtime/exec_env.h
index c77a72eedda..22c6a766cef 100644
--- a/be/src/runtime/exec_env.h
+++ b/be/src/runtime/exec_env.h
@@ -127,7 +127,6 @@ class TabletSchemaCache;
class TabletColumnObjectPool;
class UserFunctionCache;
class StoragePageCache;
-class AnnIndexIVFListCache;
class SegmentLoader;
class LookupConnectionCache;
class RowCache;
@@ -373,9 +372,6 @@ public:
void set_id_manager(IdManager* id_manager) { this->_id_manager =
id_manager; }
void set_delete_bitmap_agg_cache(DeleteBitmapAggCache* c) {
_delete_bitmap_agg_cache = c; }
void set_storage_page_cache(StoragePageCache* c) {
this->_storage_page_cache = c; }
- void set_ann_index_ivf_list_cache(AnnIndexIVFListCache* c) {
- this->_ann_index_ivf_list_cache = c;
- }
void set_segment_loader(SegmentLoader* sl) { this->_segment_loader = sl; }
void set_routine_load_task_executor(RoutineLoadTaskExecutor* r) {
this->_routine_load_task_executor = r;
@@ -419,7 +415,6 @@ public:
TabletSchemaCache* get_tablet_schema_cache() { return
_tablet_schema_cache; }
TabletColumnObjectPool* get_tablet_column_object_pool() { return
_tablet_column_object_pool; }
StoragePageCache* get_storage_page_cache() { return _storage_page_cache; }
- AnnIndexIVFListCache* get_ann_index_ivf_list_cache() { return
_ann_index_ivf_list_cache; }
SegmentLoader* segment_loader() { return _segment_loader; }
LookupConnectionCache* get_lookup_connection_cache() { return
_lookup_connection_cache; }
RowCache* get_row_cache() { return _row_cache; }
@@ -586,7 +581,6 @@ private:
TabletColumnObjectPool* _tablet_column_object_pool = nullptr;
std::unique_ptr<BaseStorageEngine> _storage_engine;
StoragePageCache* _storage_page_cache = nullptr;
- AnnIndexIVFListCache* _ann_index_ivf_list_cache = nullptr;
SegmentLoader* _segment_loader = nullptr;
LookupConnectionCache* _lookup_connection_cache = nullptr;
RowCache* _row_cache = nullptr;
diff --git a/be/src/runtime/exec_env_init.cpp b/be/src/runtime/exec_env_init.cpp
index 8d930e7b227..e837510c601 100644
--- a/be/src/runtime/exec_env_init.cpp
+++ b/be/src/runtime/exec_env_init.cpp
@@ -107,7 +107,6 @@
#include "service/backend_service.h"
#include "service/point_query_executor.h"
#include "storage/adaptive_thread_pool_controller.h"
-#include "storage/cache/ann_index_ivf_list_cache.h"
#include "storage/cache/page_cache.h"
#include "storage/id_manager.h"
#include "storage/index/ann/ann_index_result_cache/ann_index_result_cache.h"
@@ -648,20 +647,6 @@ Status ExecEnv::init_mem_env() {
<< PrettyPrinter::print(storage_cache_limit, TUnit::BYTES)
<< ", origin config value: " << config::storage_page_cache_limit;
- // Init ANN index IVF list cache (dedicated cache for IVF on disk)
- {
- int64_t ann_cache_limit =
ParseUtil::parse_mem_spec(config::ann_index_ivf_list_cache_limit,
-
MemInfo::mem_limit(),
-
MemInfo::physical_mem(), &is_percent);
- while (!is_percent && ann_cache_limit > MemInfo::mem_limit() / 2) {
- ann_cache_limit = ann_cache_limit / 2;
- }
- _ann_index_ivf_list_cache =
AnnIndexIVFListCache::create_global_cache(ann_cache_limit);
- LOG(INFO) << "ANN index IVF list cache memory limit: "
- << PrettyPrinter::print(ann_cache_limit, TUnit::BYTES)
- << ", origin config value: " <<
config::ann_index_ivf_list_cache_limit;
- }
-
// Init row cache
int64_t row_cache_mem_limit =
ParseUtil::parse_mem_spec(config::row_cache_mem_limit,
MemInfo::mem_limit(),
@@ -1002,7 +987,6 @@ void ExecEnv::destroy() {
SAFE_DELETE(_tablet_column_object_pool);
// _storage_page_cache must be destoried before _cache_manager
- SAFE_DELETE(_ann_index_ivf_list_cache);
SAFE_DELETE(_storage_page_cache);
SAFE_DELETE(_small_file_mgr);
diff --git a/be/src/runtime/memory/cache_manager.cpp
b/be/src/runtime/memory/cache_manager.cpp
index d6cbefff2dc..b6a7976f7ee 100644
--- a/be/src/runtime/memory/cache_manager.cpp
+++ b/be/src/runtime/memory/cache_manager.cpp
@@ -72,15 +72,6 @@ int64_t CacheManager::for_each_cache_refresh_capacity(double
adjust_weighted,
if (!cache_policy->enable_prune()) {
continue;
}
- // TODO(hezhiqiang): Refactor this to a generic
`enable_adjust_capacity` attribute
- // in CachePolicy so each cache can declare whether it participates
in dynamic
- // capacity adjustment, instead of hardcoding the skip here.
- // Skip ANN IVF list cache: its entries are loaded via expensive
disk/network
- // pread and should not be evicted by transient memory pressure
fluctuations.
- // It already has its own capacity limit and stale-sweep mechanism.
- if (cache_policy->type() ==
CachePolicy::CacheType::ANN_INDEX_IVF_LIST_CACHE) {
- continue;
- }
cache_policy->adjust_capacity_weighted(adjust_weighted);
freed_size +=
cache_policy->profile()->get_counter("FreedMemory")->value();
if (cache_policy->profile()->get_counter("FreedMemory")->value() != 0
&& profile) {
diff --git a/be/src/runtime/memory/cache_policy.h
b/be/src/runtime/memory/cache_policy.h
index b4404cc5816..3c9fec53222 100644
--- a/be/src/runtime/memory/cache_policy.h
+++ b/be/src/runtime/memory/cache_policy.h
@@ -56,7 +56,6 @@ public:
TABLET_COLUMN_OBJECT_POOL = 21,
SCHEMA_CLOUD_DICTIONARY_CACHE = 22,
CONDITION_CACHE = 23,
- ANN_INDEX_IVF_LIST_CACHE = 24,
ANN_INDEX_RESULT_CACHE = 25,
FLUSS_UNION_TAIL_CACHE = 26,
};
@@ -109,8 +108,6 @@ public:
return "SchemaCloudDictionaryCache";
case CacheType::CONDITION_CACHE:
return "ConditionCache";
- case CacheType::ANN_INDEX_IVF_LIST_CACHE:
- return "AnnIndexIVFListCache";
case CacheType::ANN_INDEX_RESULT_CACHE:
return "AnnIndexResultCache";
case CacheType::FLUSS_UNION_TAIL_CACHE:
@@ -145,7 +142,6 @@ public:
{"QueryCache", CacheType::QUERY_CACHE},
{"TabletColumnObjectPool", CacheType::TABLET_COLUMN_OBJECT_POOL},
{"ConditionCache", CacheType::CONDITION_CACHE},
- {"AnnIndexIVFListCache", CacheType::ANN_INDEX_IVF_LIST_CACHE},
{"AnnIndexResultCache", CacheType::ANN_INDEX_RESULT_CACHE},
{"FlussUnionTailCache", CacheType::FLUSS_UNION_TAIL_CACHE}};
diff --git a/be/src/storage/cache/ann_index_ivf_list_cache.cpp
b/be/src/storage/cache/ann_index_ivf_list_cache.cpp
deleted file mode 100644
index d07ea646eaa..00000000000
--- a/be/src/storage/cache/ann_index_ivf_list_cache.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-// 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.
-
-#include "storage/cache/ann_index_ivf_list_cache.h"
-
-#include <glog/logging.h>
-
-#include "common/config.h"
-#include "runtime/memory/lru_cache_policy.h"
-
-namespace doris {
-
-AnnIndexIVFListCache* AnnIndexIVFListCache::_s_instance = nullptr;
-
-AnnIndexIVFListCache* AnnIndexIVFListCache::create_global_cache(size_t
capacity,
- uint32_t
num_shards) {
- DCHECK(_s_instance == nullptr);
- _s_instance = new AnnIndexIVFListCache(capacity, num_shards);
- return _s_instance;
-}
-
-void AnnIndexIVFListCache::destroy_global_cache() {
- delete _s_instance;
- _s_instance = nullptr;
-}
-
-AnnIndexIVFListCache::AnnIndexIVFListCache(size_t capacity, uint32_t
num_shards) {
- _cache = std::make_unique<CacheImpl>(capacity, num_shards);
-}
-
-bool AnnIndexIVFListCache::lookup(const CacheKey& key, PageCacheHandle*
handle) {
- auto* lru_handle = _cache->lookup(key.encode());
- if (lru_handle == nullptr) {
- return false;
- }
- *handle = PageCacheHandle(_cache.get(), lru_handle);
- return true;
-}
-
-void AnnIndexIVFListCache::insert(const CacheKey& key, DataPage* page,
PageCacheHandle* handle) {
- CachePriority priority = CachePriority::NORMAL;
- auto* lru_handle = _cache->insert(key.encode(), page, page->capacity(), 0,
priority);
- DCHECK(lru_handle != nullptr);
- *handle = PageCacheHandle(_cache.get(), lru_handle);
-}
-
-} // namespace doris
diff --git a/be/src/storage/cache/ann_index_ivf_list_cache.h
b/be/src/storage/cache/ann_index_ivf_list_cache.h
deleted file mode 100644
index 9fc9a00e114..00000000000
--- a/be/src/storage/cache/ann_index_ivf_list_cache.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// 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 <stddef.h>
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "runtime/memory/lru_cache_policy.h"
-#include "storage/cache/page_cache.h"
-
-namespace doris {
-
-// Dedicated LRU cache for IVF on-disk inverted list data.
-//
-// Each cache entry corresponds to one IVF list's codes or ids region,
-// keyed by (file-prefix, file-size, region-offset). This gives perfect
-// cache alignment with the IVF access pattern: every search probes a
-// fixed set of lists and each list's codes/ids are always the same
-// (offset, size) pair, so repeated queries hit the cache without any
-// partial-block copies.
-//
-// Separated from StoragePageCache so that:
-// 1. IVF list data does not compete with column-data / index pages.
-// 2. Capacity can be tuned independently (default: 70% of physical memory
-// when ann_index_ivf_list_cache_limit == "0").
-class AnnIndexIVFListCache {
-public:
- // Reuse the same CacheKey format as StoragePageCache for consistency.
- // offset field stores the exact byte offset of the list's codes or ids.
- using CacheKey = StoragePageCache::CacheKey;
-
- class CacheImpl : public LRUCachePolicy {
- public:
- CacheImpl(size_t capacity, uint32_t num_shards)
- :
LRUCachePolicy(CachePolicy::CacheType::ANN_INDEX_IVF_LIST_CACHE, capacity,
- LRUCacheType::SIZE,
-
config::ann_index_ivf_list_cache_stale_sweep_time_sec, num_shards,
- /*element_count_capacity*/ 0,
/*enable_prune*/ true,
- /*is lru-k*/ false) {}
- };
-
- static constexpr uint32_t kDefaultNumShards = 16;
-
- // --------------- singleton ---------------
- static AnnIndexIVFListCache* instance() { return _s_instance; }
-
- static AnnIndexIVFListCache* create_global_cache(size_t capacity,
- uint32_t num_shards =
kDefaultNumShards);
- static void destroy_global_cache();
-
- // --------------- ctor / dtor ---------------
- AnnIndexIVFListCache(size_t capacity, uint32_t num_shards);
- ~AnnIndexIVFListCache() = default;
-
- AnnIndexIVFListCache(const AnnIndexIVFListCache&) = delete;
- AnnIndexIVFListCache& operator=(const AnnIndexIVFListCache&) = delete;
-
- // --------------- operations ---------------
-
- // Lookup a cached entry. Returns true on hit; `handle` is populated and
- // the caller must let it go out of scope (or call reset()) to unpin.
- bool lookup(const CacheKey& key, PageCacheHandle* handle);
-
- // Insert an entry into the cache. On success the cache takes ownership of
- // `page` (via the handle). Caller must release() the unique_ptr.
- void insert(const CacheKey& key, DataPage* page, PageCacheHandle* handle);
-
- std::shared_ptr<MemTrackerLimiter> mem_tracker() { return
_cache->mem_tracker(); }
-
-private:
- static AnnIndexIVFListCache* _s_instance;
-
- std::unique_ptr<CacheImpl> _cache;
-};
-
-} // namespace doris
diff --git a/be/src/storage/cache/page_cache.cpp
b/be/src/storage/cache/page_cache.cpp
index c71837f9de4..52c3dad8e04 100644
--- a/be/src/storage/cache/page_cache.cpp
+++ b/be/src/storage/cache/page_cache.cpp
@@ -38,11 +38,6 @@ MemoryTrackedPageBase<T>::MemoryTrackedPageBase(size_t size,
bool use_cache,
}
}
-template <typename T>
-MemoryTrackedPageBase<T>::MemoryTrackedPageBase(size_t size,
-
std::shared_ptr<MemTrackerLimiter> mem_tracker)
- : _size(size), _mem_tracker_by_allocator(std::move(mem_tracker)) {}
-
MemoryTrackedPageWithPageEntity::MemoryTrackedPageWithPageEntity(size_t size,
bool use_cache,
segment_v2::PageTypePB page_type)
: MemoryTrackedPageBase<char*>(size, use_cache, page_type),
_capacity(size) {
@@ -53,16 +48,6 @@
MemoryTrackedPageWithPageEntity::MemoryTrackedPageWithPageEntity(size_t size, bo
}
}
-MemoryTrackedPageWithPageEntity::MemoryTrackedPageWithPageEntity(
- size_t size, std::shared_ptr<MemTrackerLimiter> mem_tracker)
- : MemoryTrackedPageBase<char*>(size, std::move(mem_tracker)),
_capacity(size) {
- {
-
SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(this->_mem_tracker_by_allocator);
- this->_data = reinterpret_cast<char*>(
- Allocator<false>::alloc(this->_capacity,
ALLOCATOR_ALIGNMENT_16));
- }
-}
-
MemoryTrackedPageWithPageEntity::~MemoryTrackedPageWithPageEntity() {
if (this->_data != nullptr) {
DCHECK(this->_capacity != 0 && this->_size != 0);
diff --git a/be/src/storage/cache/page_cache.h
b/be/src/storage/cache/page_cache.h
index feec965213b..976e6da95ed 100644
--- a/be/src/storage/cache/page_cache.h
+++ b/be/src/storage/cache/page_cache.h
@@ -42,9 +42,6 @@ class MemoryTrackedPageBase : public LRUCacheValueBase {
public:
MemoryTrackedPageBase() = default;
MemoryTrackedPageBase(size_t b, bool use_cache, segment_v2::PageTypePB
page_type);
- // Construct with an explicit mem-tracker (for caches outside
StoragePageCache,
- // e.g. AnnIndexIVFListCache).
- MemoryTrackedPageBase(size_t b, std::shared_ptr<MemTrackerLimiter>
mem_tracker);
MemoryTrackedPageBase(const MemoryTrackedPageBase&) = delete;
MemoryTrackedPageBase& operator=(const MemoryTrackedPageBase&) = delete;
@@ -62,8 +59,6 @@ protected:
class MemoryTrackedPageWithPageEntity : Allocator<false>, public
MemoryTrackedPageBase<char*> {
public:
MemoryTrackedPageWithPageEntity(size_t b, bool use_cache,
segment_v2::PageTypePB page_type);
- // Construct with an explicit mem-tracker.
- MemoryTrackedPageWithPageEntity(size_t b,
std::shared_ptr<MemTrackerLimiter> mem_tracker);
size_t capacity() { return this->_capacity; }
diff --git a/be/src/storage/index/ann/faiss_ann_index.cpp
b/be/src/storage/index/ann/faiss_ann_index.cpp
index 8d68c1bee8a..73173532ed7 100644
--- a/be/src/storage/index/ann/faiss_ann_index.cpp
+++ b/be/src/storage/index/ann/faiss_ann_index.cpp
@@ -55,7 +55,6 @@
#include "faiss/impl/IDSelector.h"
#include "faiss/impl/io.h"
#include "io/io_common.h"
-#include "storage/cache/ann_index_ivf_list_cache.h"
#include "storage/cache/page_cache.h"
#include "storage/index/ann/ann_index.h"
#include "storage/index/ann/ann_index_files.h"
@@ -324,10 +323,11 @@ public:
* Cache granularity matches the IVF access pattern exactly: one entry per
* list's codes region and one per list's ids region, keyed by
* (file_prefix, file_size, byte_offset). Every repeated borrow() on the
- * same list is a guaranteed zero-copy cache hit.
+ * same list can reuse a pinned data page without copying. IVF lists share
+ * the data-page capacity, memory accounting and LRU-K policy with column data.
*
- * Thread-safety: cache lookups / inserts are lock-free (the LRU cache is
- * internally sharded). Disk reads are serialised by _io_mutex because
+ * Thread-safety: cache lookups / inserts use the page cache's internal shard
locks.
+ * Disk reads are serialised by _io_mutex because
* the input is stateful (a cursor and a read buffer).
*
* Stampede protection: when multiple threads concurrently miss the cache
@@ -340,7 +340,7 @@ struct CachedRandomAccessReader : faiss::RandomAccessReader
{
CachedRandomAccessReader(std::unique_ptr<AnnIndexInput> input, std::string
cache_key_prefix,
size_t file_size)
: _input(std::move(input)),
- _cache_key_prefix(std::move(cache_key_prefix)),
+ _cache_key_prefix(std::move(cache_key_prefix) + "/ann.ivfdata"),
_file_size(file_size) {}
// ---- faiss::RandomAccessReader interface ----
@@ -359,8 +359,8 @@ struct CachedRandomAccessReader : faiss::RandomAccessReader
{
return nullptr;
}
- auto* cache = AnnIndexIVFListCache::instance();
- if (!cache) {
+ auto* cache = StoragePageCache::instance();
+ if (!cache || config::disable_storage_page_cache) {
// Read it ourselves. NOT RandomAccessReader::borrow(): faiss
documents
// its default as "allocates a buffer and calls read_at()", and
read_at()
// below is implemented by calling borrow() -- so delegating to
the base
@@ -375,12 +375,12 @@ struct CachedRandomAccessReader :
faiss::RandomAccessReader {
return std::make_unique<OwnedReadRef>(std::move(bytes));
}
- AnnIndexIVFListCache::CacheKey key(_cache_key_prefix, _file_size,
- static_cast<int64_t>(offset));
+ // The ivfdata suffix keeps list offsets separate from other
page-cache users.
+ StoragePageCache::CacheKey key(_cache_key_prefix, _file_size,
static_cast<int64_t>(offset));
- // Fast path: cache hit — zero-copy, lock-free.
+ // Fast path: cache hit — zero-copy, without taking the I/O lock.
PageCacheHandle handle;
- if (cache->lookup(key, &handle)) {
+ if (cache->lookup(key, &handle, segment_v2::DATA_PAGE)) {
++g_ivf_on_disk_cache_stats.hit_cnt;
return _make_pinned_ref(std::move(handle), nbytes);
}
@@ -397,14 +397,14 @@ struct CachedRandomAccessReader :
faiss::RandomAccessReader {
// Double-check: a preceding thread may have loaded this key while
// we waited on _io_mutex.
- if (cache->lookup(key, &handle)) {
+ if (cache->lookup(key, &handle, segment_v2::DATA_PAGE)) {
++g_ivf_on_disk_cache_stats.hit_cnt;
return _make_pinned_ref(std::move(handle), nbytes);
}
// Still a miss — we are the first thread to reach here; read from
disk.
- auto page = _fetch_from_disk_locked(offset, nbytes,
cache->mem_tracker());
- cache->insert(key, page.get(), &handle);
+ auto page = _fetch_from_disk_locked(offset, nbytes);
+ cache->insert(key, page.get(), &handle, segment_v2::DATA_PAGE);
page.release(); // ownership transferred to cache
return _make_pinned_ref(std::move(handle), nbytes);
}
@@ -412,7 +412,7 @@ struct CachedRandomAccessReader : faiss::RandomAccessReader
{
private:
// ---- ReadRef that pins a cache entry ----
- // Owns the bytes it serves. Used when there is no list cache to pin a
page in.
+ // Owns the bytes it serves. Used when the page cache is unavailable or
disabled.
struct OwnedReadRef : faiss::ReadRef {
explicit OwnedReadRef(std::vector<uint8_t> bytes) :
_bytes(std::move(bytes)) {
data_ = _bytes.data();
@@ -444,9 +444,8 @@ private:
/// Read a region from the input, wrapped in a DataPage, and record fetch
metrics.
/// Caller must already hold _io_mutex.
- std::unique_ptr<DataPage> _fetch_from_disk_locked(
- size_t offset, size_t nbytes, std::shared_ptr<MemTrackerLimiter>
mem_tracker) const {
- auto page = std::make_unique<DataPage>(nbytes, std::move(mem_tracker));
+ std::unique_ptr<DataPage> _fetch_from_disk_locked(size_t offset, size_t
nbytes) const {
+ auto page = std::make_unique<DataPage>(nbytes, true,
segment_v2::DATA_PAGE);
const int64_t start_ns = MonotonicNanos();
_read_input(offset, page->data(), nbytes);
diff --git a/be/test/storage/cache/ann_index_ivf_list_cache_test.cpp
b/be/test/storage/cache/ann_index_ivf_list_cache_test.cpp
deleted file mode 100644
index 99c18fc534a..00000000000
--- a/be/test/storage/cache/ann_index_ivf_list_cache_test.cpp
+++ /dev/null
@@ -1,238 +0,0 @@
-// 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.
-
-#include "storage/cache/ann_index_ivf_list_cache.h"
-
-#include <gtest/gtest-message.h>
-#include <gtest/gtest-test-part.h>
-
-#include <atomic>
-#include <barrier>
-#include <cstring>
-#include <thread>
-#include <vector>
-
-#include "gtest/gtest_pred_impl.h"
-
-namespace doris {
-
-static constexpr uint32_t kNumShards = AnnIndexIVFListCache::kDefaultNumShards;
-
-class AnnIndexIVFListCacheTest : public testing::Test {
-public:
- AnnIndexIVFListCacheTest() {
- mem_tracker =
MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL,
-
"AnnIndexIVFListCacheTest");
- }
-
-protected:
- void SetUp() override {
- cache_ = std::make_unique<AnnIndexIVFListCache>(kNumShards * 1024 *
1024, kNumShards);
- }
-
- void TearDown() override { cache_.reset(); }
-
- std::shared_ptr<MemTrackerLimiter> mem_tracker;
- std::unique_ptr<AnnIndexIVFListCache> cache_;
-};
-
-TEST_F(AnnIndexIVFListCacheTest, basic_insert_and_lookup) {
- AnnIndexIVFListCache::CacheKey key("test_file", 4096, 0);
-
- PageCacheHandle handle;
- EXPECT_FALSE(cache_->lookup(key, &handle));
-
- auto* page = new DataPage(1024, mem_tracker);
- std::memset(page->data(), 0xAB, 1024);
-
- cache_->insert(key, page, &handle);
- Slice data = handle.data();
- EXPECT_EQ(data.data, page->data());
-
- PageCacheHandle lookup_handle;
- EXPECT_TRUE(cache_->lookup(key, &lookup_handle));
- Slice lookup_data = lookup_handle.data();
- EXPECT_EQ(static_cast<unsigned char>(lookup_data.data[0]), 0xAB);
-}
-
-TEST_F(AnnIndexIVFListCacheTest, cache_miss_different_key) {
- AnnIndexIVFListCache::CacheKey key("file_a", 4096, 0);
-
- auto* page = new DataPage(512, mem_tracker);
- PageCacheHandle handle;
- cache_->insert(key, page, &handle);
-
- {
- PageCacheHandle miss_handle;
- AnnIndexIVFListCache::CacheKey miss_key("file_b", 4096, 0);
- EXPECT_FALSE(cache_->lookup(miss_key, &miss_handle));
- }
-
- {
- PageCacheHandle miss_handle;
- AnnIndexIVFListCache::CacheKey miss_key("file_a", 8192, 0);
- EXPECT_FALSE(cache_->lookup(miss_key, &miss_handle));
- }
-
- {
- PageCacheHandle miss_handle;
- AnnIndexIVFListCache::CacheKey miss_key("file_a", 4096, 100);
- EXPECT_FALSE(cache_->lookup(miss_key, &miss_handle));
- }
-}
-
-TEST_F(AnnIndexIVFListCacheTest, multiple_entries) {
- constexpr int kCount = 32;
- std::vector<PageCacheHandle> handles(kCount);
- for (int i = 0; i < kCount; ++i) {
- AnnIndexIVFListCache::CacheKey key("multi", 4096, i * 1024);
- auto* page = new DataPage(256, mem_tracker);
- std::memset(page->data(), static_cast<char>(i), 256);
- cache_->insert(key, page, &handles[i]);
- }
-
- for (int i = 0; i < kCount; ++i) {
- AnnIndexIVFListCache::CacheKey key("multi", 4096, i * 1024);
- PageCacheHandle handle;
- EXPECT_TRUE(cache_->lookup(key, &handle));
- Slice data = handle.data();
- EXPECT_EQ(static_cast<unsigned char>(data.data[0]),
static_cast<unsigned char>(i));
- }
-}
-
-// Simulates the stampede protection pattern from
CachedRandomAccessReader::borrow().
-//
-// The test exercises the double-check locking path: N threads concurrently
-// miss the fast-path cache lookup for the same key; only the first thread
-// through the mutex performs the "disk I/O" (here: allocate + fill a
DataPage);
-// the remaining N-1 threads find the entry on re-check and skip the I/O.
-TEST_F(AnnIndexIVFListCacheTest, stampede_protection) {
- constexpr int kThreads = 8;
- const AnnIndexIVFListCache::CacheKey key("stampede_file", 4096, 0);
-
- std::atomic<int> io_count {0};
- std::mutex io_mutex;
- std::barrier sync_point(kThreads);
-
- auto simulate_borrow = [&]() {
- PageCacheHandle handle;
- if (cache_->lookup(key, &handle)) {
- return;
- }
-
- sync_point.arrive_and_wait();
-
- std::lock_guard<std::mutex> lock(io_mutex);
-
- if (cache_->lookup(key, &handle)) {
- return;
- }
-
- auto* page = new DataPage(1024, mem_tracker);
- std::memset(page->data(), 0xCD, 1024);
- io_count.fetch_add(1, std::memory_order_relaxed);
- cache_->insert(key, page, &handle);
- };
-
- std::vector<std::thread> threads;
- threads.reserve(kThreads);
- for (int i = 0; i < kThreads; ++i) {
- threads.emplace_back(simulate_borrow);
- }
- for (auto& t : threads) {
- t.join();
- }
-
- EXPECT_EQ(io_count.load(), 1);
-
- PageCacheHandle verify_handle;
- EXPECT_TRUE(cache_->lookup(key, &verify_handle));
- Slice data = verify_handle.data();
- EXPECT_EQ(static_cast<unsigned char>(data.data[0]), 0xCD);
-}
-
-// Variant: multiple distinct keys under contention. Each key should be
-// loaded exactly once even when many threads race on each key.
-TEST_F(AnnIndexIVFListCacheTest, stampede_protection_multiple_keys) {
- constexpr int kKeys = 4;
- constexpr int kThreadsPerKey = 4;
- constexpr int kTotalThreads = kKeys * kThreadsPerKey;
-
- std::atomic<int> io_counts[kKeys];
- for (auto& c : io_counts) {
- c.store(0);
- }
-
- std::mutex io_mutex;
- std::barrier sync_point(kTotalThreads);
-
- auto simulate_borrow = [&](int key_idx) {
- AnnIndexIVFListCache::CacheKey key("multi_stampede", 4096, key_idx *
1024);
-
- PageCacheHandle handle;
- if (cache_->lookup(key, &handle)) {
- return;
- }
-
- sync_point.arrive_and_wait();
-
- std::lock_guard<std::mutex> lock(io_mutex);
-
- if (cache_->lookup(key, &handle)) {
- return;
- }
-
- auto* page = new DataPage(512, mem_tracker);
- std::memset(page->data(), static_cast<char>(key_idx), 512);
- io_counts[key_idx].fetch_add(1, std::memory_order_relaxed);
- cache_->insert(key, page, &handle);
- };
-
- std::vector<std::thread> threads;
- threads.reserve(kTotalThreads);
- for (int k = 0; k < kKeys; ++k) {
- for (int t = 0; t < kThreadsPerKey; ++t) {
- threads.emplace_back(simulate_borrow, k);
- }
- }
- for (auto& th : threads) {
- th.join();
- }
-
- for (int k = 0; k < kKeys; ++k) {
- EXPECT_EQ(io_counts[k].load(), 1) << "key_idx=" << k;
-
- AnnIndexIVFListCache::CacheKey key("multi_stampede", 4096, k * 1024);
- PageCacheHandle handle;
- EXPECT_TRUE(cache_->lookup(key, &handle));
- Slice data = handle.data();
- EXPECT_EQ(static_cast<unsigned char>(data.data[0]),
static_cast<unsigned char>(k));
- }
-}
-
-TEST_F(AnnIndexIVFListCacheTest, singleton_lifecycle) {
- EXPECT_EQ(AnnIndexIVFListCache::instance(), nullptr);
-
- auto* inst = AnnIndexIVFListCache::create_global_cache(kNumShards * 2048,
kNumShards);
- EXPECT_NE(inst, nullptr);
- EXPECT_EQ(AnnIndexIVFListCache::instance(), inst);
-
- AnnIndexIVFListCache::destroy_global_cache();
- EXPECT_EQ(AnnIndexIVFListCache::instance(), nullptr);
-}
-
-} // namespace doris
diff --git a/be/test/storage/index/ann/ann_index_range_read_test.cpp
b/be/test/storage/index/ann/ann_index_range_read_test.cpp
index 794663d753d..b23ef1a0eb0 100644
--- a/be/test/storage/index/ann/ann_index_range_read_test.cpp
+++ b/be/test/storage/index/ann/ann_index_range_read_test.cpp
@@ -47,7 +47,6 @@
#include "io/fs/local_file_system.h"
#include "io/io_common.h"
#include "runtime/exec_env.h"
-#include "storage/cache/ann_index_ivf_list_cache.h"
#include "storage/index/ann/ann_index_reader.h"
#include "storage/index/ann/ann_index_writer.h"
#include "storage/index/ann/ann_search_params.h"
@@ -58,6 +57,7 @@
#include "storage/olap_common.h"
#include "storage/options.h"
#include "storage/tablet/tablet_schema.h"
+#include "testutil/scoped_storage_page_cache.h"
#include "util/debug/leak_annotations.h"
namespace doris::segment_v2 {
@@ -350,18 +350,11 @@ protected:
config::enable_file_cache = false;
ASSERT_TRUE(io::global_local_filesystem()->delete_directory(kTestDir).ok());
ASSERT_TRUE(io::global_local_filesystem()->create_directory(kTestDir).ok());
- // IVF_ON_DISK searches read through this cache in production
(exec_env_init installs it).
- // Installed only when nobody has, and torn down only by its installer.
- if (AnnIndexIVFListCache::instance() == nullptr) {
- (void)AnnIndexIVFListCache::create_global_cache(64 * 1024 * 1024);
- _owns_ivf_list_cache = true;
- }
+ _page_cache = std::make_unique<ScopedStoragePageCache>();
}
void TearDown() override {
- if (_owns_ivf_list_cache) {
- AnnIndexIVFListCache::destroy_global_cache();
- }
+ _page_cache.reset();
config::omp_threads_limit = _saved_omp_threads_limit;
config::enable_file_cache = _saved_enable_file_cache;
EXPECT_TRUE(io::global_local_filesystem()->delete_directory(kTestDir).ok());
@@ -377,7 +370,7 @@ protected:
private:
int32_t _saved_omp_threads_limit = -1;
bool _saved_enable_file_cache = true;
- bool _owns_ivf_list_cache = false;
+ std::unique_ptr<ScopedStoragePageCache> _page_cache;
};
TEST_F(AnnIndexRangeReadTest, LoadAndSearchIssueTheRecordedReads) {
diff --git a/be/test/storage/index/ann/ann_index_reader_test.cpp
b/be/test/storage/index/ann/ann_index_reader_test.cpp
index eedae0f6f58..7eac053a299 100644
--- a/be/test/storage/index/ann/ann_index_reader_test.cpp
+++ b/be/test/storage/index/ann/ann_index_reader_test.cpp
@@ -27,7 +27,6 @@
#include <string_view>
#include <vector>
-#include "storage/cache/ann_index_ivf_list_cache.h"
#include "storage/index/ann/ann_index.h"
#include "storage/index/ann/ann_index_iterator.h"
#include "storage/index/ann/ann_index_storage.h"
@@ -37,7 +36,7 @@
#include "storage/index/inverted/clucene/lucene_ann_store.h"
#include "storage/segment/column_reader.h"
#include "storage/tablet/tablet_schema.h"
-#include "util/defer_op.h"
+#include "testutil/scoped_storage_page_cache.h"
using namespace doris::vector_search_utils;
@@ -774,16 +773,7 @@ TEST_F(AnnIndexReaderTest, AnnIndexReaderIVFRangeSearch) {
// logging source and inputs above record the teardown, and an input destroyed
after its source
// writes into freed memory, which ASAN reports.
TEST_F(AnnIndexReaderTest, IvfOnDiskIndexIsDestroyedBeforeItsSource) {
- // IVF_ON_DISK reads through the list cache in production (exec_env_init
installs it).
- const bool owns_cache = AnnIndexIVFListCache::instance() == nullptr;
- if (owns_cache) {
- AnnIndexIVFListCache::create_global_cache(64 * 1024 * 1024);
- }
- Defer destroy_cache([owns_cache] {
- if (owns_cache) {
- AnnIndexIVFListCache::destroy_global_cache();
- }
- });
+ ScopedStoragePageCache cache;
constexpr int kDim = 8;
constexpr int kRows = 256;
diff --git a/be/test/storage/index/ann/faiss_vector_index_test.cpp
b/be/test/storage/index/ann/faiss_vector_index_test.cpp
index 5fdcf4e4aa2..5155ea2f005 100644
--- a/be/test/storage/index/ann/faiss_vector_index_test.cpp
+++ b/be/test/storage/index/ann/faiss_vector_index_test.cpp
@@ -49,8 +49,8 @@
#include "storage/index/ann/ann_search_params.h"
#include "storage/index/ann/faiss_ann_index.h"
// metrics.h not used directly here
-#include "storage/cache/ann_index_ivf_list_cache.h"
#include "storage/index/ann/vector_search_utils.h"
+#include "testutil/scoped_storage_page_cache.h"
#include "util/cpu_info.h"
#include "util/defer_op.h"
@@ -64,8 +64,7 @@ TEST_F(VectorSearchTest,
SparseLabelsSurviveReloadAndDeleteBitmapFiltering) {
config::enable_ann_index_empty_array = false;
Defer restore_config([&] { config::enable_ann_index_empty_array =
previous; });
// FAISS serialization and readers do not consult the index-writer feature
flag.
- AnnIndexIVFListCache::create_global_cache(64 * 1024 * 1024);
- Defer destroy_cache([] { AnnIndexIVFListCache::destroy_global_cache(); });
+ ScopedStoragePageCache cache(64 * 1024 * 1024);
for (auto type : {FaissBuildParameter::IndexType::HNSW,
FaissBuildParameter::IndexType::IVF,
FaissBuildParameter::IndexType::IVF_ON_DISK}) {
for (auto metric :
@@ -284,8 +283,7 @@ TEST_F(VectorSearchTest,
LegacyDenseHnswNeedsNoLabelCollection) {
}
TEST_F(VectorSearchTest, DenseIvfComplementsDoNotCollectAllListIds) {
- AnnIndexIVFListCache::create_global_cache(16 * 1024 * 1024);
- Defer destroy_cache([] { AnnIndexIVFListCache::destroy_global_cache(); });
+ ScopedStoragePageCache cache(16 * 1024 * 1024);
for (auto type :
{FaissBuildParameter::IndexType::IVF,
FaissBuildParameter::IndexType::IVF_ON_DISK}) {
FaissBuildParameter build;
@@ -1933,8 +1931,7 @@ TEST_F(VectorSearchTest,
InnerProductRangeSearchZeroAndNegativeRadius) {
}
TEST_F(VectorSearchTest, IVFOnDiskSaveLoadAndSearch) {
- AnnIndexIVFListCache::create_global_cache(64 * 1024 * 1024);
- Defer destroy_cache([] { AnnIndexIVFListCache::destroy_global_cache(); });
+ ScopedStoragePageCache cache(64 * 1024 * 1024);
auto index1 = std::make_unique<FaissVectorIndex>();
FaissBuildParameter params;
@@ -1974,29 +1971,43 @@ TEST_F(VectorSearchTest, IVFOnDiskSaveLoadAndSearch) {
ASSERT_TRUE(index2->ann_topn_search(query_vec.data(), 10, search_params,
result).ok());
EXPECT_GT(result.roaring->cardinality(), 0u);
EXPECT_GT(result.ivf_on_disk_cache_miss_cnt, 0);
+ auto* page_cache = StoragePageCache::instance();
+ EXPECT_GT(page_cache->mem_tracker(DATA_PAGE)->consumption(), 0);
+ EXPECT_EQ(page_cache->mem_tracker(INDEX_PAGE)->consumption(), 0);
+
+ IndexSearchResult warm_result;
+ ASSERT_TRUE(index2->ann_topn_search(query_vec.data(), 10, search_params,
warm_result).ok());
+ EXPECT_GT(warm_result.ivf_on_disk_cache_hit_cnt, 0);
+ EXPECT_EQ(warm_result.ivf_on_disk_cache_miss_cnt, 0);
+ EXPECT_EQ(*warm_result.roaring, *result.roaring);
+
+ // Clearing the shared data-page cache must evict IVF lists too.
+ page_cache->_data_page_cache->prune_all(true);
+ IndexSearchResult reloaded_result;
+ ASSERT_TRUE(index2->ann_topn_search(query_vec.data(), 10, search_params,
reloaded_result).ok());
+ EXPECT_GT(reloaded_result.ivf_on_disk_cache_miss_cnt, 0);
+ EXPECT_EQ(*reloaded_result.roaring, *result.roaring);
+
+ // Even a warm page cache must be bypassed when storage page caching is
disabled.
+ config::disable_storage_page_cache = true;
+ IndexSearchResult uncached_result;
+ ASSERT_TRUE(index2->ann_topn_search(query_vec.data(), 10, search_params,
uncached_result).ok());
+ EXPECT_EQ(uncached_result.ivf_on_disk_cache_hit_cnt, 0);
+ EXPECT_EQ(uncached_result.ivf_on_disk_cache_miss_cnt, 0);
+ EXPECT_EQ(*uncached_result.roaring, *result.roaring);
+ for (size_t i = 0; i < result.roaring->cardinality(); ++i) {
+ EXPECT_FLOAT_EQ(warm_result.distances[i], result.distances[i]);
+ EXPECT_FLOAT_EQ(reloaded_result.distances[i], result.distances[i]);
+ EXPECT_FLOAT_EQ(uncached_result.distances[i], result.distances[i]);
+ }
}
-// Searching WITHOUT a list cache has to read, not recurse.
-//
-// faiss documents RandomAccessReader::borrow()'s default as "allocates a
buffer
-// and calls read_at()", and CachedRandomAccessReader::read_at() is
implemented by
-// calling borrow(). Falling back to the base borrow() when
-// AnnIndexIVFListCache::instance() is null is therefore unbounded mutual
-// recursion. Every other IVF-on-disk test above installs the cache first,
which
-// is exactly why nothing has ever hit it.
-//
-// exec_env_init installs the cache unconditionally at BE startup, so a
running BE
-// does not reach this today. It is a trap for any unit test that does not
know to
-// install one -- it does not fail, it never returns -- and for any change that
-// makes the cache optional.
-//
-// The search runs on a worker with a deadline because before the fix it does
not
-// return at all: called inline it would hang the whole suite instead of
failing
-// this one case. Everything the worker touches is shared-owned so a hung
thread
-// cannot outlive its arguments.
-TEST_F(VectorSearchTest, IVFOnDiskSearchWithoutTheListCacheStillReads) {
- ASSERT_EQ(AnnIndexIVFListCache::instance(), nullptr)
- << "this case is about the no-cache path, but something installed
a cache";
+// With no page cache, borrow() must read directly: the base borrow() calls
read_at(),
+// which calls borrow() again. Keep a deadline so that recursion cannot hang
the suite.
+TEST_F(VectorSearchTest, IVFOnDiskSearchWithoutPageCacheStillReads) {
+ auto* previous_cache = StoragePageCache::instance();
+ ExecEnv::GetInstance()->set_storage_page_cache(nullptr);
+ Defer restore_cache([&] {
ExecEnv::GetInstance()->set_storage_page_cache(previous_cache); });
auto builder = std::make_unique<FaissVectorIndex>();
FaissBuildParameter params;
@@ -2021,7 +2032,7 @@ TEST_F(VectorSearchTest,
IVFOnDiskSearchWithoutTheListCacheStillReads) {
auto index = std::make_shared<FaissVectorIndex>();
index->set_type(AnnIndexType::IVF_ON_DISK);
- index->set_ivfdata_cache_key_prefix("ut_no_list_cache");
+ index->set_ivfdata_cache_key_prefix("ut_no_page_cache");
ASSERT_TRUE(vector_search_utils::load_from_directory(index.get(),
dir).ok());
auto query_vec = std::make_shared<std::vector<float>>(
@@ -2044,7 +2055,7 @@ TEST_F(VectorSearchTest,
IVFOnDiskSearchWithoutTheListCacheStillReads) {
const bool returned = ready.wait_for(std::chrono::seconds(60)) ==
std::future_status::ready;
if (!returned) {
worker.detach();
- FAIL() << "the search never returned: borrow() recurses when there is
no list cache";
+ FAIL() << "the search never returned: borrow() recurses when there is
no page cache";
}
worker.join();
ASSERT_TRUE(ready.get().ok());
@@ -2055,10 +2066,9 @@ TEST_F(VectorSearchTest,
IVFOnDiskSearchWithoutTheListCacheStillReads) {
// CachedRandomAccessReader with its _io_mutex). On the first round
// (cold cache) threads contend on the same _io_mutex; the first thread
// through loads from "disk" while the rest hit the double-check cache
-// lookup path (lines 372-375 in faiss_ann_index.cpp).
+// lookup path.
TEST_F(VectorSearchTest, IVFOnDiskConcurrentSearchStampedeProtection) {
- AnnIndexIVFListCache::create_global_cache(64 * 1024 * 1024);
- Defer destroy_cache([] { AnnIndexIVFListCache::destroy_global_cache(); });
+ ScopedStoragePageCache cache(64 * 1024 * 1024);
auto index_builder = std::make_unique<FaissVectorIndex>();
FaissBuildParameter params;
diff --git a/be/test/storage/index/inverted/snii/snii_ann_container_test.cpp
b/be/test/storage/index/inverted/snii/snii_ann_container_test.cpp
index 90fa518a66a..6d1670b41a7 100644
--- a/be/test/storage/index/inverted/snii/snii_ann_container_test.cpp
+++ b/be/test/storage/index/inverted/snii/snii_ann_container_test.cpp
@@ -39,7 +39,6 @@
#include "io/fs/local_file_system.h"
#include "io/io_common.h"
#include "runtime/exec_env.h"
-#include "storage/cache/ann_index_ivf_list_cache.h"
#include "storage/index/ann/ann_index_files.h"
#include "storage/index/ann/ann_index_reader.h"
#include "storage/index/ann/ann_index_storage.h"
@@ -57,6 +56,7 @@
#include "storage/olap_common.h"
#include "storage/options.h"
#include "storage/tablet/tablet_schema.h"
+#include "testutil/scoped_storage_page_cache.h"
#include "util/debug_points.h"
namespace doris::segment_v2 {
@@ -181,23 +181,11 @@ protected:
// wrong entry would then also disagree on the length.
_synthetic["fake_bkd_data"] = synthetic_bytes(0x11, 4096 + 17);
_synthetic["fake_bkd_index"] = synthetic_bytes(0x77, 1024 + 3);
- // IVF-on-disk reads its lists through AnnIndexIVFListCache, which
- // exec_env_init installs unconditionally at BE startup -- so this is
the
- // production path, not a test convenience. Installed only if nobody
else
- // in this binary already has one, and torn down only by whoever
installed
- // it: create_global_cache DCHECKs on a second install, and clobbering
- // another fixture's cache is how shared-state bugs start.
- if (AnnIndexIVFListCache::instance() == nullptr) {
- (void)AnnIndexIVFListCache::create_global_cache(8 * 1024 * 1024);
- _owns_ivf_list_cache = true;
- }
+ _page_cache = std::make_unique<ScopedStoragePageCache>();
}
void TearDown() override {
- if (_owns_ivf_list_cache) {
- AnnIndexIVFListCache::destroy_global_cache();
- _owns_ivf_list_cache = false;
- }
+ _page_cache.reset();
EXPECT_TRUE(io::global_local_filesystem()->delete_directory(kTestDir).ok());
}
@@ -272,7 +260,7 @@ protected:
TabletIndex _meta;
TabletIndex _fake_bkd_meta;
TabletIndex _ivf_on_disk_meta;
- bool _owns_ivf_list_cache = false;
+ std::unique_ptr<ScopedStoragePageCache> _page_cache;
std::map<std::string, std::vector<uint8_t>> _synthetic;
};
diff --git a/be/test/testutil/scoped_storage_page_cache.h
b/be/test/testutil/scoped_storage_page_cache.h
new file mode 100644
index 00000000000..d439bd1586f
--- /dev/null
+++ b/be/test/testutil/scoped_storage_page_cache.h
@@ -0,0 +1,59 @@
+// 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 <cstddef>
+
+#include "common/config.h"
+#include "runtime/exec_env.h"
+#include "runtime/memory/cache_manager.h"
+#include "storage/cache/page_cache.h"
+
+namespace doris {
+
+// Give a test a cold data-page cache without deleting the cache owned by the
test runner.
+class ScopedStoragePageCache {
+public:
+ explicit ScopedStoragePageCache(size_t capacity = 64 * 1024 * 1024)
+ : _previous(StoragePageCache::instance()),
+ _previous_disabled(config::disable_storage_page_cache),
+ _cache(capacity, 0, 0, StoragePageCache::kDefaultNumShards) {
+ ExecEnv::GetInstance()->set_storage_page_cache(&_cache);
+ config::disable_storage_page_cache = false;
+ }
+
+ ~ScopedStoragePageCache() {
+ ExecEnv::GetInstance()->set_storage_page_cache(_previous);
+ config::disable_storage_page_cache = _previous_disabled;
+ // BE_TEST replaces registrations by cache type and skips
unregistering on destruction.
+ // Restore them too, so a later cache prune cannot visit this
fixture's destroyed cache.
+ if (_previous != nullptr) {
+ for (auto type : {segment_v2::DATA_PAGE, segment_v2::INDEX_PAGE,
+ segment_v2::PRIMARY_KEY_INDEX_PAGE}) {
+
CacheManager::instance()->register_cache(_previous->_get_page_cache(type));
+ }
+ }
+ }
+
+private:
+ StoragePageCache* _previous;
+ bool _previous_disabled;
+ StoragePageCache _cache;
+};
+
+} // namespace doris
diff --git a/regression-test/suites/ann_index_p0/ann_empty_array_queries.groovy
b/regression-test/suites/ann_index_p0/ann_empty_array_queries.groovy
index f747874b2e0..8884b7bbe26 100644
--- a/regression-test/suites/ann_index_p0/ann_empty_array_queries.groovy
+++ b/regression-test/suites/ann_index_p0/ann_empty_array_queries.groovy
@@ -23,7 +23,7 @@ suite("ann_empty_array_queries", "nonConcurrent") {
def ports = [:]
getBackendIpHttpPort(hosts, ports)
for (def backendId : hosts.keySet()) {
- for (def cache : ['AnnIndexResultCache', 'SegmentCache',
'AnnIndexIVFListCache']) {
+ for (def cache : ['AnnIndexResultCache', 'SegmentCache',
'DataPageCache']) {
httpTest {
endpoint "${hosts[backendId]}:${ports[backendId]}"
uri "/api/clear_cache/${cache}"
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]