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

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


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

commit c80210883391806418a34f8a39c85fec32bc028d
Author: yiguolei <[email protected]>
AuthorDate: Tue Nov 24 12:29:52 2026 +0800

    [improvement](index) Surface ANN load errors and unify missing-index 
fallback (#70788)
    
    ### 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: #70270 (ANN storage abstraction integrated from master)
    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 +32/-31; tests +288/-32 across 15
    files. Status propagation and the two ANN consumers account for +29/-30
    production lines; shared empty-container classification adds +3/-1.
    Tests cover both changes and use the current ANN storage 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
    
    Historical validation reported for pre-rebase commit
    `42f9f0b3066a4759323af590799077f07d828152` on a Linux development host
    with ASAN (these results do not validate the updated head):
    
    ```bash
    ./build.sh --be -j 8
    ./run-be-ut.sh --run 
--filter='*AnnIndexLoadTest*:*AnnIndexReaderTest*:*AnnIndexIteratorTest*:VectorSearchTest.*:*EmptyIndexFileTest*:*InvertedIndexFileReaderTest*:IndexBuilderTest.BuildIndexOverEmptyIndexFileTest:IndexBuilderTest.BuildIndexOverMissingIndexFileTest'
 -j 8
    ```
    
    - BE build passed; all 162 tests from 8 suites passed, both commands
    exiting 0.
    - Coverage includes real empty-container TopN/range fallback, both
    inverted fallback-setting values, load-error propagation, missing
    internal files, and index building over empty/missing files.
    - The earlier AI PASS review applies only to `42f9f0b`; the rebased head
    has not been independently reviewed.
    - Historical formatting and header hygiene passed; no final clang-tidy
    result was recorded.
    - Updated lifecycle/VARIANT regression suites were not run.
    - Current rebase update (`c51dfbd5aee`): clang-format 16, header hygiene
    and diff whitespace checks passed. Builds, unit tests, regressions and
    clang-tidy were not rerun, following the author's preference.
    
    ### Notes for Reviewers
    
    - Integration with #70270 uses `open_ann_source`, passes the IO context
    into Faiss loading, and retains the source for IVF_ON_DISK. Load-error
    mocks now use the same interface; internal-file errors still cannot
    trigger fallback.
    
    - Normalize SNII logical-index absence only at the lookup boundary;
    missing files inside an existing ANN index must remain errors.
    - Removing the BE_TEST loading shortcut lets tests exercise the real
    loader. Search-only mocks explicitly model successful loading.
    - 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: the rebased head has not
    been built or tested; previous ASAN results apply only to the pre-rebase
    commit. Clang-tidy and regression validation remain unverified.
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6); review by GPT-6 Astra with xhigh effort.
    - Generated: Implementation, tests, review and this description.
    - Human review: The author approved the missing-index contract and
    shared empty-container behavior; 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      |  21 +-
 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 +++++++++++++++++++++
 .../index/ann/ann_index_range_read_test.cpp        |   4 +-
 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 +-
 15 files changed, 320 insertions(+), 63 deletions(-)

diff --git a/be/src/exprs/vectorized_fn_call.cpp 
b/be/src/exprs/vectorized_fn_call.cpp
index 3b98c6fabf3..6e3fd5ed880 100644
--- a/be/src/exprs/vectorized_fn_call.cpp
+++ b/be/src/exprs/vectorized_fn_call.cpp
@@ -1032,12 +1032,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 
{}", src_col_idx);
+        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 " << src_col_idx
+                       << ": " << 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 f00b58c36b9..fe2359ed3ad 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 254481ce928..608adf3bb9f 100644
--- a/be/src/storage/index/ann/ann_index_iterator.h
+++ b/be/src/storage/index/ann/ann_index_iterator.h
@@ -43,9 +43,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 7d76ebaa222..9e44da0f131 100644
--- a/be/src/storage/index/ann/ann_index_reader.cpp
+++ b/be/src/storage/index/ann/ann_index_reader.cpp
@@ -80,7 +80,14 @@ Status AnnIndexReader::load_index(io::IOContext* io_ctx) {
         
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()) {
-            return Status::IOError("Failed to open index file: {}", 
source.error().to_string());
+            // 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();
         }
         _vector_index = std::make_unique<FaissVectorIndex>();
         _vector_index->set_metric(_metric_type);
@@ -101,18 +108,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 4c45c6b6c27..9b1136647cc 100644
--- a/be/src/storage/index/ann/ann_index_reader.h
+++ b/be/src/storage/index/ann/ann_index_reader.h
@@ -45,12 +45,9 @@ public:
                    uint32_t segment_id = 0, size_t rows_of_segment = 0);
     ~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 bc9150843e5..9ede2a3a042 100644
