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

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


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new 0f0366b4101 [improvement](index) Surface ANN load errors and unify 
missing-index fallback (branch-4.1) (#70906)
0f0366b4101 is described below

commit 0f0366b41019cd049575174606101ff6cc994070
Author: yiguolei <[email protected]>
AuthorDate: Tue Dec 1 09:36:03 2026 +0800

    [improvement](index) Surface ANN load errors and unify missing-index 
fallback (branch-4.1) (#70906)
    
    Backport of #70788 to `branch-4.1`, based on source head
    `c51dfbd5aeed1ce22427e38808291e05ed0832c8`.
    
    ### Background
    
    ANN indexes accelerate vector TopN and range predicates. Segments
    without index data can still evaluate these predicates by scanning their
    vectors. ANN and inverted indexes share the container reader, and
    legitimate empty containers can arise from small ANN segments or
    all-NULL VARIANT columns.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #70788
    PR Type: Enhancement
    
    Problem Summary:
    
    ANN loading currently converts every returned failure into brute-force
    fallback, hiding I/O and memory errors. Use explicit statuses so only a
    missing index permits fallback, and classify empty legacy containers as
    missing index data. Most added lines test this boundary and its callers.
    After upgrading, ANN queries expose other loading failures instead of
    silently scanning.
    
    ### Details
    
    - **Change map:** Production code +26/-32; tests +284/-30 across 14
    files. Tests cover load-status propagation, both ANN consumers and empty
    containers using the existing branch-4.1 compound-directory interface.
    - **Before and after:** A single Status-returning `load_index` API
    replaces `try_load_index`. TopN and range fall back only for
    `INVERTED_INDEX_FILE_NOT_FOUND`. Empty V2/V3 containers now return that
    code rather than `INVERTED_INDEX_BYPASS`; missing internal Faiss files
    remain errors.
    - **Configs and defaults:** No new settings or default changes. Inverted
    predicates encountering empty containers now follow
    `enable_fallback_on_missing_inverted_index`, whose default remains true.
    - **Impact on existing users:** ANN loading failures other than missing
    indexes now fail the query. Inverted predicates with the fallback
    setting disabled now fail on empty containers too; the default still
    allows fallback. Empty-container diagnostics change from E-6004 to
    E-6003 while retaining `is empty`; downgrade logging changes from DEBUG
    to INFO. Persisted formats and SQL syntax are unchanged.
    - **Behavior change:** Missing and empty containers use the
    missing-index policy; unrelated loading failures remain visible.
    
    ### Testing
    
    - Builds, unit tests, regression tests and clang-tidy were not run for
    this backport, following the author's preference. Historical results in
    #70788 do not validate this branch.
    - Changed C++ lines were formatted and checked with clang-format 16;
    `git diff --check` passed.
    - Static self-review checked the release-branch interfaces, ANN
    TopN/range callers, compound-directory lifetime, and missing internal
    Faiss file handling. This is not runtime validation.
    - The new `AnnIndexLoadTest` cases cover init/open failures, cached
    failed loads, missing-only TopN/range fallback, a real empty V2
    container, null readers and missing internal files for
    HNSW/IVF/IVF_ON_DISK. Existing empty-container, reader, index-builder
    and lifecycle/VARIANT expectations are updated.
    - The branch does not contain `build-support/check-build-hygiene.sh`;
    that gate was not run.
    
    ### Notes for Reviewers
    
    - Preserve branch-4.1's `IndexFileReader::open`, CLucene exception
    handling, `_compound_dir` ownership and existing Faiss load signature.
    Do not backport the ANN storage abstraction from #70270.
    - This branch already returns `INVERTED_INDEX_FILE_NOT_FOUND` for an
    absent logical index. It has no SNII status/interface, so the
    master-only SNII normalization and injected case are omitted.
    - Adapt fixtures to `Schema`, the two-argument `SegmentIterator`
    constructor, `_opts.stats`, `idx_to_cid` and `_need_read_data_indices`.
    - Omit the comment-only change to `ann_index_range_read_test.cpp`, which
    does not exist on branch-4.1 and depends on newer storage changes.
    - Removing the BE_TEST loading shortcut lets tests exercise the real
    loader. Search-only mocks explicitly model successful loading. Missing
    files inside an existing ANN index remain errors.
    - Empty-container regression assertions retain the distinction between
    existing empty files and absent files through the diagnostic message.
    
    ### Release note
    
    ANN queries fall back when index data is absent but now report other
    loading failures. Empty V2/V3 containers follow the missing-index
    policy, including the inverted-index fallback setting, and report
    diagnostic code E-6003.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: Yes (plan: document ANN missing-only
    fallback and empty-container interaction with
    enable_fallback_on_missing_inverted_index in apache/doris-website)
    - Pre-submission status: Partially verified: static inspection and
    changed-line formatting passed; this backport has not been compiled or
    tested, and clang-tidy has not run.
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6).
    - Generated: Backport conflict resolution, release-branch test
    adaptations, static self-review and this description; implementation and
    original tests come from #70788.
    - Human review: The author directed preserving branch-4.1 interfaces and
    authorized adaptation and PR submission; extent of full code review not
    stated.
---
 be/src/exprs/vectorized_fn_call.cpp                |  10 +-
 be/src/storage/index/ann/ann_index_iterator.cpp    |   8 +-
 be/src/storage/index/ann/ann_index_iterator.h      |   5 +-
 be/src/storage/index/ann/ann_index_reader.cpp      |  16 +-
 be/src/storage/index/ann/ann_index_reader.h        |   5 +-
 be/src/storage/index/index_file_reader.cpp         |   4 +-
 be/src/storage/segment/segment_iterator.cpp        |  10 +-
 be/test/storage/index/ann/ann_index_load_test.cpp  | 227 +++++++++++++++++++++
 be/test/storage/index/ann/vector_search_utils.h    |   7 +-
 be/test/storage/index/index_builder_test.cpp       |  10 +-
 .../index/inverted/empty_index_file_test.cpp       |  34 ++-
 .../segment/inverted_index_file_reader_test.cpp    |   4 +-
 .../test_empty_index_file_lifecycle.groovy         |  28 +--
 .../test_variant_empty_index_file.groovy           |   6 +-
 14 files changed, 312 insertions(+), 62 deletions(-)

diff --git a/be/src/exprs/vectorized_fn_call.cpp 
b/be/src/exprs/vectorized_fn_call.cpp
index a7809906147..2c8410880fa 100644
--- a/be/src/exprs/vectorized_fn_call.cpp
+++ b/be/src/exprs/vectorized_fn_call.cpp
@@ -976,12 +976,16 @@ Status VectorizedFnCall::evaluate_ann_range_search(
     // Track load index timing
     {
         SCOPED_TIMER(&(stats->load_index_costs_ns));
-        if (!ann_index_iterator->try_load_index()) {
-            VLOG_DEBUG << "ANN range search skipped: "
-                       << fmt::format("Failed to load ANN index for column cid 
{}", src_col_cid);
+        Status load_status = ann_index_iterator->load_index();
+        // A segment without the ANN index still evaluates this predicate on 
its vectors.
+        // Other load failures must not silently turn into a brute-force range 
search.
+        if (load_status.is<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>()) {
+            VLOG_DEBUG << "ANN range search skipped: index is missing for 
column cid "
+                       << src_col_cid << ": " << load_status;
             ann_index_stats.fall_back_brute_force_cnt += 1;
             return Status::OK();
         }
+        RETURN_IF_ERROR(load_status);
         double load_costs_ms = 
static_cast<double>(stats->load_index_costs_ns.value()) / 1000000.0;
         DorisMetrics::instance()->ann_index_load_costs_ms->increment(
                 static_cast<int64_t>(load_costs_ms));
diff --git a/be/src/storage/index/ann/ann_index_iterator.cpp 
b/be/src/storage/index/ann/ann_index_iterator.cpp
index fc622f69857..8aeea43b655 100644
--- a/be/src/storage/index/ann/ann_index_iterator.cpp
+++ b/be/src/storage/index/ann/ann_index_iterator.cpp
@@ -27,15 +27,15 @@ AnnIndexIterator::AnnIndexIterator(const IndexReaderPtr& 
reader) : IndexIterator
     _ann_reader = std::dynamic_pointer_cast<AnnIndexReader>(reader);
 }
 
-bool AnnIndexIterator::try_load_index() {
+Status AnnIndexIterator::load_index() {
+    // An iterator without its reader is invalid, not a segment whose index 
has not been built.
     if (_ann_reader == nullptr) {
-        LOG(WARNING) << "AnnIndexIterator::try_load_index: _ann_reader is 
null";
-        return false;
+        return Status::Error<ErrorCode::INDEX_INVALID_PARAMETERS>("_ann_reader 
is null");
     }
 
     // _context may be unset in some test scenarios; pass nullptr IOContext in 
that case.
     io::IOContext* io_ctx = (_context != nullptr) ? _context->io_ctx : nullptr;
-    return _ann_reader->try_load_index(io_ctx);
+    return _ann_reader->load_index(io_ctx);
 }
 
 Status AnnIndexIterator::read_from_index(const IndexParam& param) {
diff --git a/be/src/storage/index/ann/ann_index_iterator.h 
b/be/src/storage/index/ann/ann_index_iterator.h
index d0e27a719e8..c98b11d72da 100644
--- a/be/src/storage/index/ann/ann_index_iterator.h
+++ b/be/src/storage/index/ann/ann_index_iterator.h
@@ -44,9 +44,8 @@ public:
 
     Result<bool> has_null() override { return true; }
 
-    // Try to load index, return true if successful, false if failed
-    // This method should be called before read_from_index or range_search
-    bool try_load_index();
+    // Load before searching; callers decide whether a missing index permits 
fallback.
+    MOCK_FUNCTION Status load_index();
 
     MOCK_FUNCTION Status range_search(const AnnRangeSearchParams& params,
                                       const VectorSearchUserParams& 
custom_params,
diff --git a/be/src/storage/index/ann/ann_index_reader.cpp 
b/be/src/storage/index/ann/ann_index_reader.cpp
index 80850c65901..db905866c8c 100644
--- a/be/src/storage/index/ann/ann_index_reader.cpp
+++ b/be/src/storage/index/ann/ann_index_reader.cpp
@@ -65,8 +65,8 @@ Status AnnIndexReader::load_index(io::IOContext* io_ctx) {
                     
_index_file_reader->init(config::inverted_index_read_buffer_size, io_ctx));
             auto compound_dir = _index_file_reader->open(&_index_meta, io_ctx);
             if (!compound_dir.has_value()) {
-                return Status::IOError("Failed to open index file: {}",
-                                       compound_dir.error().to_string());
+                // Keep logical-index absence distinguishable from other open 
failures.
+                return compound_dir.error();
             }
             _vector_index = std::make_unique<FaissVectorIndex>();
             _vector_index->set_metric(_metric_type);
@@ -94,18 +94,6 @@ Status AnnIndexReader::load_index(io::IOContext* io_ctx) {
     });
 }
 
-bool AnnIndexReader::try_load_index(io::IOContext* io_ctx) {
-#ifndef BE_TEST
-    Status st = load_index(io_ctx);
-    if (!st.ok()) {
-        LOG_WARNING("Failed to load ann index, will fallback to brute force 
search: {}",
-                    st.to_string());
-        return false;
-    }
-#endif
-    return true;
-}
-
 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 a170c962dcc..8df48a7c094 100644
--- a/be/src/storage/index/ann/ann_index_reader.h
+++ b/be/src/storage/index/ann/ann_index_reader.h
@@ -42,12 +42,9 @@ public:
                    std::shared_ptr<IndexFileReader> index_file_reader);
     ~AnnIndexReader() override = default;
 
+    // Only INVERTED_INDEX_FILE_NOT_FOUND permits the caller to fall back to a 
scan.
     Status load_index(io::IOContext* io_ctx);
 
-    // Try to load index, return true if successful, false if failed
-    // This method is used to check if index can be loaded before query
-    bool try_load_index(io::IOContext* io_ctx);
-
     Status query(io::IOContext* io_ctx, AnnTopNParam* param, AnnIndexStats* 
stats);
 
     Status range_search(const AnnRangeSearchParams& params,
diff --git a/be/src/storage/index/index_file_reader.cpp 
b/be/src/storage/index/index_file_reader.cpp
index ce2a4f1347f..b2cf8202b3a 100644
--- a/be/src/storage/index/index_file_reader.cpp
+++ b/be/src/storage/index/index_file_reader.cpp
@@ -71,7 +71,9 @@ Status IndexFileReader::_init_from(int32_t read_buffer_size, 
const io::IOContext
                 return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
                         "inverted index file {} is not found.", 
index_file_full_path);
             } else if (err.number() == CL_ERR_EmptyIndexSegment) {
-                return Status::Error<ErrorCode::INVERTED_INDEX_BYPASS>(
+                // Small ANN segments and all-NULL VARIANT columns can 
legitimately leave an
+                // empty container. It has no index data, so use the 
missing-index fallback policy.
+                return Status::Error<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>(
                         "inverted index file {} is empty.", 
index_file_full_path);
             }
             return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
diff --git a/be/src/storage/segment/segment_iterator.cpp 
b/be/src/storage/segment/segment_iterator.cpp
index b494a95e05c..a29a9b60093 100644
--- a/be/src/storage/segment/segment_iterator.cpp
+++ b/be/src/storage/segment/segment_iterator.cpp
@@ -961,7 +961,7 @@ Status SegmentIterator::_apply_ann_topn_predicate() {
     std::shared_ptr<std::vector<uint64_t>> result_row_ids;
     segment_v2::AnnIndexStats ann_index_stats;
 
-    // Try to load ANN index before search
+    // Load ANN index before search
     auto ann_index_iterator_casted =
             dynamic_cast<segment_v2::AnnIndexIterator*>(ann_index_iterator);
     if (ann_index_iterator_casted == nullptr) {
@@ -974,12 +974,16 @@ Status SegmentIterator::_apply_ann_topn_predicate() {
     // Track load index timing
     {
         SCOPED_TIMER(&(ann_index_stats.load_index_costs_ns));
-        if (!ann_index_iterator_casted->try_load_index()) {
-            VLOG_DEBUG << "Failed to load ANN index, fallback to brute force 
search";
+        Status load_status = ann_index_iterator_casted->load_index();
+        // Old segments may not have a newly added ANN index yet. Only absence 
permits a scan;
+        // IO, memory and invalid-index failures must reach the caller.
+        if (load_status.is<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>()) {
+            VLOG_DEBUG << "ANN index is missing, fallback to brute force 
search: " << load_status;
             _need_read_data_indices[src_cid] = true;
             _opts.stats->ann_fall_back_brute_force_cnt += 1;
             return Status::OK();
         }
+        RETURN_IF_ERROR(load_status);
         double load_costs_ms =
                 
static_cast<double>(ann_index_stats.load_index_costs_ns.value()) / 1000000.0;
         DorisMetrics::instance()->ann_index_load_costs_ms->increment(
diff --git a/be/test/storage/index/ann/ann_index_load_test.cpp 
b/be/test/storage/index/ann/ann_index_load_test.cpp
new file mode 100644
index 00000000000..2852d862ec9
--- /dev/null
+++ b/be/test/storage/index/ann/ann_index_load_test.cpp
@@ -0,0 +1,227 @@
+// 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 <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <vector>
+
+#include "exprs/vectorized_fn_call.h"
+#include "io/fs/local_file_system.h"
+#include "storage/index/ann/ann_range_search_runtime.h"
+#include "storage/index/ann/ann_topn_runtime.h"
+#include "storage/index/ann/vector_search_utils.h"
+#include "storage/index/index_file_writer.h"
+#include "storage/index/inverted/inverted_index_desc.h"
+#include "storage/schema.h"
+#include "storage/segment/column_reader.h"
+#include "storage/segment/segment.h"
+#include "storage/segment/segment_iterator.h"
+
+namespace doris::segment_v2 {
+
+using vector_search_utils::MockIndexFileReader;
+
+class AnnIndexLoadTest : public VectorSearchTest, public 
testing::WithParamInterface<int> {
+protected:
+    void SetUp() override {
+        VectorSearchTest::SetUp();
+        _meta._index_id = 1;
+        _meta._properties = {{"index_type", "hnsw"}, {"metric_type", 
"l2_distance"}, {"dim", "4"}};
+        _file_reader = std::make_shared<MockIndexFileReader>();
+        _reader = std::make_shared<AnnIndexReader>(&_meta, _file_reader);
+    }
+
+    void expect_open_failure() {
+        EXPECT_CALL(*_file_reader, init(testing::_, testing::_))
+                .WillOnce(testing::Return(Status::OK()));
+        EXPECT_CALL(*_file_reader, open(testing::_, testing::_))
+                .WillOnce(
+                        [this](const TabletIndex*, const io::IOContext*)
+                                -> Result<std::unique_ptr<DorisCompoundReader, 
DirectoryDeleter>> {
+                            return ResultError(Status(GetParam(), "injected 
ANN open failure"));
+                        });
+    }
+
+    void check_range_load_status(int load_code) {
+        std::vector<std::unique_ptr<IndexIterator>> index_iterators(1);
+        index_iterators[0] = std::make_unique<AnnIndexIterator>(_reader);
+        std::vector<std::unique_ptr<ColumnIterator>> column_iterators;
+        AnnRangeSearchRuntime runtime;
+        runtime.is_ann_range_search = true;
+        runtime.dim = 4;
+        runtime.metric_type = AnnIndexMetric::L2;
+        runtime.user_params.ann_index_candidate_rows_percent_threshold = 0;
+        roaring::Roaring candidates;
+        candidates.addRange(0, 10);
+        const auto original_candidates = candidates;
+        AnnIndexStats stats;
+        AnnRangeSearchEvaluationResult result;
+        VectorizedFnCall expr;
+        const std::vector<ColumnId> idx_to_cid {0};
+        auto status =
+                expr.evaluate_ann_range_search(runtime, index_iterators, 
idx_to_cid,
+                                               column_iterators, 10, 
candidates, stats, result);
+        const bool missing = load_code == 
ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND;
+        EXPECT_EQ(status.code(), missing ? ErrorCode::OK : load_code);
+        EXPECT_FALSE(result.executed);
+        EXPECT_EQ(stats.fall_back_brute_force_cnt, missing ? 1 : 0);
+        EXPECT_EQ(candidates, original_candidates);
+    }
+
+    void check_topn_load_status(int load_code) {
+        auto schema = std::make_shared<TabletSchema>();
+        auto segment = std::make_shared<Segment>(0, RowsetId(), schema, 
InvertedIndexFileInfo());
+        segment->_num_rows = 10;
+        TabletColumn 
vector_column(FieldAggregationMethod::OLAP_FIELD_AGGREGATION_NONE,
+                                   FieldType::OLAP_FIELD_TYPE_ARRAY);
+        vector_column.set_name("embedding");
+        TabletColumn 
element_column(FieldAggregationMethod::OLAP_FIELD_AGGREGATION_NONE,
+                                    FieldType::OLAP_FIELD_TYPE_FLOAT);
+        vector_column.add_sub_column(element_column);
+        schema->append_column(vector_column);
+        auto read_schema = std::make_shared<Schema>(schema->columns(), 
std::vector<ColumnId> {0});
+        OlapReaderStatistics stats;
+        SegmentIterator iter(segment, read_schema);
+        iter._opts.stats = &stats;
+        iter._index_iterators.resize(1);
+        iter._index_iterators[0] = std::make_unique<AnnIndexIterator>(_reader);
+        iter._need_read_data_indices[0] = false;
+        iter._row_bitmap.addRange(0, 10);
+        const auto original_candidates = iter._row_bitmap;
+
+        VExprContextSPtr order_ctx;
+        
ASSERT_TRUE(VExpr::create_expr_tree(read_from_json<TExpr>(_distance_function_call_thrift),
+                                            order_ctx)
+                            .ok());
+        iter._ann_topn_runtime = std::make_shared<AnnTopNRuntime>(true, 5, 
order_ctx);
+        iter._ann_topn_runtime->_src_column_idx = 0;
+        iter._ann_topn_runtime->_metric_type = AnnIndexMetric::L2;
+        
iter._ann_topn_runtime->_user_params.ann_index_candidate_rows_percent_threshold 
= 0;
+
+        auto status = iter._apply_ann_topn_predicate();
+        const bool missing = load_code == 
ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND;
+        EXPECT_EQ(status.code(), missing ? ErrorCode::OK : load_code);
+        EXPECT_EQ(iter._need_read_data_indices[0], missing);
+        EXPECT_EQ(stats.ann_fall_back_brute_force_cnt, missing ? 1 : 0);
+        EXPECT_EQ(iter._row_bitmap, original_candidates);
+    }
+
+    TabletIndex _meta;
+    std::shared_ptr<MockIndexFileReader> _file_reader;
+    std::shared_ptr<AnnIndexReader> _reader;
+};
+
+TEST_P(AnnIndexLoadTest, OpenStatusReachesIterator) {
+    expect_open_failure();
+    AnnIndexIterator iterator(_reader);
+    auto status = iterator.load_index();
+    EXPECT_EQ(status.code(), GetParam());
+    EXPECT_THAT(status.msg(), testing::HasSubstr("injected ANN open failure"));
+    // A repeated load returns the stored failure instead of reporting success 
with a partial index.
+    EXPECT_EQ(iterator.load_index().code(), GetParam());
+    EXPECT_EQ(_reader->_vector_index, nullptr);
+}
+
+TEST_P(AnnIndexLoadTest, InitStatusIsPreserved) {
+    EXPECT_CALL(*_file_reader, init(testing::_, testing::_))
+            .WillOnce(testing::Return(Status(GetParam(), "injected ANN init 
failure")));
+    EXPECT_CALL(*_file_reader, open(testing::_, testing::_)).Times(0);
+    AnnIndexIterator iterator(_reader);
+    auto status = iterator.load_index();
+    EXPECT_EQ(status.code(), GetParam());
+    EXPECT_EQ(status.msg(), "injected ANN init failure");
+}
+
+TEST_P(AnnIndexLoadTest, RangeFallsBackOnlyForMissingIndex) {
+    expect_open_failure();
+    check_range_load_status(GetParam());
+}
+
+TEST_P(AnnIndexLoadTest, TopNFallsBackOnlyForMissingIndex) {
+    expect_open_failure();
+    check_topn_load_status(GetParam());
+}
+
+// An injected BYPASS still propagates; a real empty container now returns 
FILE_NOT_FOUND.
+INSTANTIATE_TEST_SUITE_P(LoadErrors, AnnIndexLoadTest,
+                         
testing::Values(ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND,
+                                         ErrorCode::IO_ERROR, 
ErrorCode::MEM_LIMIT_EXCEEDED,
+                                         
ErrorCode::INVERTED_INDEX_FILE_CORRUPTED,
+                                         
ErrorCode::INVERTED_INDEX_CLUCENE_ERROR,
+                                         ErrorCode::INVERTED_INDEX_BYPASS, 
ErrorCode::NOT_FOUND));
+
+TEST_F(AnnIndexLoadTest, EmptyV2ContainerFallsBackToScan) {
+    auto fs = io::global_local_filesystem();
+    const std::string directory = "./ut_dir/ann_empty_container";
+    ASSERT_TRUE(fs->delete_directory(directory).ok());
+    ASSERT_TRUE(fs->create_directory(directory).ok());
+    const std::string prefix = directory + "/segment_0";
+    const auto path = InvertedIndexDescriptor::get_index_file_path_v2(prefix);
+    io::FileWriterPtr file_writer;
+    ASSERT_TRUE(fs->create_file(path, &file_writer).ok());
+    {
+        // A skipped ANN build leaves no logical indexes in the real V2 writer.
+        IndexFileWriter writer(fs, prefix, "empty_ann", 0, 
InvertedIndexStorageFormatPB::V2,
+                               std::move(file_writer), false);
+        ASSERT_TRUE(writer.begin_close().ok());
+        ASSERT_TRUE(writer.finish_close().ok());
+    }
+    int64_t size = -1;
+    ASSERT_TRUE(fs->file_size(path, &size).ok());
+    ASSERT_EQ(size, 0);
+
+    _reader = std::make_shared<AnnIndexReader>(
+            &_meta,
+            std::make_shared<IndexFileReader>(fs, prefix, 
InvertedIndexStorageFormatPB::V2));
+    check_range_load_status(ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND);
+    _reader = std::make_shared<AnnIndexReader>(
+            &_meta,
+            std::make_shared<IndexFileReader>(fs, prefix, 
InvertedIndexStorageFormatPB::V2));
+    check_topn_load_status(ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND);
+    ASSERT_TRUE(fs->delete_directory(directory).ok());
+}
+
+TEST_F(AnnIndexLoadTest, NullReaderIsNotMissingIndex) {
+    AnnIndexIterator iterator(nullptr);
+    
EXPECT_TRUE(iterator.load_index().is<ErrorCode::INDEX_INVALID_PARAMETERS>());
+}
+
+TEST_F(AnnIndexLoadTest, MissingInternalFaissFileIsNotMissingIndex) {
+    for (const auto* type : {"hnsw", "ivf", "ivf_on_disk"}) {
+        SCOPED_TRACE(type);
+        _meta._properties["index_type"] = type;
+        auto reader = std::make_shared<AnnIndexReader>(&_meta, _file_reader);
+        EXPECT_CALL(*_file_reader, init(testing::_, testing::_))
+                .WillOnce(testing::Return(Status::OK()));
+        EXPECT_CALL(*_file_reader, open(testing::_, testing::_))
+                .WillOnce(
+                        [this](const TabletIndex*, const io::IOContext*)
+                                -> Result<std::unique_ptr<DorisCompoundReader, 
DirectoryDeleter>> {
+                            // The logical index opens successfully, but its 
directory lacks ann.faiss.
+                            lucene::store::Directory* directory = 
_ram_dir.get();
+                            return std::unique_ptr<DorisCompoundReader, 
DirectoryDeleter>(
+                                    new 
DorisCompoundReader(directory->openInput("index_file"),
+                                                            EntriesType {}));
+                        });
+        auto status = reader->load_index(nullptr);
+        EXPECT_TRUE(status.is<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>()) << 
status;
+    }
+}
+
+} // namespace doris::segment_v2
diff --git a/be/test/storage/index/ann/vector_search_utils.h 
b/be/test/storage/index/ann/vector_search_utils.h
index 023ce9b094d..fc782827762 100644
--- a/be/test/storage/index/ann/vector_search_utils.h
+++ b/be/test/storage/index/ann/vector_search_utils.h
@@ -151,10 +151,15 @@ public:
 
 class MockAnnIndexIterator : public doris::segment_v2::AnnIndexIterator {
 public:
-    MockAnnIndexIterator() : doris::segment_v2::AnnIndexIterator(nullptr) {}
+    MockAnnIndexIterator() : doris::segment_v2::AnnIndexIterator(nullptr) {
+        // Search-only tests provide results without a physical index. 
Load-error tests override this.
+        ON_CALL(*this, 
load_index()).WillByDefault(testing::Return(Status::OK()));
+    }
 
     ~MockAnnIndexIterator() override = default;
 
+    MOCK_METHOD(Status, load_index, (), (override));
+
     MOCK_METHOD(Status, read_from_index, (const doris::segment_v2::IndexParam& 
param), (override));
     MOCK_METHOD(Status, range_search,
                 (const segment_v2::AnnRangeSearchParams& params,
diff --git a/be/test/storage/index/index_builder_test.cpp 
b/be/test/storage/index/index_builder_test.cpp
index bba51abc9c3..64d9331aeb3 100644
--- a/be/test/storage/index/index_builder_test.cpp
+++ b/be/test/storage/index/index_builder_test.cpp
@@ -175,8 +175,8 @@ protected:
     // Builds a k2 index over a rowset whose schema owns a k1 index that was 
never
     // written, and returns the index ids present in the output rowset's index
     // file. `leave_empty_index_file` picks between the two shapes a source
-    // segment with no index content can have on disk: a zero-byte file (read 
as
-    // INVERTED_INDEX_BYPASS) or no file at all 
(INVERTED_INDEX_FILE_NOT_FOUND).
+    // segment with no index content can have on disk: a zero-byte file or no 
file
+    // at all. Both are read as INVERTED_INDEX_FILE_NOT_FOUND.
     //
     // The rowset is written BEFORE the schema gains k1, so k1 has no content
     // anywhere and nothing can be lost by either shape. That is not an 
artifact
@@ -257,9 +257,7 @@ protected:
             auto reader = std::make_unique<segment_v2::IndexFileReader>(
                     io::global_local_filesystem(), source_prefix, 
InvertedIndexStorageFormatPB::V2);
             auto st = reader->init();
-            EXPECT_TRUE(leave_empty_index_file ? 
st.is<ErrorCode::INVERTED_INDEX_BYPASS>()
-                                               : 
st.is<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>())
-                    << st;
+            EXPECT_TRUE(st.is<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>()) << 
st;
         }
 
         TOlapTableIndex k2_index;
@@ -787,7 +785,7 @@ TEST_F(IndexBuilderTest, 
BuildInvertedIndexAfterWritingDataTest) {
 // nothing to carry over, and every requested index is built from the raw 
columns.
 TEST_F(IndexBuilderTest, BuildIndexOverEmptyIndexFileTest) {
     // Without tolerating the empty index file this fails the whole ALTER with
-    // [E-6004]inverted index file ... is empty.
+    // [E-6003]inverted index file ... is empty.
     EXPECT_EQ(build_k2_index_over_unwritten_k1(14695, 15695, true), 
(std::set<int64_t> {2}));
 }
 
diff --git a/be/test/storage/index/inverted/empty_index_file_test.cpp 
b/be/test/storage/index/inverted/empty_index_file_test.cpp
index cf645b1ba8a..9c584565081 100644
--- a/be/test/storage/index/inverted/empty_index_file_test.cpp
+++ b/be/test/storage/index/inverted/empty_index_file_test.cpp
@@ -22,11 +22,16 @@
 #include "gtest/gtest_pred_impl.h"
 #include "io/fs/local_file_system.h"
 #include "io/fs/stream_sink_file_writer.h"
+#include "runtime/runtime_state.h"
 #include "storage/index/index_file_reader.h"
 #include "storage/index/index_file_writer.h"
 #include "storage/index/index_writer.h"
 #include "storage/index/inverted/inverted_index_desc.h"
 #include "storage/olap_common.h"
+#include "storage/schema.h"
+#include "storage/segment/column_reader.h"
+#include "storage/segment/segment.h"
+#include "storage/segment/segment_iterator.h"
 
 namespace doris {
 
@@ -246,7 +251,7 @@ TEST_P(EmptyIndexFileTest, AllowsNullWriter) {
     }
 }
 
-TEST_P(EmptyIndexFileTest, PreservesLocalEmptyFileAfterDestruction) {
+TEST_P(EmptyIndexFileTest, PreservesLocalEmptyFileAndUsesMissingIndexPolicy) {
     auto fs = io::global_local_filesystem();
     const auto path =
             
segment_v2::InvertedIndexDescriptor::get_index_file_path_v2(index_path_prefix());
@@ -272,19 +277,36 @@ TEST_P(EmptyIndexFileTest, 
PreservesLocalEmptyFileAfterDestruction) {
     EXPECT_EQ(file_size, 0);
 
     // The contract every reader of this file relies on: a zero-length 
container
-    // is not corruption, it is "this segment has no index data". Query falls 
back
-    // to a non-indexed evaluation on it and IndexBuilder treats it as 
"nothing to
-    // carry over"; both branch on this exact error code.
+    // is not corruption, it is "this segment has no index data". Queries apply
+    // their missing-index fallback policy and IndexBuilder has nothing to 
carry over.
     auto reader =
             std::make_unique<segment_v2::IndexFileReader>(fs, 
index_path_prefix(), GetParam());
     auto st = reader->init();
-    EXPECT_TRUE(st.is<ErrorCode::INVERTED_INDEX_BYPASS>()) << st;
+    EXPECT_TRUE(st.is<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>()) << st;
     EXPECT_NE(st.to_string().find(" is empty"), std::string::npos) << st;
+
+    for (bool allow_fallback : {false, true}) {
+        SCOPED_TRACE(allow_fallback);
+        RuntimeState runtime;
+        TQueryOptions options;
+        
options.__set_enable_fallback_on_missing_inverted_index(allow_fallback);
+        runtime.set_query_options(options);
+        auto schema = std::make_shared<TabletSchema>();
+        auto segment = std::make_shared<segment_v2::Segment>(0, RowsetId(), 
schema,
+                                                             
InvertedIndexFileInfo());
+        auto read_schema = std::make_shared<Schema>(schema->columns(), 
std::vector<ColumnId> {});
+        OlapReaderStatistics stats;
+        segment_v2::SegmentIterator iterator(segment, read_schema);
+        iterator._opts.stats = &stats;
+        iterator._opts.runtime_state = &runtime;
+        EXPECT_EQ(iterator._downgrade_without_index(st), allow_fallback);
+        EXPECT_EQ(stats.inverted_index_downgrade_count, allow_fallback ? 1 : 
0);
+    }
 }
 
 TEST_P(EmptyIndexFileTest, MissingLocalFileReadsAsFileNotFound) {
     // The other half of the same contract: a rowset written before any index
-    // existed has no container at all, and that is distinct from an empty one.
+    // existed has no container at all and uses the same missing-index policy.
     auto reader = std::make_unique<segment_v2::IndexFileReader>(
             io::global_local_filesystem(), std::string(tmp_dir) + "/absent_0", 
GetParam());
     auto st = reader->init();
diff --git a/be/test/storage/segment/inverted_index_file_reader_test.cpp 
b/be/test/storage/segment/inverted_index_file_reader_test.cpp
index 8af14c095ab..2463614ec83 100644
--- a/be/test/storage/segment/inverted_index_file_reader_test.cpp
+++ b/be/test/storage/segment/inverted_index_file_reader_test.cpp
@@ -235,7 +235,7 @@ TEST_F(InvertedIndexFileReaderTest, 
TestEmptyIndexSegmentError) {
 
     Status status = reader.init(4096);
     EXPECT_FALSE(status.ok());
-    EXPECT_EQ(status.code(), ErrorCode::INVERTED_INDEX_BYPASS);
+    EXPECT_EQ(status.code(), ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND);
 }
 
 // Test case for unknown inverted index format error
@@ -467,4 +467,4 @@ TEST_F(InvertedIndexFileReaderTest, 
TestGetAllDirectoriesError) {
     EXPECT_TRUE(result.value().empty()); // Should be empty since no init was 
called
 }
 
-} // namespace doris::segment_v2
\ No newline at end of file
+} // namespace doris::segment_v2
diff --git 
a/regression-test/suites/inverted_index_p0/test_empty_index_file_lifecycle.groovy
 
b/regression-test/suites/inverted_index_p0/test_empty_index_file_lifecycle.groovy
index 04b53207ae9..2c1f8766d1d 100644
--- 
a/regression-test/suites/inverted_index_p0/test_empty_index_file_lifecycle.groovy
+++ 
b/regression-test/suites/inverted_index_p0/test_empty_index_file_lifecycle.groovy
@@ -23,7 +23,7 @@
 //
 //     rowset schema owns an inverted index  <=>  every segment owns an index 
file
 //
-// An empty index file (E-6004 "is empty") is therefore expected wherever a
+// An empty index file (E-6003 "is empty") is therefore expected wherever a
 // rowset's schema still has the index, and NO index file at all (E-6003 "not
 // found") is expected once it has none. Every producer has to keep the first 
half
 // true -- load, compaction, light and direct schema change, BUILD INDEX -- and
@@ -34,8 +34,8 @@ suite("test_empty_index_file_lifecycle", "p0") {
     getBackendIpHttpPort(backendId_to_backendIP, backendId_to_backendHttpPort)
 
     // show_nested_index_file reports the first rowset it cannot open, so 
there is
-    // one status per tablet: "E-6004" empty index file, "E-6003" none at all,
-    // "OK" an index file with real indexes in it.
+    // one status per tablet: E-6003 for both empty and absent containers,
+    // distinguished by the message; "OK" for a file with real indexes in it.
     def index_file_status = { String tableName ->
         def statuses = [] as Set
         for (def tablet : sql_return_maparray(" show tablets from ${tableName} 
")) {
@@ -44,7 +44,11 @@ suite("test_empty_index_file_lifecycle", "p0") {
             def (code, out, err) = http_client("GET", String.format(
                     "http://%s:%s/api/show_nested_index_file?tablet_id=%s";, 
ip, port, tablet.TabletId))
             logger.info("show_nested_index_file tablet=${tablet.TabletId}: 
code=${code}, out=${out}, err=${err}")
-            statuses.add(code == 500 ? parseJson(out.trim()).status : "OK")
+            def status = code == 500 ? parseJson(out.trim()).status : "OK"
+            if (status == "E-6003") {
+                status += out.contains(" is empty") ? " (empty)" : " (missing)"
+            }
+            statuses.add(status)
         }
         return statuses
     }
@@ -109,7 +113,7 @@ suite("test_empty_index_file_lifecycle", "p0") {
         sql " insert into ${tableName} values (1, NULL) "
         sql " insert into ${tableName} values (2, NULL) "
         sql "sync"
-        assert_index_file_status(tableName, "E-6004", "load")
+        assert_index_file_status(tableName, "E-6003 (empty)", "load")
         assert_readable(tableName)
 
         // The steps below do not depend on the write path that loaded the 
rows, so
@@ -120,14 +124,14 @@ suite("test_empty_index_file_lifecycle", "p0") {
 
         // 2. compaction: two empty-index inputs produce one empty-index output
         trigger_and_wait_compaction(tableName, "full")
-        assert_index_file_status(tableName, "E-6004", "full compaction")
+        assert_index_file_status(tableName, "E-6003 (empty)", "full 
compaction")
         assert_readable(tableName)
 
         // 3. light schema change: a default-valued ADD COLUMN keeps the 
segments
         //    and their index files (locally it hard-links them)
         sql """ ALTER TABLE ${tableName} ADD COLUMN c INT DEFAULT "7" """
         wait_alter_done(tableName)
-        assert_index_file_status(tableName, "E-6004", "light schema change")
+        assert_index_file_status(tableName, "E-6003 (empty)", "light schema 
change")
         assert_readable(tableName)
 
         // 4. direct schema change: a type change rewrites every rowset, so the
@@ -135,14 +139,14 @@ suite("test_empty_index_file_lifecycle", "p0") {
         //    to be repeated, or FE rejects the statement as a default value 
change.
         sql """ ALTER TABLE ${tableName} MODIFY COLUMN c BIGINT DEFAULT "7" """
         wait_alter_done(tableName)
-        assert_index_file_status(tableName, "E-6004", "direct schema change")
+        assert_index_file_status(tableName, "E-6003 (empty)", "direct schema 
change")
         assert_readable(tableName)
 
         if (!isCloudMode()) {
             // 5. ADD INDEX + BUILD INDEX runs IndexBuilder over the existing 
index
             //    files. An empty one means "nothing to carry over", exactly 
like a
             //    rowset written before any index existed; failing on it 
aborts the
-            //    whole ALTER with "[E-6004] ... is empty".
+            //    whole ALTER with "[E-6003] ... is empty".
             sql " ALTER TABLE ${tableName} ADD INDEX id_idx (`id`) USING 
INVERTED "
             wait_alter_done(tableName)
             build_index_on_table("id_idx", tableName)
@@ -155,7 +159,7 @@ suite("test_empty_index_file_lifecycle", "p0") {
             //    surviving index is the all-NULL VARIANT one
             sql " ALTER TABLE ${tableName} DROP INDEX id_idx "
             wait_alter_done(tableName)
-            assert_index_file_status(tableName, "E-6004", "dropping one of two 
indexes")
+            assert_index_file_status(tableName, "E-6003 (empty)", "dropping 
one of two indexes")
             assert_readable(tableName)
         }
 
@@ -165,13 +169,13 @@ suite("test_empty_index_file_lifecycle", "p0") {
         sql " ALTER TABLE ${tableName} DROP INDEX v_idx "
         wait_alter_done(tableName)
         if (!isCloudMode()) {
-            assert_index_file_status(tableName, "E-6004", "dropping the last 
index")
+            assert_index_file_status(tableName, "E-6003 (empty)", "dropping 
the last index")
         }
         // Full compaction needs a second rowset, or it has nothing to merge.
         sql " insert into ${tableName} (id, v) values (3, NULL) "
         if (!isCloudMode()) {
             trigger_and_wait_compaction(tableName, "full")
-            assert_index_file_status(tableName, "E-6003", "compacting a table 
with no index")
+            assert_index_file_status(tableName, "E-6003 (missing)", 
"compacting a table with no index")
         }
         assert_readable(tableName, 3)
     }
diff --git 
a/regression-test/suites/inverted_index_p0/test_variant_empty_index_file.groovy 
b/regression-test/suites/inverted_index_p0/test_variant_empty_index_file.groovy
index 724eee97f73..548654508ec 100644
--- 
a/regression-test/suites/inverted_index_p0/test_variant_empty_index_file.groovy
+++ 
b/regression-test/suites/inverted_index_p0/test_variant_empty_index_file.groovy
@@ -41,8 +41,8 @@ suite("test_variant_empty_index_file", "p0") {
     // The schema owns an index, so every segment owns an index file -- but an
     // all-NULL VARIANT column extracts no subcolumn, so no logical index is 
ever
     // opened and the file is closed empty. Reading it must say "is empty"
-    // (E-6004), never "not found" (E-6003): the file is there, it just has no
-    // index in it.
+    // with E-6003: empty and absent containers both mean no index data, but
+    // the message must still distinguish the existing empty file.
     def assert_empty_index_file = { String table ->
         sql "sync"
         def tablets = sql_return_maparray """ show tablets from ${table}; """
@@ -52,7 +52,7 @@ suite("test_variant_empty_index_file", "p0") {
         String port = backendId_to_backendHttpPort.get(backend_id)
         def (code, out, err) = http_client("GET", 
String.format("http://%s:%s/api/show_nested_index_file?tablet_id=%s";, ip, port, 
tablet_id))
         logger.info("Run show_nested_index_file_on_tablet: code=" + code + ", 
out=" + out + ", err=" + err)
-        assertEquals("E-6004", parseJson(out.trim()).status)
+        assertEquals("E-6003", parseJson(out.trim()).status)
         assertTrue(out.contains(" is empty"))
     }
 


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

Reply via email to