hello-stephen commented on code in PR #71435:
URL: https://github.com/apache/doris/pull/71435#discussion_r4803837483


##########
be/test/storage/index/inverted/reader/collection_statistics_test.cpp:
##########
@@ -1055,6 +1066,116 @@ TEST_F(CollectionStatisticsTest, 
HiddenRowsAreCollectedLikeCompactedAway) {
     expect_collected_term(kMatchField, L"alpha", 2);
 }
 
+TEST_F(CollectionStatisticsTest, ColdCollectionOpensBelongToOneReader) {
+    auto schema = create_legacy_v3_schema();
+    TabletSchemaPB pb;
+    schema->to_schema_pb(&pb);
+    pb.set_keys_type(UNIQUE_KEYS);
+    pb.set_num_short_key_columns(1);
+    pb.set_delete_sign_idx(2);
+    pb.mutable_column(0)->set_aggregation("REPLACE");
+    auto* id = pb.add_column();
+    id->set_unique_id(2);
+    id->set_name("id");
+    id->set_type("INT");
+    id->set_length(4);
+    id->set_index_length(4);
+    id->set_is_key(true);
+    id->set_is_nullable(false);
+    pb.mutable_column()->SwapElements(0, 1);
+    auto* sign = pb.add_column();
+    sign->set_unique_id(3);
+    sign->set_name(DELETE_SIGN);
+    sign->set_type("TINYINT");
+    sign->set_length(1);
+    sign->set_is_nullable(false);
+    sign->set_aggregation("REPLACE");
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    auto dirs = std::make_unique<segment_v2::TmpFileDirs>(
+            std::vector<StorePath> {StorePath(test_dir_, 1024)});
+    ASSERT_TRUE(dirs->init().ok());
+    _tmp_file_dirs_scope.install(std::move(dirs));
+    EngineOptions options;
+    StorageEngine engine(options);
+    RowsetWriterContext context;
+    context.rowset_id.init(12051);
+    context.tablet_id = 12051;
+    context.rowset_state = VISIBLE;
+    context.rowset_type = BETA_ROWSET;
+    context.tablet_path = test_dir_;
+    context.tablet_schema = schema;
+    context.version = {2, 2};
+    context.enable_unique_key_merge_on_write = true;
+    context.allow_packed_file = false;
+    auto writer = RowsetFactory::create_rowset_writer(engine, context, false);
+    ASSERT_TRUE(writer.has_value()) << writer.error();
+    for (int32_t i = 0; i < 3; ++i) {
+        auto block = schema->create_storage_block();
+        {
+            auto guard = block.mutate_columns_scoped();
+            auto& columns = guard.mutable_columns();
+            columns[0]->insert_data(reinterpret_cast<const char*>(&i), 
sizeof(i));
+            columns[1]->insert_data("alpha beta", 10);
+            const int8_t sign_value = 0;
+            columns[2]->insert_data(reinterpret_cast<const 
char*>(&sign_value), sizeof(sign_value));
+        }
+        ASSERT_TRUE(writer.value()->add_block(&block).ok());
+        ASSERT_TRUE(writer.value()->flush().ok());
+    }
+    RowsetSharedPtr rowset;
+    ASSERT_TRUE(writer.value()->build(rowset).ok());
+    ASSERT_EQ(3, rowset->num_segments());
+    // The test runner's 1000-byte global cache cannot retain these real 
segments.
+    auto* old_loader = SegmentLoader::instance();
+    SegmentLoader loader(64 << 20, 1024);

Review Comment:
   [P3] Restore the segment cache registration as well as the loader. Under 
BE_TEST, constructing this SegmentLoader replaces the existing SEGMENT_CACHE 
entry in CacheManager, and unregister_cache is a no-op. The defer restores 
ExecEnv's loader but leaves the manager pointing to the destroyed temporary 
policy; a later cache-prune operation in the same test process can use that 
stale entry. Use the isolated CacheManager setup/teardown in 
PointQuerySegmentReuseTest, or restore the previous cache registration before 
destroying this loader.



##########
be/test/storage/rowset/beta_rowset_test.cpp:
##########
@@ -918,4 +934,630 @@ TEST_F(BetaRowsetTest, WholeKeyMergeKeepsOneRowPerKey) {
     EXPECT_EQ(read_keys(rowset.get(), context), expected_keys);
 }
 
+class SegmentKeyPruningTest : public BetaRowsetTest {
+protected:
+    void SetUp() override {
+        _old_enabled = config::enable_segment_key_range_pruning;
+        _old_aggregate = config::enable_aggregate_non_mow_key_bounds;
+        _old_threshold = config::segments_key_bounds_truncation_threshold;
+        config::enable_segment_key_range_pruning = true;
+        config::enable_aggregate_non_mow_key_bounds = false;
+        config::segments_key_bounds_truncation_threshold = -1;
+        schema = std::make_shared<TabletSchema>();
+        create_tablet_schema(schema);
+        schema->_keys_type = UNIQUE_KEYS;
+        meta = std::make_shared<RowsetMeta>();
+        init_rs_meta(meta, 1, 1);
+        persist_schema();
+        context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+        context.stats = &_stats;
+        context.enable_unique_key_merge_on_write = true;
+        context.lower_bound_keys = &lower;
+        context.upper_bound_keys = &upper;
+        context.is_lower_keys_included = &include_lower;
+        context.is_upper_keys_included = &include_upper;
+    }
+
+    void TearDown() override {
+        config::enable_segment_key_range_pruning = _old_enabled;
+        config::enable_aggregate_non_mow_key_bounds = _old_aggregate;
+        config::segments_key_bounds_truncation_threshold = _old_threshold;
+    }
+
+    void persist_schema() {
+        TabletSchemaPB pb;
+        schema->to_schema_pb(&pb);
+        meta->_schema = std::make_shared<TabletSchema>();
+        meta->_schema->init_from_pb(pb);
+    }
+
+    RowCursor key(std::initializer_list<std::optional<int32_t>> values) {
+        OlapTuple tuple;
+        for (auto value : values) {
+            if (value) {
+                tuple.add_field(Field::create_field<TYPE_INT>(*value));
+            } else {
+                tuple.add_null();
+            }
+        }
+        RowCursor cursor;
+        EXPECT_TRUE(cursor.init(schema, tuple).ok());
+        return cursor;
+    }
+
+    RowCursor string_key(const std::optional<std::string>& value) {
+        RowCursor cursor;
+        OlapTuple tuple;
+        if (value) {
+            tuple.add_field(Field::create_field<TYPE_STRING>(*value));
+        } else {
+            tuple.add_null();
+        }
+        EXPECT_TRUE(cursor.init(schema, tuple).ok());
+        return cursor;
+    }
+
+    KeyBoundsPB bounds(const RowCursor& min, const RowCursor& max) {
+        KeyBoundsPB result;
+        min.encode_key<true>(result.mutable_min_key(), min.field_count());
+        max.encode_key<true>(result.mutable_max_key(), max.field_count());
+        return result;
+    }
+
+    void segments(const std::vector<KeyBoundsPB>& values) {
+        meta->set_num_segments(cast_set<int64_t>(values.size()));
+        meta->set_segments_key_bounds(values);
+    }
+
+    void range(std::optional<RowCursor> lo, std::optional<RowCursor> hi, bool 
incl_lo = true,
+               bool incl_hi = true) {
+        lower.push_back(std::move(lo));
+        upper.push_back(std::move(hi));
+        include_lower.push_back(incl_lo);
+        include_upper.push_back(incl_hi);
+    }
+
+    void clear_ranges() {
+        lower.clear();
+        upper.clear();
+        include_lower.clear();
+        include_upper.clear();
+    }
+
+    void expect_ids(const std::vector<uint64_t>& expected, RowSetSplits splits 
= {}) {
+        _stats = {};
+        auto rowset = std::make_shared<BetaRowset>(schema, meta, "");
+        BetaRowsetReader reader(rowset);
+        ASSERT_TRUE(reader.init(&context, splits).ok());
+        std::vector<RowwiseIteratorUPtr> iters;
+        ASSERT_TRUE(reader.get_segment_iterators(&context, &iters, 
false).ok());
+        std::vector<uint64_t> ids;
+        for (const auto& iter : iters) {
+            ids.push_back(iter->data_id());
+        }
+        EXPECT_EQ(expected, ids);
+        EXPECT_EQ(0, _stats.segment_open_count);
+        auto candidate_count =
+                splits.segment_offsets.first == splits.segment_offsets.second
+                        ? meta->num_segments()
+                        : splits.segment_offsets.second - 
splits.segment_offsets.first;
+        EXPECT_EQ(candidate_count - cast_set<int64_t>(expected.size()),
+                  _stats.segment_key_bounds_pruned);
+    }
+
+    TabletSchemaSPtr schema;
+    RowsetMetaSharedPtr meta;
+    RowsetReaderContext context;
+    std::vector<std::optional<RowCursor>> lower;
+    std::vector<std::optional<RowCursor>> upper;
+    std::vector<bool> include_lower;
+    std::vector<bool> include_upper;
+
+private:
+    bool _old_enabled;
+    bool _old_aggregate;
+    int32_t _old_threshold;
+};
+
+TEST_F(SegmentKeyPruningTest, IntegerPrefixesRangesAndNulls) {
+    segments({bounds(key({-2, 0}), key({-2, 4})), bounds(key({1, 1}), key({1, 
4})),
+              bounds(key({3, 1}), key({3, 5})),
+              bounds(key({std::nullopt, 0}), key({std::nullopt, 8}))});
+    range(key({1}), key({1}));
+    expect_ids({1});
+    config::enable_segment_key_range_pruning = false;
+    expect_ids({0, 1, 2, 3});
+    config::enable_segment_key_range_pruning = true;
+    range(key({3}), key({3}));
+    expect_ids({1, 2});
+    clear_ranges();
+    range(key({std::nullopt}), key({std::nullopt}));
+    expect_ids({3});
+    clear_ranges();
+    range(std::nullopt, key({-2}), false, false);
+    expect_ids({3});
+    clear_ranges();
+    range(key({3}), std::nullopt, false);
+    expect_ids({});
+    clear_ranges();
+    range(key({-2}), key({3}));
+    expect_ids({0, 1, 2});
+    clear_ranges();
+    range(key({-2}), key({3}), false, false);
+    expect_ids({1});
+    clear_ranges();
+    range(key({1, 2}), key({1, 3}));
+    expect_ids({1});
+    clear_ranges();
+    range(key({2}), key({2}));
+    expect_ids({});
+    // Projection order is unrelated to scan-key order.
+    context.read_schema = 
std::make_shared<ReadSchema>(std::vector<TabletColumnPtr> {
+            schema->columns()[2], schema->columns()[1], schema->columns()[0]});
+    expect_ids({});
+}
+
+TEST_F(SegmentKeyPruningTest, LexicographicNotPerColumnAndOpenBoundaries) {
+    segments({bounds(key({1, 999}), key({2, 2})),
+              bounds(key({2, std::nullopt}), key({2, std::nullopt}))});
+    range(key({2, 1}), key({2, 1}));
+    expect_ids({0});
+    clear_ranges();
+    range(key({2}), key({2}));
+    expect_ids({0, 1});
+    clear_ranges();
+    range(key({2}), std::nullopt, false);
+    expect_ids({});
+    clear_ranges();
+    range(std::nullopt, key({1}), false, false);
+    expect_ids({});
+    for (bool lo : {false, true}) {
+        for (bool hi : {false, true}) {
+            clear_ranges();
+            range(key({2, std::nullopt}), key({2, std::nullopt}), lo, hi);
+            expect_ids(lo && hi ? std::vector<uint64_t> {0, 1} : 
std::vector<uint64_t> {0});
+        }
+    }
+}
+
+TEST_F(SegmentKeyPruningTest, TruncatedBoundsOnlyPruneWhenProven) {
+    auto b = bounds(key({1, 100}), key({1, 200}));
+    b.mutable_min_key()->resize(5);
+    b.mutable_max_key()->resize(5);
+    segments({b});
+    meta->set_segments_key_bounds_truncated(true);
+    range(key({2}), key({2}));
+    expect_ids({});
+    clear_ranges();
+    range(key({1, 300}), key({1, 300}));
+    expect_ids({0});
+    b.mutable_min_key()->resize(2);
+    b.mutable_max_key()->resize(2);
+    segments({b});
+    range(key({2}), key({2}));
+    expect_ids({0});
+    clear_ranges();
+    range(key({-1}), key({-1}));
+    expect_ids({});
+    // One unknown side does not mask a proof from the other side.
+    b = bounds(key({1, 100}), key({3, 200}));
+    b.mutable_min_key()->resize(1);
+    segments({b});
+    clear_ranges();
+    range(key({4}), key({4}));
+    expect_ids({});
+}
+
+TEST_F(SegmentKeyPruningTest, ConservativeMetadataAndReaderFallbacks) {
+    const auto b = bounds(key({1, 1}), key({1, 5}));
+    segments({b});
+    range(key({9}), key({9}));
+    expect_ids({});
+    context.enable_unique_key_merge_on_write = false;
+    expect_ids({0});
+    context.enable_unique_key_merge_on_write = true;
+    meta->set_segments_key_bounds_aggregated(true);
+    expect_ids({0});
+    meta->set_segments_key_bounds_aggregated(false);
+    meta->set_segments_key_bounds({});
+    expect_ids({0});
+    meta->set_segments_key_bounds({b, b});
+    expect_ids({0});
+    meta->set_segments_key_bounds({KeyBoundsPB {}});
+    expect_ids({0});
+    auto invalid = b;
+    invalid.set_min_key("z");
+    invalid.set_max_key("a");
+    meta->set_segments_key_bounds({invalid});
+    expect_ids({0});
+    meta->set_segments_key_bounds({b});
+    meta->_schema.reset();
+    expect_ids({0});
+    persist_schema();
+    for (auto type : {ReaderType::READER_BASE_COMPACTION, 
ReaderType::READER_ALTER_TABLE}) {
+        context.reader_type = type;
+        expect_ids({0});
+    }
+    context.reader_type = ReaderType::READER_QUERY;
+    context.read_changelog = true;
+    expect_ids({0});
+    context.read_changelog = false;
+    context.read_schema =
+            std::make_shared<ReadSchema>(std::vector<TabletColumnPtr> 
{schema->columns()[2]});
+    expect_ids({0});
+    context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+    meta->tablet_schema()->_cluster_key_uids = {1};
+    expect_ids({0});
+    meta->tablet_schema()->_cluster_key_uids.clear();
+    meta->tablet_schema()->_sort_type = SortType::ZORDER;
+    expect_ids({0});
+    meta->tablet_schema()->_sort_type = SortType::LEXICAL;
+    // Mutate query schema only: the persisted schema was copied by 
set_tablet_schema.
+    schema->mutable_column(0).set_unique_id(99);
+    expect_ids({0});
+    schema->mutable_column(0).set_unique_id(1);
+    schema->mutable_column(0)._type = FieldType::OLAP_FIELD_TYPE_BIGINT;
+    expect_ids({0});
+    schema->mutable_column(0)._type = FieldType::OLAP_FIELD_TYPE_INT;
+    schema->mutable_column(0)._is_nullable = false;
+    expect_ids({0});
+    schema->mutable_column(0)._is_nullable = true;
+    schema->mutable_column(0).set_length(8);
+    expect_ids({0});
+    schema->mutable_column(0).set_length(4);
+    clear_ranges();
+    range(std::nullopt, std::nullopt);
+    expect_ids({0});
+    clear_ranges();
+    expect_ids({0});
+    for (int i = 0; i < 65; ++i) {
+        range(key({9}), key({9}));
+    }
+    expect_ids({0});
+    clear_ranges();
+    range(key({9}), key({9, 0}));
+    expect_ids({0});
+}
+
+TEST_F(SegmentKeyPruningTest, LinkedBoundsWithNewSchemaSurviveMetadataReload) {
+    context.enable_unique_key_merge_on_write = false;
+    // A linked DROP removes the integer key from the schema, not from the old 
bounds.
+    TabletSchemaPB pb;
+    schema->to_schema_pb(&pb);
+    pb.set_keys_type(DUP_KEYS);
+    pb.set_num_short_key_columns(1);
+    pb.mutable_column(0)->set_type("VARCHAR");
+    pb.mutable_column(0)->set_length(22);
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    RowCursor old;
+    ASSERT_TRUE(old.init_scan_key(schema, 
{Field::create_field<TYPE_STRING>("a"),
+                                           Field::create_field<TYPE_INT>(1)})
+                        .ok());
+    segments({bounds(old, old)});
+    pb.mutable_column()->DeleteSubrange(1, 1);
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    persist_schema();
+    context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+    range(std::nullopt, string_key("a"));
+    auto reload_and_check = [&] {
+        RowsetMetaPB saved;
+        meta->to_rowset_pb(&saved);
+        meta = std::make_shared<RowsetMeta>();
+        ASSERT_TRUE(meta->init_from_pb(saved));
+        expect_ids({0});
+    };
+    reload_and_check();
+
+    // Linked ADD inserts a default key before a key outside the short-key 
prefix.
+    pb.Clear();
+    pb.set_keys_type(DUP_KEYS);
+    pb.set_num_short_key_columns(3);
+    for (int i = 0; i < 5; ++i) {
+        auto* col = pb.add_column();
+        col->set_unique_id(i + 1);
+        col->set_name("c" + std::to_string(i));
+        col->set_type("INT");
+        col->set_length(4);
+        col->set_index_length(4);
+        col->set_is_key(i < 4);
+        col->set_is_nullable(false);
+    }
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    segments({bounds(key({1, 2, 3, 100}), key({1, 2, 3, 100}))});
+    auto* added = pb.add_column();
+    *added = pb.column(3);
+    added->set_unique_id(6);
+    added->set_name("new_key");
+    added->set_default_value("0");
+    pb.mutable_column()->SwapElements(3, 5);
+    pb.mutable_column()->SwapElements(4, 5);
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    persist_schema();
+    context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+    clear_ranges();
+    range(key({1, 2, 3, 0}), key({1, 2, 3, 0}));
+    reload_and_check();
+}
+
+TEST_F(SegmentKeyPruningTest, LongEndpointsChargeLimiterAndReleaseOnEveryExit) 
{
+    TabletSchemaPB pb;
+    schema->to_schema_pb(&pb);
+    pb.mutable_column(0)->set_type("VARCHAR");
+    pb.mutable_column(0)->set_length(32770);
+    pb.mutable_column(1)->set_is_key(false);
+    pb.set_num_short_key_columns(1);
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    persist_schema();
+    context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+    segments({bounds(string_key("a"), string_key("b"))});
+    for (int i = 0; i < 64; ++i) {
+        std::string value(32768, 'x');
+        value.back() = static_cast<char>(i);
+        range(string_key(value), string_key(value));
+    }
+    auto tracker = 
MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::QUERY,
+                                                    "segment-endpoint-test");
+    const auto old_consume_min = config::mem_tracker_consume_min_size_bytes;
+    config::mem_tracker_consume_min_size_bytes = 1;
+    Defer restore_consume_min {
+            [&] { config::mem_tracker_consume_min_size_bytes = 
old_consume_min; }};
+    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(tracker);
+    ++enable_thread_catch_bad_alloc;
+    Defer restore_catch {[] { --enable_thread_catch_bad_alloc; }};
+    const auto consumed = [&] {
+        thread_context()->thread_mem_tracker_mgr->flush_untracked_mem();
+        return tracker->consumption();
+    };
+    const auto baseline = consumed();
+    expect_ids({});
+    EXPECT_EQ(baseline, consumed());
+    EXPECT_GE(tracker->peak_consumption() - baseline, 128 * 32769);
+    // Reject the first payload, then reject after multiple endpoints have 
been encoded.
+    for (int64_t allowance : {int64_t {8192}, int64_t {2 << 20}}) {
+        tracker->set_limit(baseline + allowance);
+        try {
+            expect_ids({});
+            FAIL() << "Endpoint copies must respect the query limit";
+        } catch (const Exception& exception) {
+            EXPECT_EQ(exception.code(), ErrorCode::MEM_ALLOC_FAILED);
+        }
+        tracker->set_limit(-1);
+        EXPECT_EQ(baseline, consumed());
+    }
+    // A late unsupported OR endpoint must discard all earlier encoded buffers.
+    pb.mutable_column(0)->set_unique_id(99);
+    auto unsupported_schema = std::make_shared<TabletSchema>();
+    unsupported_schema->init_from_pb(pb);
+    RowCursor unsupported;
+    ASSERT_TRUE(unsupported
+                        .init_scan_key(unsupported_schema,
+                                       
{Field::create_field<TYPE_STRING>("fallback")})
+                        .ok());
+    lower.back() = std::move(unsupported);
+    expect_ids({0});
+    EXPECT_EQ(baseline, consumed());
+}
+
+TEST_F(SegmentKeyPruningTest, VarcharFullKeyAndUnsupportedStringPrefix) {
+    TabletSchemaPB pb;
+    schema->to_schema_pb(&pb);
+    pb.mutable_column(0)->set_type("VARCHAR");
+    pb.mutable_column(0)->set_length(100);
+    pb.mutable_column(1)->set_is_key(false);
+    pb.set_num_short_key_columns(1);
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    persist_schema();
+    context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+    segments({bounds(string_key("a"), string_key("a")), 
bounds(string_key("aa"), string_key("ab")),
+              bounds(string_key(""), string_key("")),
+              bounds(string_key(std::nullopt), string_key(std::nullopt))});
+    range(string_key("aa"), string_key("aa"));
+    expect_ids({1});
+    clear_ranges();
+    range(string_key(""), string_key(""));
+    expect_ids({2});
+    clear_ranges();
+    range(string_key(std::nullopt), string_key(std::nullopt));
+    expect_ids({3});
+    clear_ranges();
+    range(string_key("abc"), std::nullopt);
+    expect_ids({});
+    meta->set_segments_key_bounds_truncated(true);
+    expect_ids({0, 1, 2});
+    // Sequence suffixes and non-final VARCHAR columns cannot use length 
ordering.
+    meta->tablet_schema()->_sequence_col_idx = 2;
+    expect_ids({0, 1, 2, 3});
+    meta->tablet_schema()->_sequence_col_idx = -1;
+    meta->tablet_schema()->_num_key_columns = 2;
+    expect_ids({0, 1, 2, 3});
+}
+
+TEST_F(SegmentKeyPruningTest, SplitKeepsPhysicalIdsRowRangesAndDeleteBitmap) {
+    segments({bounds(key({0, 0}), key({0, 5})), bounds(key({1, 0}), key({1, 
5})),
+              bounds(key({2, 0}), key({2, 5})), bounds(key({3, 0}), key({3, 
5}))});
+    meta->set_segment_ids({100, 102, 105, 110});
+    range(key({3}), key({3}));
+    RowSetSplits splits;
+    splits.segment_offsets = {1, 4};
+    splits.segment_row_ranges = {RowRanges::create_single(10, 11), 
RowRanges::create_single(20, 22),
+                                 RowRanges::create_single(30, 33)};
+    context.version = {1, 1};
+    context.delete_bitmap = std::make_shared<DeleteBitmap>(12345);
+    context.delete_bitmap->add({meta->rowset_id(), 110, 1}, 31);
+    expect_ids({110}, splits);
+    auto rowset = std::make_shared<BetaRowset>(schema, meta, "");
+    BetaRowsetReader reader(rowset);
+    ASSERT_TRUE(reader.init(&context, splits).ok());
+    std::vector<RowwiseIteratorUPtr> iters;
+    ASSERT_TRUE(reader.get_segment_iterators(&context, &iters, false).ok());
+    ASSERT_EQ(1, iters.size());
+    auto* lazy = 
dynamic_cast<segment_v2::LazyInitSegmentIterator*>(iters[0].get());
+    ASSERT_NE(nullptr, lazy);
+    EXPECT_EQ(3, lazy->_segment.pos);
+    EXPECT_EQ(110, lazy->_segment.id);
+    EXPECT_EQ(3, lazy->_read_options.row_ranges.count());
+    EXPECT_EQ(30, lazy->_read_options.row_ranges.get_range_from(0));
+    ASSERT_EQ(1, lazy->_read_options.delete_bitmap.size());
+    EXPECT_TRUE(lazy->_read_options.delete_bitmap.at(110)->contains(31));
+}
+
+TEST_F(SegmentKeyPruningTest, EverySupportedIntegerWidth) {
+    const std::array<std::pair<const char*, int32_t>, 5> types {
+            {{"TINYINT", 1}, {"SMALLINT", 2}, {"INT", 4}, {"BIGINT", 8}, 
{"LARGEINT", 16}}};
+    for (auto [type, width] : types) {
+        SCOPED_TRACE(type);
+        TabletSchemaPB pb;
+        schema->to_schema_pb(&pb);
+        pb.mutable_column(0)->set_type(type);
+        pb.mutable_column(0)->set_length(width);
+        pb.mutable_column(0)->set_index_length(width);
+        schema = std::make_shared<TabletSchema>();
+        schema->init_from_pb(pb);
+        persist_schema();
+        context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+        auto typed_key = [&](int value) {
+            Field f;
+            switch (schema->column(0).type()) {
+            case FieldType::OLAP_FIELD_TYPE_TINYINT:
+                f = Field::create_field<TYPE_TINYINT>(cast_set<int8_t>(value));
+                break;
+            case FieldType::OLAP_FIELD_TYPE_SMALLINT:
+                f = 
Field::create_field<TYPE_SMALLINT>(cast_set<int16_t>(value));
+                break;
+            case FieldType::OLAP_FIELD_TYPE_INT:
+                f = Field::create_field<TYPE_INT>(value);
+                break;
+            case FieldType::OLAP_FIELD_TYPE_BIGINT:
+                f = Field::create_field<TYPE_BIGINT>(value);
+                break;
+            default:
+                f = Field::create_field<TYPE_LARGEINT>(value);
+            }
+            RowCursor cursor;
+            EXPECT_TRUE(cursor.init_scan_key(schema, {f}).ok());
+            return cursor;
+        };
+        segments({bounds(typed_key(-2), typed_key(-1)), bounds(typed_key(0), 
typed_key(1)),
+                  bounds(typed_key(2), typed_key(3))});
+        clear_ranges();
+        range(typed_key(0), typed_key(0));
+        expect_ids({1});
+    }
+}
+
+TEST_F(SegmentKeyPruningTest, 
FinalVarcharAfterNullableIntegerAndUnsupportedOrRange) {
+    TabletSchemaPB pb;
+    schema->to_schema_pb(&pb);
+    pb.mutable_column(1)->set_type("VARCHAR");
+    pb.mutable_column(1)->set_length(100);
+    schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(pb);
+    persist_schema();
+    context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+    auto composite = [&](std::optional<int32_t> prefix, std::string suffix) {
+        RowCursor cursor;
+        EXPECT_TRUE(cursor.init_scan_key(schema, {prefix ? 
Field::create_field<TYPE_INT>(*prefix)
+                                                         : 
Field(PrimitiveType::TYPE_NULL),
+                                                  
Field::create_field<TYPE_STRING>(suffix)})
+                            .ok());
+        return cursor;
+    };
+    segments({bounds(composite(std::nullopt, "a"), composite(std::nullopt, 
"aa")),
+              bounds(composite(1, "a"), composite(1, "ab")),
+              bounds(composite(2, "a"), composite(2, "ab"))});
+    range(composite(1, "aa"), composite(1, "aa"));
+    expect_ids({1});
+    clear_ranges();
+    range(composite(std::nullopt, "aa"), composite(std::nullopt, "aa"));
+    expect_ids({0});
+    clear_ranges();
+    range(key({1}), key({1}));
+    expect_ids({1});
+    // One supported range cannot justify dropping another OR range with a 
different schema.
+    TabletSchemaPB unsupported_pb = pb;
+    unsupported_pb.mutable_column(0)->set_unique_id(99);
+    auto unsupported_schema = std::make_shared<TabletSchema>();
+    unsupported_schema->init_from_pb(unsupported_pb);
+    RowCursor unsupported;
+    ASSERT_TRUE(
+            unsupported.init_scan_key(unsupported_schema, 
{Field::create_field<TYPE_INT>(2)}).ok());
+    range(unsupported.clone(), unsupported.clone());
+    expect_ids({0, 1, 2});
+}
+
+TEST_F(SegmentKeyPruningTest, ColdReaderOnOffAndEmptyMergeUnion) {
+    create_unique_tablet_schema(schema);
+    context.read_schema = std::make_shared<ReadSchema>(schema->columns());
+    ASSERT_TRUE(context.read_schema->init_from_tablet_schema(*schema, 
false).ok());
+    EngineOptions options;
+    StorageEngine engine(options);
+    RowsetSharedPtr rowset;
+    ASSERT_NO_FATAL_FAILURE(write_overlapping_rowset(
+            engine, schema, 10201,
+            {{{-2, 0, 0}, {-2, 4, 4}}, {{1, 1, 1}, {1, 4, 4}}, {{3, 1, 1}, {3, 
5, 5}}}, &rowset,
+            true));
+    ASSERT_EQ(3, rowset->num_segments());
+    ASSERT_EQ(3, rowset->rowset_meta()->get_segments_key_bounds().size());
+    ASSERT_FALSE(rowset->rowset_meta()->is_segments_key_bounds_aggregated());
+    ASSERT_NE(nullptr, rowset->rowset_meta()->tablet_schema());
+    range(key({1}), key({1}));
+    for (bool enabled : {false, true}) {
+        config::enable_segment_key_range_pruning = enabled;
+        SegmentLoader::instance()->erase_segments(*rowset->rowset_meta());
+        _stats = {};
+        EXPECT_EQ((std::vector<std::pair<int32_t, int32_t>> {{1, 1}, {1, 4}}),
+                  read_keys(rowset.get(), context));
+        EXPECT_EQ(enabled ? 2 : 0, _stats.segment_key_bounds_pruned);
+        EXPECT_EQ(enabled ? 1 : 3, _stats.segment_open_count);
+    }
+    // All-match negative control: no candidate is pruned.
+    clear_ranges();
+    range(key({-2}), key({3}));
+    for (bool enabled : {false, true}) {
+        config::enable_segment_key_range_pruning = enabled;
+        SegmentLoader::instance()->erase_segments(*rowset->rowset_meta());
+        _stats = {};
+        EXPECT_EQ(6, read_keys(rowset.get(), context).size());
+        EXPECT_EQ(0, _stats.segment_key_bounds_pruned);
+        EXPECT_EQ(3, _stats.segment_open_count);
+    }
+    clear_ranges();
+    range(key({9}), key({9}));
+    for (bool ordered : {false, true}) {

Review Comment:
   [P3] Exercise the empty merge path as well as union. The fixture's segments 
have strictly disjoint bounds, so BetaRowsetWriter marks them NONOVERLAPPING 
even though write_overlapping_rowset requests OVERLAPPING. 
BetaRowsetReader::is_merge_iterator also requires overlapping metadata, so 
changing need_ordered_result here runs union twice. Use actually overlapping 
segment bounds or explicitly set/assert the overlap metadata before the ordered 
all-pruned case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to