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

yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new 499ae6b2c27 branch-4.2: [fix](storage) Rebuild unhealthy cached column 
readers #70738 (#71354)
499ae6b2c27 is described below

commit 499ae6b2c27c3ea63ddfb85e33ffd399363ae470
Author: yiguolei <[email protected]>
AuthorDate: Fri Dec 4 09:33:18 2026 +0800

    branch-4.2: [fix](storage) Rebuild unhealthy cached column readers #70738 
(#71354)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Related PR: #70738
    
    PR Type: Bugfix
    
    A transient IO or memory error during lazy column/index initialization
    can leave a failed reader cached across requests. Backport #70738 to
    `branch-4.2` so subsequent cache access rebuilds unhealthy readers.
    Health checks cover owned column readers, Variant metadata and ANN
    indexes; missing ANN indexes remain healthy to preserve scan fallback.
    Conditional eviction protects concurrently published replacements.
    
    Source commit: `6c956540e171ee5d9b91bd9fc8b53658ff2d73c4`.
    
    ### Backport details
    
    - Preserve branch-4.2 compile-check wrappers in
    `binary_column_reader.cpp` and the existing `SegmentWriter` test
    include.
    - Add the health-check test includes and explicit `<cstdint>`,
    `<string>` and status includes for the ANN reader.
    - Related changes #70723, #70270 and #70788 are already present on
    branch-4.2 via #70757, #71121 and #71250, respectively.
    
    ### Validation
    
    - `git diff --cached --check` passed before committing; no unresolved
    conflicts remain.
    - Compared all added/removed lines against the source commit: the
    backport preserves its changes, with only the explicit standard-library
    includes added for branch-4.2.
    - Included the upstream unit-test changes. Builds and tests were not run
    for this backport, following the author's preference; historical
    upstream results do not validate this revision.
    
    ### Release note
    
    Recover cached column readers after transient initialization failures on
    subsequent cache access.
    
    ### Check List (For Author)
    
    - Test
    - [x] Unit Test (upstream test changes included; not run for this
    backport)
    - Behavior changed:
    - [x] Yes. Failed cached readers are rebuilt; Variant external-metadata
    memory errors retire the reader instead of retrying initialization in
    place.
    - Does this need documentation?
        - [x] No.
    
    ### Check List (For Reviewer who merge this PR)
    
    - [ ] Confirm the release note
    - [ ] Confirm test cases
    - [ ] Confirm document
    - [ ] Add branch pick label
    
    ### AI Disclosure
    
    Codex assisted with backport conflict resolution, static diff inspection
    and this PR description.
---
 be/src/storage/index/ann/ann_index_reader.cpp      |  72 +++--
 be/src/storage/index/ann/ann_index_reader.h        |   6 +
 be/src/storage/index/index_reader.h                |  32 ++-
 be/src/storage/segment/column_reader.cpp           |  39 ++-
 be/src/storage/segment/column_reader.h             |  27 ++
 be/src/storage/segment/column_reader_cache.cpp     | 121 +++++++--
 be/src/storage/segment/column_reader_cache.h       |  17 +-
 .../segment/variant/binary_column_reader.cpp       |  11 +
 .../storage/segment/variant/binary_column_reader.h |   8 +
 .../segment/variant/variant_column_reader.cpp      |  50 +++-
 .../segment/variant/variant_column_reader.h        |   4 +-
 be/test/storage/index/ann/ann_index_load_test.cpp  |  13 +
 .../storage/index/ann/ann_index_reader_test.cpp    |  15 +-
 .../storage/segment/column_reader_cache_test.cpp   | 299 +++++++++++++++++++++
 .../segment/external_col_meta_util_test.cpp        |  36 ++-
 15 files changed, 653 insertions(+), 97 deletions(-)

diff --git a/be/src/storage/index/ann/ann_index_reader.cpp 
b/be/src/storage/index/ann/ann_index_reader.cpp
index 962c769aef4..c038e6ccc42 100644
--- a/be/src/storage/index/ann/ann_index_reader.cpp
+++ b/be/src/storage/index/ann/ann_index_reader.cpp
@@ -21,6 +21,7 @@
 #include <memory>
 
 #include "common/config.h"
+#include "common/exception.h"
 #include "common/metrics/doris_metrics.h"
 #include "io/io_common.h"
 #include "runtime/runtime_profile.h"
@@ -56,40 +57,53 @@ Status 
AnnIndexReader::new_iterator(std::unique_ptr<IndexIterator>* iterator) {
 }
 
 Status AnnIndexReader::load_index(io::IOContext* io_ctx) {
-    return _load_index_once.call([&]() {
-        DorisMetrics::instance()->ann_index_load_cnt->increment(1);
+    return _load_with_health_check([&]() {
+        return _load_index_once.call([&]() {
+            DorisMetrics::instance()->ann_index_load_cnt->increment(1);
 
-        
RETURN_IF_ERROR(_index_file_reader->init(config::inverted_index_read_buffer_size,
 io_ctx));
-        auto source = _index_file_reader->open_ann_source(&_index_meta, 
io_ctx);
-        if (!source.has_value()) {
-            // SNII reports an absent logical index separately from an absent 
container.
-            // Normalize only this lookup failure; missing files inside an ANN 
index are errors.
-            if (source.error().is<ErrorCode::INVERTED_INDEX_SNII_NOT_FOUND>()) 
{
-                return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
-                        "ANN index {} is missing: {}", _index_meta.index_id(),
-                        source.error().to_string());
+            RETURN_IF_ERROR(
+                    
_index_file_reader->init(config::inverted_index_read_buffer_size, io_ctx));
+            auto source = _index_file_reader->open_ann_source(&_index_meta, 
io_ctx);
+            if (!source.has_value()) {
+                // SNII reports an absent logical index separately from an 
absent container.
+                // Normalize only this lookup failure; missing files inside an 
ANN index are errors.
+                if 
(source.error().is<ErrorCode::INVERTED_INDEX_SNII_NOT_FOUND>()) {
+                    return 
Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
+                            "ANN index {} is missing: {}", 
_index_meta.index_id(),
+                            source.error().to_string());
+                }
+                return source.error();
             }
-            return source.error();
-        }
-        _vector_index = std::make_unique<FaissVectorIndex>();
-        _vector_index->set_metric(_metric_type);
-        _vector_index->set_type(_index_type);
-        // Provide a cache key prefix so IVF_ON_DISK can cache ivfdata
-        // blocks in StoragePageCache. Use cache_key (which includes
-        // index_id) rather than file_path, because the idx file is a
-        // compound file shared by multiple indexes.
-        static_cast<FaissVectorIndex*>(_vector_index.get())
-                ->set_ivfdata_cache_key_prefix(
-                        
_index_file_reader->get_index_file_cache_key(&_index_meta));
-        RETURN_IF_ERROR(_vector_index->load(source->get(), io_ctx));
-        // Keep the source alive. For IVF_ON_DISK the CachedRandomAccessReader
-        // reads ann.ivfdata through an input opened from it on every search.
-        // For other types this is harmless (just holds a file handle).
-        _source = std::move(*source);
-        return Status::OK();
+            _vector_index = std::make_unique<FaissVectorIndex>();
+            _vector_index->set_metric(_metric_type);
+            _vector_index->set_type(_index_type);
+            // Provide a cache key prefix so IVF_ON_DISK can cache ivfdata
+            // blocks in StoragePageCache. Use cache_key (which includes
+            // index_id) rather than file_path, because the idx file is a
+            // compound file shared by multiple indexes.
+            static_cast<FaissVectorIndex*>(_vector_index.get())
+                    ->set_ivfdata_cache_key_prefix(
+                            
_index_file_reader->get_index_file_cache_key(&_index_meta));
+            RETURN_IF_ERROR(_vector_index->load(source->get(), io_ctx));
+            // Keep the source alive. For IVF_ON_DISK the 
CachedRandomAccessReader
+            // reads ann.ivfdata through an input opened from it on every 
search.
+            // For other types this is harmless (just holds a file handle).
+            _source = std::move(*source);
+            return Status::OK();
+        });
     });
 }
 
+Status AnnIndexReader::healthy_status() const {
+    auto status = IndexReader::healthy_status();
+    // Small segments can legitimately have no ANN data. Keep their cached 
reader
+    // healthy so every query can fall back without rebuilding the 
ColumnReader.
+    if (status.is<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>()) {
+        return Status::OK();
+    }
+    return status;
+}
+
 Status AnnIndexReader::query(io::IOContext* io_ctx, AnnTopNParam* param, 
AnnIndexStats* stats) {
     // Index should be loaded before calling query
     DCHECK(_vector_index != nullptr);
diff --git a/be/src/storage/index/ann/ann_index_reader.h 
b/be/src/storage/index/ann/ann_index_reader.h
index 14662c37160..79469ccda1a 100644
--- a/be/src/storage/index/ann/ann_index_reader.h
+++ b/be/src/storage/index/ann/ann_index_reader.h
@@ -17,6 +17,10 @@
 
 #pragma once
 
+#include <cstdint>
+#include <string>
+
+#include "common/status.h"
 #include "runtime/runtime_state.h"
 #include "storage/index/ann/ann_index.h"
 #include "storage/index/ann/ann_index_storage.h"
@@ -45,6 +49,8 @@ public:
     // Only INVERTED_INDEX_FILE_NOT_FOUND permits the caller to fall back to a 
scan.
     Status load_index(io::IOContext* io_ctx);
 
+    Status healthy_status() const override;
+
     Status query(io::IOContext* io_ctx, AnnTopNParam* param, AnnIndexStats* 
stats);
 
     Status range_search(const AnnRangeSearchParams& params,
diff --git a/be/src/storage/index/index_reader.h 
b/be/src/storage/index/index_reader.h
index bd92d9f8e54..08ca40ff97b 100644
--- a/be/src/storage/index/index_reader.h
+++ b/be/src/storage/index/index_reader.h
@@ -21,6 +21,8 @@
 
 #include <memory>
 
+#include "common/exception.h"
+#include "common/status.h"
 #include "storage/metadata_adder.h"
 
 namespace doris {
@@ -40,11 +42,39 @@ public:
     IndexReader() = default;
     ~IndexReader() override = default;
 
+    virtual Status healthy_status() const { return _healthy_status.status(); }
+
     virtual IndexType index_type() = 0;
     virtual uint64_t get_index_id() const = 0;
 
     virtual Status new_iterator(std::unique_ptr<IndexIterator>* iterator) = 0;
+
+protected:
+    // Only wrap initialization of cached state. Query-local failures must not
+    // poison this reader. Preserve exceptions after recording them.
+    template <typename Fn>
+    Status _load_with_health_check(Fn&& load) {
+        try {
+            auto status = load();
+            _healthy_status.update(status);
+            return status;
+        } catch (const doris::Exception& e) {
+            _healthy_status.update(e.to_status());
+            throw;
+        } catch (const std::exception& e) {
+            _healthy_status.update(Status::InternalError(
+                    "Exception while initializing cached index reader: {}", 
e.what()));
+            throw;
+        } catch (...) {
+            _healthy_status.update(Status::InternalError(
+                    "Unknown exception while initializing cached index 
reader"));
+            throw;
+        }
+    }
+
+private:
+    AtomicStatus _healthy_status;
 };
 using IndexReaderPtr = std::shared_ptr<IndexReader>;
 
-} // namespace doris::segment_v2
\ No newline at end of file
+} // namespace doris::segment_v2
diff --git a/be/src/storage/segment/column_reader.cpp 
b/be/src/storage/segment/column_reader.cpp
index c8ab319086f..1dd7a2667a4 100644
--- a/be/src/storage/segment/column_reader.cpp
+++ b/be/src/storage/segment/column_reader.cpp
@@ -555,6 +555,23 @@ ColumnReader::ColumnReader(const ColumnReaderOptions& 
opts, const ColumnMetaPB&
 
 ColumnReader::~ColumnReader() = default;
 
+Status ColumnReader::healthy_status() const {
+    RETURN_IF_ERROR(_healthy_status.status());
+    // Child ownership is fixed before publication. Array/Map metadata can have
+    // an unused nullable-helper slot, so only inspect populated child slots.
+    for (const auto& reader : _sub_readers) {
+        if (reader != nullptr) {
+            RETURN_IF_ERROR(reader->healthy_status());
+        }
+    }
+    // Index readers, unlike column children, are added lazily under this lock.
+    std::shared_lock lock(_load_index_lock);
+    for (const auto& [id, reader] : _index_readers) {
+        RETURN_IF_ERROR(reader->healthy_status());
+    }
+    return Status::OK();
+}
+
 int64_t ColumnReader::get_metadata_size() const {
     return sizeof(ColumnReader) + (_segment_zone_map ? 
_segment_zone_map->ByteSizeLong() : 0);
 }
@@ -865,14 +882,19 @@ Status ColumnReader::_load_ordinal_index(bool 
use_page_cache, bool kept_in_memor
     if (!_ordinal_index) {
         return Status::InternalError("ordinal_index not inited");
     }
-    return _ordinal_index->load(use_page_cache, kept_in_memory, 
iter_opts.stats, &iter_opts.io_ctx);
+    return _load_with_health_check([&] {
+        return _ordinal_index->load(use_page_cache, kept_in_memory, 
iter_opts.stats,
+                                    &iter_opts.io_ctx);
+    });
 }
 
 Status ColumnReader::_load_zone_map_index(bool use_page_cache, bool 
kept_in_memory,
                                           const ColumnIteratorOptions& 
iter_opts) {
     if (_zone_map_index != nullptr) {
-        return _zone_map_index->load(use_page_cache, kept_in_memory, 
iter_opts.stats,
-                                     &iter_opts.io_ctx);
+        return _load_with_health_check([&] {
+            return _zone_map_index->load(use_page_cache, kept_in_memory, 
iter_opts.stats,
+                                         &iter_opts.io_ctx);
+        });
     }
     return Status::OK();
 }
@@ -1009,8 +1031,10 @@ bool ColumnReader::has_bloom_filter_index(bool ngram) 
const {
 Status ColumnReader::_load_bloom_filter_index(bool use_page_cache, bool 
kept_in_memory,
                                               const ColumnIteratorOptions& 
iter_opts) {
     if (_bloom_filter_index != nullptr) {
-        return _bloom_filter_index->load(use_page_cache, kept_in_memory, 
iter_opts.stats,
-                                         &iter_opts.io_ctx);
+        return _load_with_health_check([&] {
+            return _bloom_filter_index->load(use_page_cache, kept_in_memory, 
iter_opts.stats,
+                                             &iter_opts.io_ctx);
+        });
     }
     return Status::OK();
 }
@@ -1029,8 +1053,9 @@ Status 
ColumnReader::get_ordinal_index_reader(OrdinalIndexReader*& reader,
                                               OlapReaderStatistics* 
index_load_stats) {
     CHECK(_ordinal_index) << fmt::format("ordinal index is null for column 
reader of type {}",
                                          std::to_string(int(_meta_type)));
-    RETURN_IF_ERROR(
-            _ordinal_index->load(_use_index_page_cache, _opts.kept_in_memory, 
index_load_stats));
+    RETURN_IF_ERROR(_load_with_health_check([&] {
+        return _ordinal_index->load(_use_index_page_cache, 
_opts.kept_in_memory, index_load_stats);
+    }));
     reader = _ordinal_index.get();
     return Status::OK();
 }
diff --git a/be/src/storage/segment/column_reader.h 
b/be/src/storage/segment/column_reader.h
index a3bd46e5f70..16a88b6a3a0 100644
--- a/be/src/storage/segment/column_reader.h
+++ b/be/src/storage/segment/column_reader.h
@@ -161,6 +161,10 @@ public:
 
     ~ColumnReader() override;
 
+    // Checks this reader and its owned readers without changing their local 
status.
+    // Does not perform IO. Call without holding the column-reader cache mutex.
+    virtual Status healthy_status() const;
+
     // create a new column iterator. Client should delete returned iterator
     virtual Status new_iterator(ColumnIteratorUPtr* iterator, const 
TabletColumn* col,
                                 const StorageReadOptions*);
@@ -257,6 +261,28 @@ private:
                  io::FileReaderSPtr file_reader);
     Status init(const ColumnMetaPB* meta);
 
+    // Only wrap initialization of cached state. Iterator-local read failures
+    // must not poison this reader. Preserve exceptions after recording them.
+    template <typename Fn>
+    Status _load_with_health_check(Fn&& load) {
+        try {
+            auto status = load();
+            _healthy_status.update(status);
+            return status;
+        } catch (const doris::Exception& e) {
+            _healthy_status.update(e.to_status());
+            throw;
+        } catch (const std::exception& e) {
+            _healthy_status.update(Status::InternalError(
+                    "Exception while initializing cached column reader: {}", 
e.what()));
+            throw;
+        } catch (...) {
+            _healthy_status.update(Status::InternalError(
+                    "Unknown exception while initializing cached column 
reader"));
+            throw;
+        }
+    }
+
     [[nodiscard]] Status _load_zone_map_index(bool use_page_cache, bool 
kept_in_memory,
                                               const ColumnIteratorOptions& 
iter_opts);
     [[nodiscard]] Status _load_ordinal_index(bool use_page_cache, bool 
kept_in_memory,
@@ -289,6 +315,7 @@ private:
     CompressionTypePB _meta_compression;
 
     ColumnReaderOptions _opts;
+    AtomicStatus _healthy_status;
     uint64_t _num_rows;
 
     io::FileReaderSPtr _file_reader;
diff --git a/be/src/storage/segment/column_reader_cache.cpp 
b/be/src/storage/segment/column_reader_cache.cpp
index bc380061e8b..3e1932b94e8 100644
--- a/be/src/storage/segment/column_reader_cache.cpp
+++ b/be/src/storage/segment/column_reader_cache.cpp
@@ -17,6 +17,9 @@
 
 #include "storage/segment/column_reader_cache.h"
 
+#include <iterator>
+#include <vector>
+
 #include "storage/segment/column_meta_accessor.h"
 #include "storage/segment/segment.h"
 #include "storage/segment/variant/variant_column_reader.h"
@@ -47,49 +50,111 @@ ColumnReaderCache::~ColumnReaderCache() {
 }
 
 std::shared_ptr<ColumnReader> ColumnReaderCache::_lookup(const 
ColumnReaderCacheKey& key) {
-    std::lock_guard<std::mutex> lock(_cache_mutex);
-    auto it = _cache_map.find(key);
-    if (it == _cache_map.end()) {
+    std::shared_ptr<ColumnReader> reader;
+    {
+        std::unique_lock<std::mutex> lock(_cache_mutex);
+        auto it = _cache_map.find(key);
+        if (it == _cache_map.end()) {
+            g_segment_column_cache_miss_count << 1;
+            return nullptr;
+        }
+        _lru_list.splice(_lru_list.begin(), _lru_list, it->second);
+        reader = it->second->reader;
+    }
+    // Recursive checks can acquire reader locks. Never hold the cache mutex
+    // across them: reader creation paths can access this cache while holding
+    // reader locks in the opposite order.
+    if (!reader->healthy_status().ok()) {
+        _erase_if_same(key, reader);
         g_segment_column_cache_miss_count << 1;
         return nullptr;
     }
-    // Move the accessed node to the front of the linked list
-    _lru_list.splice(_lru_list.begin(), _lru_list, it->second);
-    DCHECK_EQ(it->second->key.first, key.first);
     g_segment_column_cache_hit_count << 1;
-    return it->second->reader;
+    return reader;
+}
+
+void ColumnReaderCache::_erase_if_same(const ColumnReaderCacheKey& key,
+                                       const std::shared_ptr<ColumnReader>& 
reader) {
+    std::unique_lock<std::mutex> lock(_cache_mutex);
+    auto it = _cache_map.find(key);
+    // Another caller may have replaced this entry while health was checked.
+    // A late failure from the old instance must not remove its replacement.
+    if (it != _cache_map.end() && it->second->reader == reader) {
+        _erase_locked(lock, it->second);
+    }
+}
+
+std::list<CacheNode>::iterator ColumnReaderCache::_erase_locked(
+        const std::unique_lock<std::mutex>& lock, 
std::list<CacheNode>::iterator it) {
+    DCHECK(lock.owns_lock());
+    DCHECK_EQ(lock.mutex(), &_cache_mutex);
+    _cache_map.erase(it->key);
+    g_segment_column_reader_cache_count << -1;
+    g_segment_column_cache_evict_count << 1;
+    return _lru_list.erase(it);
 }
 
-void ColumnReaderCache::_insert_locked_nocheck(const ColumnReaderCacheKey& key,
+void ColumnReaderCache::_insert_locked_nocheck(const 
std::unique_lock<std::mutex>& lock,
+                                               const ColumnReaderCacheKey& key,
                                                const 
std::shared_ptr<ColumnReader>& reader) {
-    // If capacity exceeded, remove least recently used (tail)
+    DCHECK(lock.owns_lock());
+    DCHECK_EQ(lock.mutex(), &_cache_mutex);
+    // If capacity exceeded, remove least recently used (tail).
     if (_cache_map.size() >= config::max_segment_partial_column_cache_size) {
-        g_segment_column_reader_cache_count << -1;
-        g_segment_column_cache_evict_count << 1;
-        auto last_it = _lru_list.end();
-        --last_it;
-        _cache_map.erase(last_it->key);
-        _lru_list.pop_back();
+        _erase_locked(lock, std::prev(_lru_list.end()));
     }
-    g_segment_column_reader_cache_count << 1;
     _lru_list.push_front(CacheNode {
             .key = key, .reader = reader, .last_access = 
std::chrono::steady_clock::now()});
-    _cache_map[key] = _lru_list.begin();
+    try {
+        _cache_map.emplace(key, _lru_list.begin());
+    } catch (...) {
+        // Map allocation may fail after the list insertion. An orphaned node
+        // could later erase a different reader inserted for the same key.
+        _lru_list.pop_front();
+        throw;
+    }
+    g_segment_column_reader_cache_count << 1;
 }
 
-void ColumnReaderCache::_insert_direct(const ColumnReaderCacheKey& key,
-                                       const std::shared_ptr<ColumnReader>& 
column_reader) {
-    std::lock_guard<std::mutex> lock(_cache_mutex);
-    _insert_locked_nocheck(key, column_reader);
+std::shared_ptr<ColumnReader> ColumnReaderCache::_insert_direct(
+        const ColumnReaderCacheKey& key, const std::shared_ptr<ColumnReader>& 
column_reader) {
+    // An existing nested-group child can fail while its path reader is being
+    // resolved. Check it before taking the cache mutex, just as on lookup.
+    if (!column_reader->healthy_status().ok()) {
+        return column_reader;
+    }
+    std::unique_lock<std::mutex> lock(_cache_mutex);
+    auto it = _cache_map.find(key);
+    // Concurrent misses may insert the same key. Replace its reader in place
+    // so the map and LRU list retain exactly one node for that key.
+    if (it != _cache_map.end()) {
+        it->second->reader = column_reader;
+        _lru_list.splice(_lru_list.begin(), _lru_list, it->second);
+    } else {
+        _insert_locked_nocheck(lock, key, column_reader);
+    }
+    return column_reader;
 }
 
 std::map<int32_t, std::shared_ptr<ColumnReader>> 
ColumnReaderCache::get_available_readers(
         bool include_subcolumns) {
-    std::lock_guard<std::mutex> lock(_cache_mutex);
+    std::vector<std::pair<ColumnReaderCacheKey, 
std::shared_ptr<ColumnReader>>> snapshot;
+    {
+        std::unique_lock<std::mutex> lock(_cache_mutex);
+        snapshot.reserve(_lru_list.size());
+        for (const auto& node : _lru_list) {
+            snapshot.emplace_back(node.key, node.reader);
+        }
+    }
     std::map<int32_t, std::shared_ptr<ColumnReader>> readers;
-    for (const auto& node : _lru_list) {
-        if (include_subcolumns || node.key.second.empty()) {
-            readers.insert({node.key.first, node.reader});
+    for (const auto& [key, reader] : snapshot) {
+        // Enumeration, like lookup, checks reader trees without the cache 
lock.
+        if (!reader->healthy_status().ok()) {
+            _erase_if_same(key, reader);
+            continue;
+        }
+        if (include_subcolumns || key.second.empty()) {
+            readers.insert({key.first, reader});
         }
     }
     return readers;
@@ -140,7 +205,8 @@ Status ColumnReaderCache::get_column_reader(int32_t col_uid,
         RETURN_IF_ERROR(ColumnReader::create(opts, meta, _num_rows, 
_file_reader, &reader));
     }
 
-    _insert_direct({col_uid, {}}, reader);
+    reader = _insert_direct({col_uid, {}}, reader);
+    RETURN_IF_ERROR(reader->healthy_status());
     *column_reader = std::move(reader);
     return Status::OK();
 }
@@ -195,7 +261,8 @@ Status ColumnReaderCache::get_path_column_reader(int32_t 
col_uid, PathInData rel
     RETURN_IF_ERROR(st);
 
     // Cache and return
-    _insert_direct({col_uid, relative_path}, path_reader);
+    path_reader = _insert_direct({col_uid, relative_path}, path_reader);
+    RETURN_IF_ERROR(path_reader->healthy_status());
     *column_reader = std::move(path_reader);
     return Status::OK();
 }
diff --git a/be/src/storage/segment/column_reader_cache.h 
b/be/src/storage/segment/column_reader_cache.h
index a0be7b441f6..b2c6393696f 100644
--- a/be/src/storage/segment/column_reader_cache.h
+++ b/be/src/storage/segment/column_reader_cache.h
@@ -16,6 +16,8 @@
 // under the License.
 #pragma once
 
+#include <mutex>
+
 #include "agent/be_exec_version_manager.h"
 #include "io/fs/file_reader.h"
 #include "storage/segment/stream_reader.h"
@@ -71,15 +73,20 @@ public:
                                           const io::IOContext* io_ctx = 
nullptr);
 
 private:
-    // Lookup function remains similar
+    // Health is checked outside the cache lock; unhealthy instances are 
removed.
     std::shared_ptr<ColumnReader> _lookup(const ColumnReaderCacheKey& key);
-    // Insert helper: assumes _cache_mutex already locked, will evict if needed
-    void _insert_locked_nocheck(const ColumnReaderCacheKey& key,
+    // The caller must hold _cache_mutex through lock; evicts if needed.
+    void _insert_locked_nocheck(const std::unique_lock<std::mutex>& lock,
+                                const ColumnReaderCacheKey& key,
                                 const std::shared_ptr<ColumnReader>& reader);
 
     // Insert an already-created reader directly into cache
-    void _insert_direct(const ColumnReaderCacheKey& key,
-                        const std::shared_ptr<ColumnReader>& column_reader);
+    std::shared_ptr<ColumnReader> _insert_direct(
+            const ColumnReaderCacheKey& key, const 
std::shared_ptr<ColumnReader>& column_reader);
+    std::list<CacheNode>::iterator _erase_locked(const 
std::unique_lock<std::mutex>& lock,
+                                                 
std::list<CacheNode>::iterator it);
+    void _erase_if_same(const ColumnReaderCacheKey& key,
+                        const std::shared_ptr<ColumnReader>& reader);
     // keep _lru_list and _cache_map thread safe
     std::mutex _cache_mutex;
     // Doubly-linked list to maintain LRU order
diff --git a/be/src/storage/segment/variant/binary_column_reader.cpp 
b/be/src/storage/segment/variant/binary_column_reader.cpp
index 3d4f05871c4..a8c03a40014 100644
--- a/be/src/storage/segment/variant/binary_column_reader.cpp
+++ b/be/src/storage/segment/variant/binary_column_reader.cpp
@@ -30,6 +30,17 @@ namespace doris::segment_v2 {
 
 #include "common/compile_check_begin.h"
 
+Status SingleSparseColumnReader::healthy_status() const {
+    return _single_reader->healthy_status();
+}
+
+Status MultipleBinaryColumnReader::healthy_status() const {
+    for (const auto& [index, reader] : _multiple_column_readers) {
+        RETURN_IF_ERROR(reader->healthy_status());
+    }
+    return Status::OK();
+}
+
 Status DummyBinaryColumnReader::new_binary_column_iterator(ColumnIteratorUPtr* 
iter) const {
     static const TabletColumn binary_column = []() {
         TabletColumn binary_column;
diff --git a/be/src/storage/segment/variant/binary_column_reader.h 
b/be/src/storage/segment/variant/binary_column_reader.h
index e31b46703fe..64f99f42954 100644
--- a/be/src/storage/segment/variant/binary_column_reader.h
+++ b/be/src/storage/segment/variant/binary_column_reader.h
@@ -46,6 +46,8 @@ class BinaryColumnReader {
 public:
     virtual ~BinaryColumnReader() = default;
 
+    virtual Status healthy_status() const = 0;
+
     virtual Status new_binary_column_iterator(ColumnIteratorUPtr* iter) const 
= 0;
 
     virtual Status add_binary_column_reader(std::shared_ptr<ColumnReader> 
reader,
@@ -65,6 +67,8 @@ public:
 // for example, old version variant column without any binary data.
 class DummyBinaryColumnReader : public BinaryColumnReader {
 public:
+    Status healthy_status() const override { return Status::OK(); }
+
     Status new_binary_column_iterator(ColumnIteratorUPtr* iter) const override;
     Status add_binary_column_reader(std::shared_ptr<ColumnReader> reader, 
uint32_t index) override;
     std::pair<std::shared_ptr<ColumnReader>, std::string> 
select_reader_and_cache_key(
@@ -76,6 +80,8 @@ public:
 
 class SingleSparseColumnReader : public BinaryColumnReader {
 public:
+    Status healthy_status() const override;
+
     Status add_binary_column_reader(std::shared_ptr<ColumnReader> reader, 
uint32_t index) override;
 
     std::pair<std::shared_ptr<ColumnReader>, std::string> 
select_reader_and_cache_key(
@@ -95,6 +101,8 @@ private:
 
 class MultipleBinaryColumnReader : public BinaryColumnReader {
 public:
+    Status healthy_status() const override;
+
     Status new_binary_column_iterator(ColumnIteratorUPtr* iter) const override;
 
     Status add_binary_column_reader(std::shared_ptr<ColumnReader> reader, 
uint32_t index) override;
diff --git a/be/src/storage/segment/variant/variant_column_reader.cpp 
b/be/src/storage/segment/variant/variant_column_reader.cpp
index 8f477cd3045..bb6a91dcef9 100644
--- a/be/src/storage/segment/variant/variant_column_reader.cpp
+++ b/be/src/storage/segment/variant/variant_column_reader.cpp
@@ -1584,6 +1584,32 @@ Status VariantColumnReader::create_path_reader(
     return st;
 }
 
+Status VariantColumnReader::healthy_status() const {
+    RETURN_IF_ERROR(ColumnReader::healthy_status());
+    // These reader collections are built by init() and immutable afterwards.
+    // External-meta loading changes metadata/statistics, not reader ownership.
+    RETURN_IF_ERROR(_root_column_reader->healthy_status());
+    RETURN_IF_ERROR(_binary_column_reader->healthy_status());
+    auto check_groups = [&](auto&& self, const NestedGroupReaders& groups) -> 
Status {
+        for (const auto& [path, group] : groups) {
+            // Match find_in_nested_groups(): absent/invalid groups cannot 
serve
+            // a read. Path resolution also permits an absent child reader.
+            if (!group || !group->is_valid()) {
+                continue;
+            }
+            RETURN_IF_ERROR(group->offsets_reader->healthy_status());
+            for (const auto& [child_path, reader] : group->child_readers) {
+                if (reader != nullptr) {
+                    RETURN_IF_ERROR(reader->healthy_status());
+                }
+            }
+            RETURN_IF_ERROR(self(self, group->nested_group_readers));
+        }
+        return Status::OK();
+    };
+    return check_groups(check_groups, _nested_group_readers);
+}
+
 Status VariantColumnReader::load_external_meta_once(OlapReaderStatistics* 
stats,
                                                     const io::IOContext* 
source_io_ctx) {
     if (!_ext_meta_reader || !_ext_meta_reader->available()) {
@@ -1592,19 +1618,19 @@ Status 
VariantColumnReader::load_external_meta_once(OlapReaderStatistics* stats,
     // Ensure only one writer can populate `_subcolumns_meta_info` / 
`_statistics`
     // while readers of these structures hold shared locks.
     std::unique_lock<std::shared_mutex> lock(_subcolumns_meta_mutex);
-    Status status = _external_meta_load_once->call([&] {
-        VariantStatistics* variant_stats = 
variant_util::should_record_variant_path_stats(
-                                                   
_tablet_schema->column_by_uid(_root_unique_id))
-                                                   ? _statistics.get()
-                                                   : nullptr;
-        return _ext_meta_reader->load_all(_subcolumns_meta_info.get(), 
variant_stats, stats,
-                                          source_io_ctx);
+    // A partial merge may already have modified the tree/statistics. Rebuild 
the
+    // cached reader after any failure instead of retrying that shared state.
+    return _load_with_health_check([&] {
+        return _external_meta_load_once.call([&] {
+            VariantStatistics* variant_stats =
+                    variant_util::should_record_variant_path_stats(
+                            _tablet_schema->column_by_uid(_root_unique_id))
+                            ? _statistics.get()
+                            : nullptr;
+            return _ext_meta_reader->load_all(_subcolumns_meta_info.get(), 
variant_stats, stats,
+                                              source_io_ctx);
+        });
     });
-    if (status.is<ErrorCode::MEM_LIMIT_EXCEEDED>()) {
-        // A retry skips paths already merged by load_all.
-        _external_meta_load_once.emplace();
-    }
-    return status;
 }
 
 TabletIndexes VariantColumnReader::find_subcolumn_tablet_indexes(const 
TabletColumn& column,
diff --git a/be/src/storage/segment/variant/variant_column_reader.h 
b/be/src/storage/segment/variant/variant_column_reader.h
index b57f2c0d4d1..8e3ee3e3c3a 100644
--- a/be/src/storage/segment/variant/variant_column_reader.h
+++ b/be/src/storage/segment/variant/variant_column_reader.h
@@ -185,6 +185,8 @@ using PathToBinaryColumnCacheUPtr = 
std::unique_ptr<PathToBinaryColumnCache>;
 
 class VariantColumnReader : public ColumnReader {
 public:
+    Status healthy_status() const override;
+
     uint32_t path_encoding() const { return _path_encoding; }
 
     VariantColumnReader() = default;
@@ -428,7 +430,7 @@ private:
 
     // Protect the external meta load guard, subcolumn metadata and statistics.
     mutable std::shared_mutex _subcolumns_meta_mutex;
-    std::optional<DorisCallOnce<Status>> _external_meta_load_once 
{std::in_place};
+    DorisCallOnce<Status> _external_meta_load_once;
     std::unique_ptr<SubcolumnColumnMetaInfo> _subcolumns_meta_info;
     // Sparse column readers (single or bucketized)
     std::shared_ptr<BinaryColumnReader> _binary_column_reader;
diff --git a/be/test/storage/index/ann/ann_index_load_test.cpp 
b/be/test/storage/index/ann/ann_index_load_test.cpp
index dc2d357655d..5ef43cdb41e 100644
--- a/be/test/storage/index/ann/ann_index_load_test.cpp
+++ b/be/test/storage/index/ann/ann_index_load_test.cpp
@@ -142,6 +142,14 @@ TEST_P(AnnIndexLoadTest, OpenStatusReachesIterator) {
     // A repeated load returns the stored failure instead of reporting success 
with a partial index.
     EXPECT_EQ(iterator.load_index().code(), expected_code());
     EXPECT_EQ(_reader->_vector_index, nullptr);
+    const int health_code = expected_code() == 
ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND
+                                    ? ErrorCode::OK
+                                    : expected_code();
+    EXPECT_EQ(_reader->healthy_status().code(), health_code);
+    ColumnReader owner;
+    owner._index_readers.emplace(_meta.index_id(), _reader);
+    EXPECT_EQ(owner.healthy_status().code(), health_code);
+    EXPECT_TRUE(owner._healthy_status.status().ok());
 }
 
 TEST_P(AnnIndexLoadTest, InitStatusIsPreserved) {
@@ -152,6 +160,8 @@ TEST_P(AnnIndexLoadTest, InitStatusIsPreserved) {
     auto status = iterator.load_index();
     EXPECT_EQ(status.code(), GetParam());
     EXPECT_EQ(status.msg(), "injected ANN init failure");
+    EXPECT_EQ(_reader->healthy_status().code(),
+              GetParam() == ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND ? 
ErrorCode::OK : GetParam());
 }
 
 TEST_P(AnnIndexLoadTest, RangeFallsBackOnlyForMissingIndex) {
@@ -197,10 +207,12 @@ TEST_F(AnnIndexLoadTest, EmptyV2ContainerFallsBackToScan) 
{
             &_meta,
             std::make_shared<IndexFileReader>(fs, prefix, 
InvertedIndexStorageFormatPB::V2));
     check_range_load_status(ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND);
+    EXPECT_TRUE(_reader->healthy_status().ok());
     _reader = std::make_shared<AnnIndexReader>(
             &_meta,
             std::make_shared<IndexFileReader>(fs, prefix, 
InvertedIndexStorageFormatPB::V2));
     check_topn_load_status(ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND);
+    EXPECT_TRUE(_reader->healthy_status().ok());
     ASSERT_TRUE(fs->delete_directory(directory).ok());
 }
 
@@ -229,6 +241,7 @@ TEST_F(AnnIndexLoadTest, 
MissingInternalFaissFileIsNotMissingIndex) {
                 });
         auto status = reader->load_index(nullptr);
         EXPECT_TRUE(status.is<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>()) << 
status;
+        
EXPECT_TRUE(reader->healthy_status().is<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>());
     }
 }
 
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 e296254fbd9..53b59dcea2f 100644
--- a/be/test/storage/index/ann/ann_index_reader_test.cpp
+++ b/be/test/storage/index/ann/ann_index_reader_test.cpp
@@ -35,6 +35,7 @@
 #include "storage/index/ann/faiss_ann_index.h"
 #include "storage/index/ann/vector_search_utils.h"
 #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"
 
@@ -218,16 +219,22 @@ TEST_F(AnnIndexReaderTest, TestLoadIndexSuccess) {
 }
 
 TEST_F(AnnIndexReaderTest, TestLoadIndexFailureInit) {
-    auto reader = 
std::make_unique<segment_v2::AnnIndexReader>(_tablet_index.get(),
+    auto column_reader = std::make_shared<segment_v2::ColumnReader>();
+    auto reader = 
std::make_shared<segment_v2::AnnIndexReader>(_tablet_index.get(),
                                                                
_mock_index_file_reader);
+    column_reader->_index_readers.emplace(_tablet_index->index_id(), reader);
 
-    // Mock failed init
     EXPECT_CALL(*_mock_index_file_reader, init(testing::_, testing::_))
             .WillOnce(testing::Return(Status::IOError("Init failed")));
 
     io::IOContext io_ctx;
-    Status status = reader->load_index(&io_ctx);
-    EXPECT_FALSE(status.ok());
+    EXPECT_FALSE(reader->load_index(&io_ctx).ok());
+    // The retained initialization failure must retire the owning ColumnReader
+    // so a later query can retry loading ANN with a new reader.
+    EXPECT_FALSE(reader->healthy_status().ok());
+    EXPECT_FALSE(column_reader->healthy_status().ok());
+    EXPECT_TRUE(column_reader->_healthy_status.status().ok());
+    EXPECT_FALSE(reader->load_index(&io_ctx).ok());
 }
 
 TEST_F(AnnIndexReaderTest, TestLoadIndexFailureOpen) {
diff --git a/be/test/storage/segment/column_reader_cache_test.cpp 
b/be/test/storage/segment/column_reader_cache_test.cpp
index 61a8b3f9424..1ef890521f6 100644
--- a/be/test/storage/segment/column_reader_cache_test.cpp
+++ b/be/test/storage/segment/column_reader_cache_test.cpp
@@ -21,8 +21,10 @@
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 
+#include <barrier>
 #include <chrono>
 #include <memory>
+#include <new>
 #include <string>
 #include <thread>
 #include <vector>
@@ -33,12 +35,15 @@
 #include "core/data_type/data_type_nullable.h"
 #include "io/fs/file_reader.h"
 #include "io/fs/local_file_system.h"
+#include "storage/index/bloom_filter/bloom_filter_index_reader.h"
 #include "storage/segment/column_meta_accessor.h"
 #include "storage/segment/column_reader.h"
 #include "storage/segment/encoding_info.h"
 #include "storage/segment/mock/mock_segment.h"
 #include "storage/segment/segment.h"
 #include "storage/segment/segment_writer.h"
+#include "storage/segment/variant/binary_column_reader.h"
+#include "storage/segment/variant/nested_group_reader.h"
 #include "storage/segment/variant/variant_column_reader.h"
 #include "storage/tablet/tablet_schema.h"
 #include "util/coding.h"
@@ -83,6 +88,15 @@ private:
     FieldType _type;
 };
 
+class HealthCheckingColumnReader : public MockColumnReader {
+public:
+    HealthCheckingColumnReader() : MockColumnReader(1) {}
+    Status healthy_status() const override {
+        return check ? check() : ColumnReader::healthy_status();
+    }
+    std::function<Status()> check;
+};
+
 class ColumnReaderCacheTest : public ::testing::Test {
 protected:
     // EncodingInfo friended ColumnReaderCacheTest so the fixture can pick a 
valid V2
@@ -229,6 +243,291 @@ TEST_F(ColumnReaderCacheTest, BasicCacheOperations) {
     EXPECT_EQ(readers[1], reader);
 }
 
+// A first lazy-load failure must not be returned by all subsequent cache hits.
+TEST_F(ColumnReaderCacheTest, RebuildAfterOrdinalLoadFailure) {
+    setup_column_uid_mapping(1, 0);
+    ColumnMetaPB meta;
+    meta.set_type(static_cast<int32_t>(FieldType::OLAP_FIELD_TYPE_INT));
+    meta.set_unique_id(1);
+    meta.set_encoding(get_v2_default_encoding(FieldType::OLAP_FIELD_TYPE_INT));
+    auto* index = meta.add_indexes();
+    index->set_type(ORDINAL_INDEX);
+    
index->mutable_ordinal_index()->mutable_root_page()->set_is_root_data_page(true);
+    setup_segment_footer({meta});
+
+    std::shared_ptr<ColumnReader> failed;
+    ASSERT_TRUE(_cache->get_column_reader(1, &failed, &_stats).ok());
+    // Seed the retained result of a failed index read, then exercise the 
actual
+    // ColumnReader loading entry point used by point reads and prefetch.
+    ASSERT_FALSE(failed->_ordinal_index->_load_once
+                         .call([] { return Status::IOError("injected ordinal 
read failure"); })
+                         .ok());
+    OrdinalIndexReader* ordinal = nullptr;
+    EXPECT_FALSE(failed->get_ordinal_index_reader(ordinal, &_stats).ok());
+    EXPECT_FALSE(failed->healthy_status().ok());
+
+    std::shared_ptr<ColumnReader> replacement;
+    ASSERT_TRUE(_cache->get_column_reader(1, &replacement, &_stats).ok());
+    ASSERT_NE(failed, replacement);
+    EXPECT_TRUE(replacement->healthy_status().ok());
+    EXPECT_TRUE(replacement->get_ordinal_index_reader(ordinal, &_stats).ok());
+    EXPECT_NE(ordinal, nullptr);
+
+    // Late use of an old shared_ptr must not poison or remove its replacement.
+    EXPECT_FALSE(failed->get_ordinal_index_reader(ordinal, &_stats).ok());
+    std::shared_ptr<ColumnReader> cached;
+    ASSERT_TRUE(_cache->get_column_reader(1, &cached, &_stats).ok());
+    EXPECT_EQ(cached, replacement);
+    EXPECT_EQ(_cache->_lru_list.size(), 1);
+    EXPECT_EQ(_cache->_cache_map.size(), 1);
+}
+
+TEST_F(ColumnReaderCacheTest, IndexExceptionsInvalidateReader) {
+    setup_column_uid_mapping(1, 0);
+    ColumnMetaPB meta;
+    meta.set_type(static_cast<int32_t>(FieldType::OLAP_FIELD_TYPE_INT));
+    meta.set_unique_id(1);
+    meta.set_encoding(get_v2_default_encoding(FieldType::OLAP_FIELD_TYPE_INT));
+    meta.add_indexes()->set_type(ORDINAL_INDEX);
+    setup_segment_footer({meta});
+
+    for (bool doris_exception : {true, false}) {
+        std::shared_ptr<ColumnReader> failed;
+        ASSERT_TRUE(_cache->get_column_reader(1, &failed, &_stats).ok());
+        auto throw_failure = [&]() -> Status {
+            if (doris_exception) {
+                throw doris::Exception(ErrorCode::MEM_LIMIT_EXCEEDED,
+                                       "injected allocation failure");
+            }
+            throw std::bad_alloc();
+        };
+        
EXPECT_ANY_THROW(static_cast<void>(failed->_ordinal_index->_load_once.call(throw_failure)));
+        ColumnIteratorOptions options;
+        options.stats = &_stats;
+        if (doris_exception) {
+            EXPECT_THROW(static_cast<void>(failed->_load_ordinal_index(false, 
false, options)),
+                         doris::Exception);
+            
EXPECT_TRUE(failed->healthy_status().is<ErrorCode::MEM_LIMIT_EXCEEDED>());
+        } else {
+            EXPECT_THROW(static_cast<void>(failed->_load_ordinal_index(false, 
false, options)),
+                         std::bad_alloc);
+            
EXPECT_TRUE(failed->healthy_status().is<ErrorCode::INTERNAL_ERROR>());
+        }
+        EXPECT_TRUE(_cache->get_available_readers(false).empty());
+        EXPECT_TRUE(_cache->_lru_list.empty());
+        EXPECT_TRUE(_cache->_cache_map.empty());
+    }
+}
+
+TEST_F(ColumnReaderCacheTest, ZoneMapAndBloomFilterFailuresInvalidateReader) {
+    setup_column_uid_mapping(1, 0);
+    ColumnMetaPB meta;
+    meta.set_type(static_cast<int32_t>(FieldType::OLAP_FIELD_TYPE_INT));
+    meta.set_unique_id(1);
+    meta.set_encoding(get_v2_default_encoding(FieldType::OLAP_FIELD_TYPE_INT));
+    meta.add_indexes()->set_type(ORDINAL_INDEX);
+    meta.add_indexes()->set_type(ZONE_MAP_INDEX);
+    meta.add_indexes()->set_type(BLOOM_FILTER_INDEX);
+    setup_segment_footer({meta});
+    ColumnIteratorOptions options;
+    options.stats = &_stats;
+
+    std::shared_ptr<ColumnReader> zone_reader;
+    ASSERT_TRUE(_cache->get_column_reader(1, &zone_reader, &_stats).ok());
+    ASSERT_FALSE(zone_reader->_zone_map_index->_load_once
+                         .call([] { return Status::IOError("injected zone map 
failure"); })
+                         .ok());
+    EXPECT_FALSE(zone_reader->_load_zone_map_index(false, false, 
options).ok());
+    EXPECT_FALSE(zone_reader->healthy_status().ok());
+
+    std::shared_ptr<ColumnReader> bloom_reader;
+    ASSERT_TRUE(_cache->get_column_reader(1, &bloom_reader, &_stats).ok());
+    EXPECT_NE(zone_reader, bloom_reader);
+    ASSERT_FALSE(bloom_reader->_bloom_filter_index->_load_once
+                         .call([] {
+                             return Status::MemoryLimitExceeded("injected 
bloom filter failure");
+                         })
+                         .ok());
+    EXPECT_FALSE(bloom_reader->_load_bloom_filter_index(false, false, 
options).ok());
+    EXPECT_FALSE(bloom_reader->healthy_status().ok());
+    EXPECT_TRUE(_cache->get_available_readers(false).empty());
+}
+
+TEST_F(ColumnReaderCacheTest, ChildFailureInvalidatesCachedParentAndPath) {
+    ColumnMetaPB meta;
+    meta.set_type(static_cast<int32_t>(FieldType::OLAP_FIELD_TYPE_ARRAY));
+    for (auto type : {FieldType::OLAP_FIELD_TYPE_INT, 
FieldType::OLAP_FIELD_TYPE_UNSIGNED_BIGINT}) {
+        auto* child = meta.add_children_columns();
+        child->set_type(static_cast<int32_t>(type));
+        child->set_num_rows(10);
+        child->set_encoding(get_v2_default_encoding(type));
+        child->add_indexes()->set_type(ORDINAL_INDEX);
+    }
+    ColumnReaderOptions options;
+    std::shared_ptr<ColumnReader> parent;
+    ASSERT_TRUE(ColumnReader::create(options, meta, 10, nullptr, 
&parent).ok());
+    auto child = parent->_sub_readers[0];
+    auto ancestor = std::make_shared<MockColumnReader>(1);
+    ancestor->_sub_readers.push_back(parent);
+    // Reusing the same options must not couple independent reader trees.
+    std::shared_ptr<ColumnReader> same_options_reader;
+    ASSERT_TRUE(ColumnReader::create(options, meta, 10, nullptr, 
&same_options_reader).ok());
+    _cache->_insert_direct({1, {}}, ancestor);
+    _cache->_insert_direct({1, PathInData("element")}, child);
+    auto independent = std::make_shared<MockColumnReader>(2);
+    _cache->_insert_direct({2, {}}, independent);
+
+    ASSERT_FALSE(child->_ordinal_index->_load_once
+                         .call([] { return Status::IOError("injected child 
index failure"); })
+                         .ok());
+    OrdinalIndexReader* ordinal = nullptr;
+    EXPECT_FALSE(child->get_ordinal_index_reader(ordinal, &_stats).ok());
+    EXPECT_FALSE(parent->healthy_status().ok());
+    EXPECT_FALSE(ancestor->healthy_status().ok());
+    EXPECT_TRUE(parent->_healthy_status.status().ok());
+    EXPECT_TRUE(ancestor->_healthy_status.status().ok());
+    EXPECT_TRUE(parent->_sub_readers[1]->healthy_status().ok());
+    EXPECT_TRUE(same_options_reader->healthy_status().ok());
+    EXPECT_EQ(_cache->_lookup({1, PathInData("element")}), nullptr);
+    EXPECT_EQ(_cache->_lookup({1, {}}), nullptr);
+    EXPECT_EQ(_cache->_lookup({2, {}}), independent);
+    EXPECT_TRUE(independent->healthy_status().ok());
+    EXPECT_EQ(_cache->_lru_list.size(), 1);
+}
+
+TEST_F(ColumnReaderCacheTest, ParentFailureDoesNotPoisonChildren) {
+    auto parent = std::make_shared<MockColumnReader>(1);
+    auto child = std::make_shared<MockColumnReader>(2);
+    parent->_sub_readers.push_back(child);
+    parent->_healthy_status.update(Status::IOError("parent initialization 
failed"));
+    EXPECT_FALSE(parent->healthy_status().ok());
+    EXPECT_TRUE(child->healthy_status().ok());
+}
+
+TEST_F(ColumnReaderCacheTest, VariantHealthChecksAllOwnedReaderTrees) {
+    auto make_variant = [] {
+        auto reader = std::make_shared<VariantColumnReader>();
+        reader->_root_column_reader = std::make_shared<MockColumnReader>(1);
+        reader->_binary_column_reader = 
std::make_shared<DummyBinaryColumnReader>();
+        reader->_nested_group_readers.emplace("absent", nullptr);
+        reader->_nested_group_readers.emplace("invalid", 
std::make_unique<NestedGroupReader>());
+        return reader;
+    };
+    auto variant = make_variant();
+    EXPECT_TRUE(variant->healthy_status().ok());
+    variant->_root_column_reader->_healthy_status.update(Status::IOError("root 
failed"));
+    EXPECT_FALSE(variant->healthy_status().ok());
+    EXPECT_TRUE(variant->_healthy_status.status().ok());
+
+    for (bool bucketed : {false, true}) {
+        variant = make_variant();
+        auto binary = std::make_shared<MockColumnReader>(2);
+        if (bucketed) {
+            variant->_binary_column_reader = 
std::make_shared<MultipleDocColumnReader>();
+        } else {
+            variant->_binary_column_reader = 
std::make_shared<SingleSparseColumnReader>();
+        }
+        
ASSERT_TRUE(variant->_binary_column_reader->add_binary_column_reader(binary, 
0).ok());
+        EXPECT_TRUE(variant->healthy_status().ok());
+        binary->_healthy_status.update(Status::IOError("binary reader 
failed"));
+        EXPECT_FALSE(variant->healthy_status().ok());
+        EXPECT_TRUE(variant->_healthy_status.status().ok());
+        EXPECT_TRUE(variant->_root_column_reader->healthy_status().ok());
+    }
+
+    for (bool offsets_failure : {false, true}) {
+        variant = make_variant();
+        auto group = std::make_unique<NestedGroupReader>();
+        group->offsets_reader = std::make_shared<MockColumnReader>(3);
+        auto nested = std::make_unique<NestedGroupReader>();
+        auto offsets = std::make_shared<MockColumnReader>(4);
+        auto child = std::make_shared<MockColumnReader>(5);
+        nested->offsets_reader = offsets;
+        nested->child_readers.emplace("value", child);
+        nested->child_readers.emplace("absent", nullptr);
+        group->nested_group_readers.emplace("nested", std::move(nested));
+        variant->_nested_group_readers.emplace("array", std::move(group));
+        EXPECT_TRUE(variant->healthy_status().ok());
+        (offsets_failure ? offsets : child)
+                ->_healthy_status.update(Status::IOError("nested-group 
descendant failed"));
+        EXPECT_FALSE(variant->healthy_status().ok());
+        EXPECT_TRUE(variant->_healthy_status.status().ok());
+        EXPECT_TRUE(variant->_root_column_reader->healthy_status().ok());
+    }
+}
+
+TEST_F(ColumnReaderCacheTest, 
RecursiveChecksReleaseCacheLockAndPreserveReplacement) {
+    for (bool enumerate : {false, true}) {
+        auto old = std::make_shared<HealthCheckingColumnReader>();
+        _cache->_insert_direct({1, {}}, old);
+        auto replacement = std::make_shared<MockColumnReader>(1);
+        bool replaced = false;
+        old->check = [&]() -> Status {
+            bool unlocked = false;
+            std::thread probe([&] {
+                std::unique_lock lock(_cache->_cache_mutex, std::try_to_lock);
+                unlocked = lock.owns_lock();
+            });
+            probe.join();
+            EXPECT_TRUE(unlocked);
+            if (!unlocked) {
+                return Status::IOError("health checked under cache lock");
+            }
+            // Simulate another caller replacing the old instance while the
+            // outer lookup/enumeration is checking its health without the 
lock.
+            if (!std::exchange(replaced, true)) {
+                EXPECT_EQ(_cache->_insert_direct({1, {}}, replacement), 
replacement);
+            }
+            return Status::IOError("old reader failed");
+        };
+        if (enumerate) {
+            EXPECT_TRUE(_cache->get_available_readers(false).empty());
+        } else {
+            EXPECT_EQ(_cache->_lookup({1, {}}), nullptr);
+        }
+        EXPECT_TRUE(replaced);
+        EXPECT_EQ(_cache->_lookup({1, {}}), replacement);
+        EXPECT_EQ(_cache->_cache_map.size(), 1);
+        EXPECT_EQ(_cache->_lru_list.size(), 1);
+        // Each iteration starts from an empty cache.
+        _cache->_erase_if_same({1, {}}, replacement);
+    }
+}
+
+TEST_F(ColumnReaderCacheTest, ConcurrentReplacementsKeepOneCacheEntry) {
+    auto failed = std::make_shared<MockColumnReader>(1);
+    _cache->_insert_direct({1, {}}, failed);
+    failed->_healthy_status.update(Status::IOError("injected failure"));
+    constexpr int threads_count = 8;
+    std::barrier ready(threads_count);
+    std::vector<std::shared_ptr<ColumnReader>> readers(threads_count);
+    std::vector<std::thread> threads;
+    for (int i = 0; i < threads_count; ++i) {
+        threads.emplace_back([&, i] {
+            EXPECT_EQ(_cache->_lookup({1, {}}), nullptr);
+            auto candidate = std::make_shared<MockColumnReader>(1);
+            // All callers have missed before any publishes a replacement.
+            ready.arrive_and_wait();
+            readers[i] = _cache->_insert_direct({1, {}}, candidate);
+            EXPECT_EQ(readers[i], candidate);
+        });
+    }
+    for (auto& thread : threads) {
+        thread.join();
+    }
+    auto cached = _cache->_lookup({1, {}});
+    ASSERT_NE(cached, nullptr);
+    bool cached_is_candidate = false;
+    for (const auto& reader : readers) {
+        EXPECT_NE(reader, failed);
+        EXPECT_TRUE(reader->healthy_status().ok());
+        cached_is_candidate |= (cached == reader);
+    }
+    EXPECT_TRUE(cached_is_candidate);
+    EXPECT_EQ(_cache->_lru_list.size(), 1);
+    EXPECT_EQ(_cache->_cache_map.size(), 1);
+}
+
 // Test LRU eviction
 TEST_F(ColumnReaderCacheTest, LRUEviction) {
     // Set cache size to 2
diff --git a/be/test/storage/segment/external_col_meta_util_test.cpp 
b/be/test/storage/segment/external_col_meta_util_test.cpp
index 6c1d51bd9bf..35d32460dc8 100644
--- a/be/test/storage/segment/external_col_meta_util_test.cpp
+++ b/be/test/storage/segment/external_col_meta_util_test.cpp
@@ -33,6 +33,7 @@
 #include "io/fs/local_file_system.h"
 #include "io/io_common.h"
 #include "storage/segment/column_meta_accessor.h"
+#include "storage/segment/column_reader_cache.h"
 #include "storage/segment/segment.h"
 #include "storage/segment/segment_writer.h"
 #include "storage/segment/variant/variant_column_reader.h"
@@ -445,7 +446,7 @@ TEST(ExternalColMetaUtilTest, 
VariantExtMetaWriterAndReaderInteropAndCompatibili
     EXPECT_TRUE(has);
 }
 
-TEST(ExternalColMetaUtilTest, 
VariantColumnReaderRetriesExternalMetaAfterPageAllocationFailure) {
+TEST(ExternalColMetaUtilTest, 
VariantColumnReaderRebuiltAfterPageAllocationFailure) {
     SegmentFooterPB footer;
     footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
     const int32_t root_uid = 1;
@@ -551,27 +552,40 @@ TEST(ExternalColMetaUtilTest, 
VariantColumnReaderRetriesExternalMetaAfterPageAll
     column_opts.tablet_schema->append_column(std::move(tablet_column));
     ColumnMetaAccessor accessor;
     ASSERT_TRUE(accessor.init(*footer_sp, recording_fr).ok());
-    VariantColumnReader variant_reader;
-    st = variant_reader.init(column_opts, &accessor, footer_sp, root_uid, 
footer.num_rows(),
-                             recording_fr, &reader_stats, &io_ctx);
-    ASSERT_TRUE(st.ok()) << st;
+    ColumnReaderCache cache(&accessor, column_opts.tablet_schema, 
recording_fr, footer.num_rows(),
+                            [&](std::shared_ptr<SegmentFooterPB>& out, 
OlapReaderStatistics*,
+                                const io::IOContext*) {
+                                out = footer_sp;
+                                return Status::OK();
+                            });
+    std::shared_ptr<ColumnReader> cached;
+    ASSERT_TRUE(cache.get_column_reader(root_uid, &cached, &reader_stats, 
&io_ctx).ok());
+    auto failed = std::static_pointer_cast<VariantColumnReader>(cached);
 
     reset_recording("#load_external_meta_once");
     const PathInData key_path("key0");
     recording_fr->fail_next_read_with_allocation_error();
-    st = variant_reader.load_external_meta_once(&reader_stats, &io_ctx);
+    st = failed->load_external_meta_once(&reader_stats, &io_ctx);
     ASSERT_TRUE(st.is<ErrorCode::MEM_LIMIT_EXCEEDED>()) << st;
+    EXPECT_FALSE(failed->healthy_status().ok());
     expect_recorded_reads_with_limiter("failed load_external_meta_once");
-    EXPECT_EQ(variant_reader.get_subcolumn_meta_by_path(key_path), nullptr);
+    EXPECT_EQ(failed->get_subcolumn_meta_by_path(key_path), nullptr);
+    EXPECT_FALSE(failed->load_external_meta_once(&reader_stats, &io_ctx).ok());
+    EXPECT_TRUE(recording_fr->records().empty());
 
-    st = variant_reader.load_external_meta_once(&reader_stats, &io_ctx);
+    ASSERT_TRUE(cache.get_column_reader(root_uid, &cached, &reader_stats, 
&io_ctx).ok());
+    auto replacement = std::static_pointer_cast<VariantColumnReader>(cached);
+    ASSERT_NE(failed, replacement);
+    ASSERT_TRUE(replacement->healthy_status().ok());
+    st = replacement->load_external_meta_once(&reader_stats, &io_ctx);
     ASSERT_TRUE(st.ok()) << st.to_json();
     expect_recorded_reads_with_limiter("load_external_meta_once");
-    EXPECT_NE(variant_reader.get_subcolumn_meta_by_path(key_path), nullptr);
-    EXPECT_EQ(variant_reader.get_stats()->subcolumns_non_null_size.at("key0"), 
123);
+    EXPECT_NE(replacement->get_subcolumn_meta_by_path(key_path), nullptr);
+    EXPECT_EQ(replacement->get_stats()->subcolumns_non_null_size.at("key0"), 
123);
 
-    ASSERT_TRUE(variant_reader.load_external_meta_once(&reader_stats, 
&io_ctx).ok());
+    ASSERT_TRUE(replacement->load_external_meta_once(&reader_stats, 
&io_ctx).ok());
     EXPECT_TRUE(recording_fr->records().empty());
+    EXPECT_FALSE(failed->healthy_status().ok());
 
     bool has = false;
     reset_recording("#has_prefix");


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

Reply via email to