--- a/be/src/storage/index/index_file_reader.cpp
+++ b/be/src/storage/index/index_file_reader.cpp
@@ -89,7 +89,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 89f5777b067..fb8c5db198a 100644
--- a/be/src/storage/segment/segment_iterator.cpp
+++ b/be/src/storage/segment/segment_iterator.cpp
@@ -1178,7 +1178,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) {
@@ -1191,12 +1191,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;
             _column_states[src_cid].need_read_data = 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..ad7cbe8d6ef
--- /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/clucene/lucene_ann_store.h"
+#include "storage/index/inverted/common/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_ann_source(testing::_, testing::_))
+                .WillOnce([this](const TabletIndex*,
+                                 const io::IOContext*) -> 
Result<std::unique_ptr<AnnIndexSource>> {
+                    return ResultError(Status(GetParam(), "injected ANN open 
failure"));
+                });
+    }
+
+    int expected_code() const {
+        return GetParam() == ErrorCode::INVERTED_INDEX_SNII_NOT_FOUND
+                       ? ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND
+                       : GetParam();
+    }
+
+    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;
+        auto status = expr.evaluate_ann_range_search(runtime, index_iterators, 
column_iterators, 10,
+                                                     candidates, stats, false, 
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;
+        auto read_schema = 
std::make_shared<ReadSchema>(std::vector<TabletColumnPtr> {});
+        OlapReaderStatistics stats;
+        StorageReadOptions opts(stats);
+        SegmentIterator iter(segment, read_schema, opts);
+        iter._index_iterators.resize(1);
+        iter._index_iterators[0] = std::make_unique<AnnIndexIterator>(_reader);
+        iter._column_states.resize(1);
+        iter._column_states[0].need_read_data = 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._column_states[0].need_read_data, 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(), expected_code());
+    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(), expected_code());
+    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_ann_source(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(expected_code());
+}
+
+TEST_P(AnnIndexLoadTest, TopNFallsBackOnlyForMissingIndex) {
+    expect_open_failure();
+    check_topn_load_status(expected_code());
+}
+
+// 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::INVERTED_INDEX_SNII_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_ann_source(testing::_, testing::_))
+                .WillOnce([this](const TabletIndex*,
+                                 const io::IOContext*) -> 
Result<std::unique_ptr<AnnIndexSource>> {
+                    // The logical index opens successfully, but its directory 
lacks ann.faiss.
+                    lucene::store::Directory* directory = _ram_dir.get();
+                    return std::make_unique<LuceneAnnSource>(
+                            std::shared_ptr<lucene::store::Directory>(
+                                    new 
DorisCompoundReader(directory->openInput("index_file"),
+                                                            EntriesType {}),
+                                    DirectoryDeleter {}));
+                });
+        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/ann_index_range_read_test.cpp 
b/be/test/storage/index/ann/ann_index_range_read_test.cpp
index cce7b893b63..794663d753d 100644
--- a/be/test/storage/index/ann/ann_index_range_read_test.cpp
+++ b/be/test/storage/index/ann/ann_index_range_read_test.cpp
@@ -416,8 +416,8 @@ TEST_F(AnnIndexRangeReadTest, 
LoadAndSearchIssueTheRecordedReads) {
     }
 }
 
-// A load whose index file is cut short reports the failure as a status, so 
try_load_index() can
-// fall back to brute force: the CLucene error of the read past the end must 
not escape. E.g. the
+// A load whose index file is cut short reports the failure as a status to the 
query caller;
+// corruption must not trigger brute-force fallback or let a CLucene exception 
escape. E.g. the
 // last 4 KiB of the file gone leaves its file table whole, and reading 
ann.faiss reaches EOF.
 TEST_F(AnnIndexRangeReadTest, ACutShortIndexFileFailsTheLoadWithAStatus) {
     const AnnCase& ann_case = ann_cases().front();
diff --git a/be/test/storage/index/ann/vector_search_utils.h 
b/be/test/storage/index/ann/vector_search_utils.h
index 0c88aa0f24d..e32d1f77f3f 100644
--- a/be/test/storage/index/ann/vector_search_utils.h
+++ b/be/test/storage/index/ann/vector_search_utils.h
@@ -162,10 +162,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 40e70cc1dd7..26424839ad1 100644
--- a/be/test/storage/index/index_builder_test.cpp
+++ b/be/test/storage/index/index_builder_test.cpp
@@ -665,8 +665,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
@@ -743,9 +743,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;
@@ -1395,7 +1393,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 468d8211228..0404cca42de 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/common/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<ReadSchema>(std::vector<TabletColumnPtr> {});
+        OlapReaderStatistics stats;
+        StorageReadOptions opts(stats);
+        opts.runtime_state = &runtime;
+        segment_v2::SegmentIterator iterator(segment, read_schema, opts);
+        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 c5e288d2df8..1be47f85d05 100644
--- a/be/test/storage/segment/inverted_index_file_reader_test.cpp
+++ b/be/test/storage/segment/inverted_index_file_reader_test.cpp
@@ -279,7 +279,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
@@ -562,4 +562,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