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

csun5285 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 7530d325f53 branch-4.2: [improvement](index) Surface ANN load errors 
and unify missing-index fallback #70788 (#71250)
7530d325f53 is described below

commit 7530d325f5360dedd0c86b5096fa8b2423700ff1
Author: yiguolei <[email protected]>
AuthorDate: Thu Dec 3 14:21:11 2026 +0800

    branch-4.2: [improvement](index) Surface ANN load errors and unify 
missing-index fallback #70788 (#71250)
    
    
    Related PR: #70788
    
    Backport #70788 (`c80210883391806418a34f8a39c85fec32bc028d`) to
    `branch-4.2`.
---
 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        |   8 +-
 be/test/storage/index/ann/ann_index_load_test.cpp  | 235 +++++++++++++++++++++
 .../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, 327 insertions(+), 62 deletions(-)

diff --git a/be/src/exprs/vectorized_fn_call.cpp 
b/be/src/exprs/vectorized_fn_call.cpp
index 137fe34e97d..eea778799d3 100644
--- a/be/src/exprs/vectorized_fn_call.cpp
+++ b/be/src/exprs/vectorized_fn_call.cpp
@@ -979,12 +979,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 " << 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 db1aac9d8be..1ef0e120f69 100644
--- a/be/src/storage/index/ann/ann_index_iterator.cpp
+++ b/be/src/storage/index/ann/ann_index_iterator.cpp
@@ -28,15 +28,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 4d7c21241fe..962c769aef4 100644
--- a/be/src/storage/index/ann/ann_index_reader.cpp
+++ b/be/src/storage/index/ann/ann_index_reader.cpp
@@ -62,7 +62,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);
@@ -83,18 +90,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 f4cac2f981f..14662c37160 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 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 2ba2b1b2be9..6b15eb67c83 100644
--- a/be/src/storage/segment/segment_iterator.cpp
+++ b/be/src/storage/segment/segment_iterator.cpp
@@ -1115,12 +1115,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..dc2d357655d
--- /dev/null
+++ b/be/test/storage/index/ann/ann_index_load_test.cpp
@@ -0,0 +1,235 @@
+// 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;
+        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(), 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 387fe2e1875..8ad4f25fbbf 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
@@ -415,8 +415,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 239df2f81de..a36e727c94f 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 009bb833814..59f78d5d454 100644
--- a/be/test/storage/index/index_builder_test.cpp
+++ b/be/test/storage/index/index_builder_test.cpp
@@ -198,8 +198,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
@@ -280,9 +280,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;
@@ -1161,7 +1159,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..754d0965b59 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<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 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