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

csun5285 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 6e6680944db [fix](storage) Fix reading a rowset whose segments overlap 
on keys (#69797)
6e6680944db is described below

commit 6e6680944db655d0b8d9da54eefa950bd2a16765
Author: Chenyang Sun <[email protected]>
AuthorDate: Tue Nov 24 10:56:14 2026 +0800

    [fix](storage) Fix reading a rowset whose segments overlap on keys (#69797)
    
    ### What problem does this PR solve?
    
    When one load flushes several memtables, its rowset has segments that
    overlap on keys, and the
    rowset reader merges them. Four bugs on that merge returned wrong rows;
    horizontal compaction reads
    through the same merge, so bugs 1 to 3 also wrote wrong rows into the
    compacted rowset.
    
    ```sql
    -- curl -X POST 
http://<be_host>:<be_webserver_port>/api/debug_point/add/MemTable.need_flush
    SET parallel_pipeline_task_num = 1;
    SET batch_size = 8192;
    
    CREATE TABLE mor_unique (k INT, v INT) UNIQUE KEY(k) DISTRIBUTED BY HASH(k) 
BUCKETS 1
    PROPERTIES ("replication_num" = "1", "disable_auto_compaction" = "true",
                "enable_unique_key_merge_on_write" = "false");
    CREATE TABLE agg_sum (k INT, s BIGINT SUM) AGGREGATE KEY(k) DISTRIBUTED BY 
HASH(k) BUCKETS 1
    PROPERTIES ("replication_num" = "1", "disable_auto_compaction" = "true");
    CREATE TABLE seq_map (k INT, v1 INT, s1 BIGINT, v2 INT, s2 BIGINT) UNIQUE 
KEY(k) DISTRIBUTED BY HASH(k) BUCKETS 1
    PROPERTIES ("replication_num" = "1", "disable_auto_compaction" = "true",
                "enable_unique_key_merge_on_write" = "false", 
"light_schema_change" = "true",
                "sequence_mapping.s1" = "v1", "sequence_mapping.s2" = "v2");
    CREATE TABLE mow_topn (k1 INT, k2 INT, v INT) UNIQUE KEY(k1, k2) 
DISTRIBUTED BY HASH(k1) BUCKETS 1
    PROPERTIES ("replication_num" = "1", "disable_auto_compaction" = "true",
                "enable_unique_key_merge_on_write" = "true");
    
    -- older write: v = k; newer write: v = 100 + k
    INSERT INTO mor_unique SELECT number % 4, number % 4 + if(number < 8192, 0, 
100) FROM numbers("number" = "16384");
    -- each write folds into s = 2048 per key, so every key sums to 4096
    INSERT INTO agg_sum SELECT number % 4, 1 FROM numbers("number" = "16384");
    -- older write: v1 = v2 = k, s1 = 2, s2 = 1; newer write: v1 = v2 = 100 + 
k, s1 = 1, s2 = 2
    INSERT INTO seq_map SELECT number % 4, number % 4 + if(number < 8192, 0, 
100), if(number < 8192, 2, 1),
                               number % 4 + if(number < 8192, 0, 100), 
if(number < 8192, 1, 2)
    FROM numbers("number" = "16384");
    -- older write: k2 = k1; newer write: k2 = k1 + 8192, so every k1 is in two 
keys
    INSERT INTO mow_topn SELECT number % 8192, number, number FROM 
numbers("number" = "16384");
    ```
    
    Results before the fix are from master `31a036fbcda`, after it from this
    PR.
    
    **1. A merge-on-read UNIQUE KEY table returns the older value (REPLACE
    columns of AGGREGATE KEY too):** the segment merge picks the newer row
    by `data_id()`, which `LazyInitSegmentIterator` (used for merges since
    #46570) answered with 0.
    
    ```sql
    SELECT k, v FROM mor_unique ORDER BY k;
    -- before: (0, 0) (1, 1) (2, 2) (3, 3)
    -- after:  (0, 100) (1, 101) (2, 102) (3, 103)
    ```
    
    **2. An AGGREGATE KEY table returns a key twice when a Block boundary
    cuts its rows (sequence-mapping tables too):** `Level0Iterator` took the
    same-key flag before loading the next Block, so the first row of every
    Block lost it.
    
    ```sql
    -- the segment merge yields k = 0 0 1 1 2 2 3 3; Blocks of 3 rows cut key 1
    SELECT /*+ SET_VAR(batch_size = 3) */ k, s FROM agg_sum ORDER BY k;
    -- before: (0, 4096) (1, 2048) (1, 2048) (2, 4096) (3, 4096)
    -- after:  (0, 4096) (1, 4096) (2, 4096) (3, 4096)
    ```
    
    **3. A sequence-mapping table loses a column group:** the segment merge
    kept one row per key, while each column group must come from the row
    with the largest value of its own sequence column (#54936 handled only
    the merge across rowsets).
    
    ```sql
    -- v1 must come from the older write (s1 = 2), v2 from the newer one (s2 = 
2)
    SELECT k, v1, s1, v2, s2 FROM seq_map ORDER BY k;
    -- before: (0, 0, 2, 0, 1) (1, 1, 2, 1, 1) (2, 2, 2, 2, 1) (3, 3, 2, 3, 1)
    -- after:  (0, 0, 2, 100, 2) (1, 1, 2, 101, 2) (2, 2, 2, 102, 2) (3, 3, 2, 
103, 2)
    ```
    
    **4. `ORDER BY <key prefix> LIMIT n` on a merge-on-write UNIQUE KEY
    table misses rows:** the storage TopN merges segments by the ORDER BY
    columns, on which different keys compare equal, but still dropped "same
    key" rows as older versions (#15663).
    
    ```sql
    SELECT * FROM (SELECT k1, k2 FROM mow_topn ORDER BY k1 LIMIT 4) t ORDER BY 
k1, k2;
    -- before: (0, 0) (1, 1) (2, 2) (3, 3)
    -- after:  (0, 0) (0, 8192) (1, 1) (1, 8193)
    ```
    
    Fixes: (1) `LazyInitSegmentIterator::data_id()` answers its segment id;
    (2) `Level0Iterator::next()`
    takes the same-key flag after `refresh_current_row()`; (3)
    `TabletReader` keeps every row of a key
    for a sequence-mapping table, and `BlockReader` merges the column
    groups; (4) `BetaRowsetReader`
    drops older rows only when it merges by the whole key (a merge-on-write
    table's delete bitmap
    already filters them).
    
    Issue Number: close #xxx
    
    Related PR: #xxx
    
    Problem Summary:
    
    ### Release note
    
    None
    
    ### Check List (For Author)
    
    - Test <!-- At least one of them must be included. -->
        - [ ] Regression test
        - [ ] Unit Test
        - [ ] Manual test (add detailed scripts or steps below)
        - [ ] No need to test or manual test. Explain why:
    - [ ] This is a refactor/code format and no logic has been changed.
            - [ ] Previous test can cover this change.
            - [ ] No code files have been changed.
            - [ ] Other reason <!-- Add your reason?  -->
    
    - Behavior changed:
        - [ ] No.
        - [ ] Yes. <!-- Explain the behavior change -->
    
    - Does this need documentation?
        - [ ] No.
    - [ ] Yes. <!-- Add document PR link here. eg:
    https://github.com/apache/doris-website/pull/1214 -->
    
    ### Check List (For Reviewer who merge this PR)
    
    - [ ] Confirm the release note
    - [ ] Confirm test cases
    - [ ] Confirm document
    - [ ] Add branch pick label <!-- Add branch pick label that this PR
    should merge into -->
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 be/src/storage/iterator/vcollect_iterator.cpp      |   8 +-
 be/src/storage/rowset/beta_rowset_reader.cpp       |   7 +-
 .../storage/segment/lazy_init_segment_iterator.h   |   4 +
 be/src/storage/tablet/tablet_reader.cpp            |   5 +-
 .../block_reader_overlapping_segments_test.cpp     | 473 +++++++++++++++++++++
 be/test/storage/rowset/beta_rowset_test.cpp        | 156 +++++++
 ...st_mow_topn_key_prefix_overlapping_segments.out |  76 ++++
 .../test_overlapping_segments_merge.out            |  45 ++
 ...mow_topn_key_prefix_overlapping_segments.groovy | 123 ++++++
 .../test_overlapping_segments_merge.groovy         | 172 ++++++++
 10 files changed, 1064 insertions(+), 5 deletions(-)

diff --git a/be/src/storage/iterator/vcollect_iterator.cpp 
b/be/src/storage/iterator/vcollect_iterator.cpp
index 50acc1c5ed3..256b5d0d4c5 100644
--- a/be/src/storage/iterator/vcollect_iterator.cpp
+++ b/be/src/storage/iterator/vcollect_iterator.cpp
@@ -555,15 +555,17 @@ Status 
VCollectIterator::Level0Iterator::next(IteratorRowRef* ref) {
         _current++;
     } else {
         _ref.row_pos++;
-        if (_is_merge_iterator && _ref.row_pos < _block->rows()) {
-            _ref.is_same = _row_is_same[_ref.row_pos];
-        }
     }
 
     RETURN_IF_ERROR(refresh_current_row());
 
     if (_get_data_by_ref) {
         _ref = _block_view[_current];
+    } else if (_is_merge_iterator) {
+        // After refresh_current_row(): when the previous row ended its Block, 
the refresh read the
+        // next Block and cleared is_same, so a bit taken before it was lost.
+        DCHECK_LT(static_cast<size_t>(_ref.row_pos), _row_is_same.size());
+        _ref.is_same = _row_is_same[_ref.row_pos];
     }
 
     *ref = _ref;
diff --git a/be/src/storage/rowset/beta_rowset_reader.cpp 
b/be/src/storage/rowset/beta_rowset_reader.cpp
index 3cd7b88cc99..7b99f95d2c1 100644
--- a/be/src/storage/rowset/beta_rowset_reader.cpp
+++ b/be/src/storage/rowset/beta_rowset_reader.cpp
@@ -345,7 +345,12 @@ Status BetaRowsetReader::_init_iterator() {
         if (_read_options.changelog_tso_idx != -1) {
             sequence_loc = _read_options.changelog_tso_idx;
         }
-        _iterator = new_merge_iterator(std::move(iterators), sequence_loc, 
_read_context->is_unique,
+        // Only a merge by the whole key may drop the older versions of a key. 
A storage TopN merges
+        // by its ORDER BY key prefix, on which rows of different keys compare 
equal, and it only
+        // reads merge-on-write tables, whose delete bitmap already filters 
the older versions.
+        const bool drop_older_versions =
+                _read_context->is_unique && 
_read_context->read_orderby_key_columns == nullptr;
+        _iterator = new_merge_iterator(std::move(iterators), sequence_loc, 
drop_older_versions,
                                        _read_context->read_orderby_key_reverse,
                                        _read_context->merged_rows, 
_read_context->read_schema,
                                        _read_options.changelog_tso_idx != -1);
diff --git a/be/src/storage/segment/lazy_init_segment_iterator.h 
b/be/src/storage/segment/lazy_init_segment_iterator.h
index 381f71162ba..ba4a558ae4b 100644
--- a/be/src/storage/segment/lazy_init_segment_iterator.h
+++ b/be/src/storage/segment/lazy_init_segment_iterator.h
@@ -50,6 +50,10 @@ public:
 
     const ReadSchema& schema() const override { return *_schema; }
 
+    // The segment merge takes the newer row of a key from the segment with 
the larger data_id. The
+    // segment id is known before init() loads the segment, unlike the inner 
iterator.
+    uint64_t data_id() const override { return 
static_cast<uint64_t>(_segment.id); }
+
     void update_profile(RuntimeProfile* profile) override {
         if (_inner_iterator != nullptr) {
             _inner_iterator->update_profile(profile);
diff --git a/be/src/storage/tablet/tablet_reader.cpp 
b/be/src/storage/tablet/tablet_reader.cpp
index e26c87f2a73..9d388e0045c 100644
--- a/be/src/storage/tablet/tablet_reader.cpp
+++ b/be/src/storage/tablet/tablet_reader.cpp
@@ -179,7 +179,10 @@ Status TabletReader::_capture_rs_readers(const 
ReaderParams& read_params) {
     _reader_context.delete_handler = &_delete_handler;
     _reader_context.stats = &_stats;
     _reader_context.use_page_cache = read_params.use_page_cache;
-    _reader_context.is_unique = tablet()->keys_type() == UNIQUE_KEYS;
+    // A table with a sequence map needs every row of a key: each column group 
comes from the row
+    // with the largest sequence value of that group.
+    _reader_context.is_unique =
+            tablet()->keys_type() == UNIQUE_KEYS && 
!_tablet_schema->has_seq_map();
     _reader_context.merged_rows = &_merged_rows;
     _reader_context.delete_bitmap = read_params.delete_bitmap;
     _reader_context.enable_unique_key_merge_on_write = 
tablet()->enable_unique_key_merge_on_write();
diff --git 
a/be/test/storage/iterator/block_reader_overlapping_segments_test.cpp 
b/be/test/storage/iterator/block_reader_overlapping_segments_test.cpp
new file mode 100644
index 00000000000..835bf8cf412
--- /dev/null
+++ b/be/test/storage/iterator/block_reader_overlapping_segments_test.cpp
@@ -0,0 +1,473 @@
+// 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.
+
+// One load that flushes several memtables writes a rowset whose segments 
overlap on keys, so the
+// same key can sit in two segments of one rowset. Reading such a rowset takes 
two merges: the
+// rowset reader merges its segments (VMergeIterator over 
LazyInitSegmentIterators) and marks
+// every row whose key repeats the row before it, then VCollectIterator merges 
the rowsets and
+// hands every row with its same-key bit to the BlockReader fold. These tests 
write such rowsets
+// for AGG_KEYS, merge-on-read UNIQUE_KEYS and sequence-map UNIQUE_KEYS 
tables, read them through
+// BlockReader as a query and as a compaction, with Block sizes that cut key 
groups in two, and
+// check the rows that come back:
+//   - the row of the segment flushed later is the newer row of its key;
+//   - a key group cut by a Block boundary is still folded into one row;
+//   - a sequence-map table still sees every row of a key, so every column 
group takes the row
+//     with its own largest sequence value.
+
+#include <gen_cpp/olap_file.pb.h>
+#include <gtest/gtest.h>
+#include <unistd.h>
+
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "common/config.h"
+#include "common/status.h"
+#include "core/block/block.h"
+#include "core/column/column.h"
+#include "core/column/column_nullable.h"
+#include "io/fs/local_file_system.h"
+#include "runtime/exec_env.h"
+#include "storage/iterator/block_reader.h"
+#include "storage/iterators.h"
+#include "storage/olap_common.h"
+#include "storage/rowset/beta_rowset.h"
+#include "storage/rowset/rowset.h"
+#include "storage/rowset/rowset_factory.h"
+#include "storage/rowset/rowset_reader.h"
+#include "storage/rowset/rowset_writer.h"
+#include "storage/rowset/rowset_writer_context.h"
+#include "storage/schema.h"
+#include "storage/segment/lazy_init_segment_iterator.h"
+#include "storage/storage_engine.h"
+#include "storage/tablet/base_tablet.h"
+#include "storage/tablet/tablet.h"
+#include "storage/tablet/tablet_meta.h"
+#include "storage/tablet/tablet_reader.h"
+#include "storage/tablet/tablet_schema.h"
+#include "util/uid_util.h"
+
+namespace doris {
+
+namespace {
+
+constexpr uint32_t kMaxPathLen = 1024;
+
+// One tablet column of a test schema. Every cell is an int64_t in the tests.
+struct ColumnSpec {
+    ColumnSpec(std::string name_, std::string type_, bool is_key_ = false,
+               std::string aggregation_ = "")
+            : name(std::move(name_)),
+              type(std::move(type_)),
+              is_key(is_key_),
+              aggregation(std::move(aggregation_)) {}
+
+    std::string name;
+    std::string type; // INT, BIGINT or TINYINT
+    bool is_key;
+    std::string aggregation; // AGG_KEYS value columns only
+};
+
+using Row = std::vector<int64_t>;
+// Sequence map of a UNIQUE_KEYS schema: each sequence column with the one 
value column it governs.
+using SequenceMapSpec = std::vector<std::pair<std::string, std::string>>;
+
+int column_length(const std::string& type) {
+    if (type == "INT") {
+        return 4;
+    }
+    if (type == "BIGINT") {
+        return 8;
+    }
+    DORIS_CHECK_EQ(type, "TINYINT");
+    return 1;
+}
+
+TPrimitiveType::type thrift_type(FieldType type) {
+    switch (type) {
+    case FieldType::OLAP_FIELD_TYPE_INT:
+        return TPrimitiveType::INT;
+    case FieldType::OLAP_FIELD_TYPE_BIGINT:
+        return TPrimitiveType::BIGINT;
+    case FieldType::OLAP_FIELD_TYPE_TINYINT:
+        return TPrimitiveType::TINYINT;
+    default:
+        DORIS_CHECK(false) << "unexpected test column type " << 
static_cast<int>(type);
+        return TPrimitiveType::INVALID_TYPE;
+    }
+}
+
+TKeysType::type thrift_keys_type(KeysType keys_type) {
+    switch (keys_type) {
+    case KeysType::UNIQUE_KEYS:
+        return TKeysType::UNIQUE_KEYS;
+    case KeysType::AGG_KEYS:
+        return TKeysType::AGG_KEYS;
+    default:
+        DORIS_CHECK(false) << "unexpected keys type " << 
static_cast<int>(keys_type);
+        return TKeysType::DUP_KEYS;
+    }
+}
+
+void append_cell(IColumn& column, FieldType type, int64_t value) {
+    switch (type) {
+    case FieldType::OLAP_FIELD_TYPE_INT: {
+        auto v = static_cast<int32_t>(value);
+        column.insert_data(reinterpret_cast<const char*>(&v), sizeof(v));
+        return;
+    }
+    case FieldType::OLAP_FIELD_TYPE_BIGINT:
+        column.insert_data(reinterpret_cast<const char*>(&value), 
sizeof(value));
+        return;
+    case FieldType::OLAP_FIELD_TYPE_TINYINT: {
+        auto v = static_cast<int8_t>(value);
+        column.insert_data(reinterpret_cast<const char*>(&v), sizeof(v));
+        return;
+    }
+    default:
+        DORIS_CHECK(false) << "unexpected test column type " << 
static_cast<int>(type);
+    }
+}
+
+int64_t read_cell(const IColumn& column, size_t row) {
+    const IColumn* col = &column;
+    if (const auto* nullable = check_and_get_column<ColumnNullable>(*col)) {
+        DORIS_CHECK(!nullable->is_null_at(row));
+        col = &nullable->get_nested_column();
+    }
+    return col->get_int(row);
+}
+
+std::string trace(ReaderType reader_type, int batch_size) {
+    return "reader_type=" + std::to_string(static_cast<int>(reader_type)) +
+           " batch_size=" + std::to_string(batch_size);
+}
+
+// A query and a compaction both read through BlockReader, with Blocks of 1, 2 
and 3 rows that cut
+// key groups in two and with Blocks that hold the whole merge.
+constexpr std::array kReaderTypes = {ReaderType::READER_QUERY,
+                                     ReaderType::READER_CUMULATIVE_COMPACTION};
+constexpr std::array kBatchSizes = {1, 2, 3, 100};
+
+} // namespace
+
+class BlockReaderOverlappingSegmentsTest : public testing::Test {
+protected:
+    void SetUp() override {
+        char buffer[kMaxPathLen];
+        EXPECT_NE(getcwd(buffer, kMaxPathLen), nullptr);
+        _absolute_dir = std::string(buffer) + 
"/ut_dir/block_reader_overlapping_segments_test";
+        auto st = 
io::global_local_filesystem()->delete_directory(_absolute_dir);
+        ASSERT_TRUE(st.ok()) << st;
+        st = io::global_local_filesystem()->create_directory(_absolute_dir + 
"/tablet_path");
+        ASSERT_TRUE(st.ok()) << st;
+        doris::EngineOptions options;
+        auto engine = std::make_unique<StorageEngine>(options);
+        _engine = engine.get();
+        ExecEnv::GetInstance()->set_storage_engine(std::move(engine));
+        _saved_adaptive_batch_size = config::enable_adaptive_batch_size;
+        // Row-count limits only, so the Block boundaries of a read are 
deterministic.
+        config::enable_adaptive_batch_size = false;
+    }
+
+    void TearDown() override {
+        config::enable_adaptive_batch_size = _saved_adaptive_batch_size;
+        
EXPECT_TRUE(io::global_local_filesystem()->delete_directory(_absolute_dir).ok());
+        _engine = nullptr;
+        ExecEnv::GetInstance()->set_storage_engine(nullptr);
+    }
+
+    // Column unique ids are the positions in `columns`.
+    static TabletSchemaSPtr make_schema(KeysType keys_type, const 
std::vector<ColumnSpec>& columns,
+                                        const SequenceMapSpec& sequence_map = 
{}) {
+        TabletSchemaPB pb;
+        pb.set_keys_type(keys_type);
+        pb.set_num_short_key_columns(1);
+        pb.set_num_rows_per_row_block(1024);
+        pb.set_compress_kind(COMPRESS_NONE);
+        pb.set_next_column_unique_id(static_cast<int32_t>(columns.size()));
+        auto uid_of = [&](const std::string& name) -> int32_t {
+            for (size_t i = 0; i < columns.size(); ++i) {
+                if (columns[i].name == name) {
+                    return static_cast<int32_t>(i);
+                }
+            }
+            DORIS_CHECK(false) << "unknown column " << name;
+            return -1;
+        };
+        for (size_t i = 0; i < columns.size(); ++i) {
+            const auto& spec = columns[i];
+            ColumnPB* column = pb.add_column();
+            column->set_unique_id(static_cast<int32_t>(i));
+            column->set_name(spec.name);
+            column->set_type(spec.type);
+            column->set_is_key(spec.is_key);
+            column->set_length(column_length(spec.type));
+            column->set_index_length(column_length(spec.type));
+            column->set_is_nullable(false);
+            if (!spec.aggregation.empty()) {
+                column->set_aggregation(spec.aggregation);
+            }
+        }
+        for (const auto& [sequence_column, value_column] : sequence_map) {
+            ColumnGroupPB* group = pb.mutable_seq_map()->add_cg();
+            group->set_sequence_column(uid_of(sequence_column));
+            group->add_columns_in_group(uid_of(value_column));
+        }
+        auto schema = std::make_shared<TabletSchema>();
+        schema->init_from_pb(pb);
+        return schema;
+    }
+
+    // One rowset with one segment per entry of `segments`, declared 
OVERLAPPING when there are
+    // several, like the rowset of one load that flushed several memtables: 
segment i + 1 was
+    // flushed after segment i. Rows of a segment must be in key order.
+    RowsetSharedPtr write_rowset(const TabletSchemaSPtr& schema,
+                                 const std::vector<std::vector<Row>>& 
segments, int64_t version) {
+        static int64_t next_rowset_id = 10000;
+        RowsetWriterContext context;
+        RowsetId rowset_id;
+        rowset_id.init(next_rowset_id++);
+        context.rowset_id = rowset_id;
+        context.rowset_type = BETA_ROWSET;
+        context.rowset_state = VISIBLE;
+        context.tablet_schema = schema;
+        context.tablet_path = _absolute_dir + "/tablet_path";
+        context.version = Version(version, version);
+        context.segments_overlap = segments.size() > 1 ? OVERLAPPING : 
NONOVERLAPPING;
+        context.max_rows_per_segment = UINT32_MAX;
+        auto res = RowsetFactory::create_rowset_writer(*_engine, context, 
false);
+        EXPECT_TRUE(res.has_value()) << res.error();
+        auto writer = std::move(res).value();
+
+        for (const auto& segment : segments) {
+            Block block = schema->create_storage_block();
+            {
+                auto columns_guard = block.mutate_columns_scoped();
+                auto& columns = columns_guard.mutable_columns();
+                for (const auto& row : segment) {
+                    EXPECT_EQ(row.size(), columns.size());
+                    for (size_t c = 0; c < columns.size(); ++c) {
+                        append_cell(*columns[c], schema->column(c).type(), 
row[c]);
+                    }
+                }
+            }
+            EXPECT_TRUE(writer->add_block(&block).ok());
+            EXPECT_TRUE(writer->flush().ok());
+        }
+
+        RowsetSharedPtr rowset;
+        EXPECT_TRUE(writer->build(rowset).ok());
+        EXPECT_EQ(segments.size(), rowset->num_segments());
+        return rowset;
+    }
+
+    // A merge-on-read tablet of `schema`.
+    TabletSharedPtr create_tablet(const TabletSchema& schema) {
+        std::vector<TColumn> columns;
+        std::unordered_map<uint32_t, uint32_t> col_ordinal_to_unique_id;
+        for (size_t i = 0; i < schema.num_columns(); ++i) {
+            const TabletColumn& column = schema.column(i);
+            TColumn t_column;
+            t_column.column_type.type = thrift_type(column.type());
+            t_column.__set_column_name(column.name());
+            t_column.__set_is_key(column.is_key());
+            columns.push_back(t_column);
+            col_ordinal_to_unique_id[static_cast<uint32_t>(i)] = 
column.unique_id();
+        }
+        TTabletSchema t_schema;
+        t_schema.__set_short_key_column_count(schema.num_short_key_columns());
+        t_schema.__set_schema_hash(3333);
+        t_schema.__set_keys_type(thrift_keys_type(schema.keys_type()));
+        t_schema.__set_storage_type(TStorageType::COLUMN);
+        t_schema.__set_columns(columns);
+        TabletMetaSharedPtr tablet_meta(new TabletMeta(
+                1, 1, 1, 1, 1, 1, t_schema, 1, col_ordinal_to_unique_id, 
UniqueId(1, 2),
+                TTabletType::TABLET_TYPE_DISK, TCompressionType::LZ4F, 0,
+                /*enable_unique_key_merge_on_write=*/false));
+        TabletSharedPtr tablet(new Tablet(*_engine, tablet_meta, nullptr));
+        static_cast<void>(tablet->init());
+        return tablet;
+    }
+
+    // Read `rowsets` through BlockReader the way a scan or a compaction of 
`reader_type` with
+    // `batch_size` rows per Block does, and return every row in output order.
+    static std::vector<Row> read(const TabletSharedPtr& tablet, const 
TabletSchemaSPtr& schema,
+                                 const std::vector<RowsetSharedPtr>& rowsets,
+                                 ReaderType reader_type, int batch_size) {
+        TabletReader::ReaderParams params;
+        params.tablet = tablet;
+        params.tablet_schema = schema;
+        params.reader_type = reader_type;
+        params.version = Version(0, rowsets.back()->end_version());
+        TabletReadSource read_source;
+        for (const auto& rowset : rowsets) {
+            RowsetReaderSharedPtr rs_reader;
+            EXPECT_TRUE(rowset->create_reader(&rs_reader).ok());
+            read_source.rs_splits.emplace_back(std::move(rs_reader));
+        }
+        read_source.fill_delete_predicates();
+        params.set_read_source(std::move(read_source));
+        params.read_schema = std::make_shared<ReadSchema>(schema->columns());
+
+        BlockReader reader;
+        reader.set_batch_size(batch_size);
+        Status st = reader.init(params);
+        EXPECT_TRUE(st.ok()) << st;
+        std::vector<Row> rows;
+        bool eof = !st.ok();
+        while (!eof) {
+            Block block = params.read_schema->create_read_block();
+            st = reader.next_block_with_aggregation(&block, &eof);
+            EXPECT_TRUE(st.ok()) << st;
+            if (!st.ok()) {
+                break;
+            }
+            for (size_t r = 0; r < block.rows(); ++r) {
+                Row row;
+                for (size_t c = 0; c < block.columns(); ++c) {
+                    row.push_back(read_cell(*block.get_by_position(c).column, 
r));
+                }
+                rows.push_back(std::move(row));
+            }
+        }
+        return rows;
+    }
+
+    StorageEngine* _engine = nullptr;
+    std::string _absolute_dir;
+    bool _saved_adaptive_batch_size = false;
+};
+
+// The segment merge orders the rows of one key (and one sequence value) by 
the data_id of their
+// iterators: the row of the segment flushed later is the newer one. The merge 
may ask before the
+// lazy iterator has loaded its segment, so data_id must name the segment 
without loading it, and
+// keep naming it once the segment is loaded.
+TEST_F(BlockReaderOverlappingSegmentsTest, 
LazySegmentIteratorDataIdIsTheSegmentId) {
+    auto schema = make_schema(KeysType::UNIQUE_KEYS,
+                              {{"k", "INT", true}, {"v", "INT"}, {DELETE_SIGN, 
"TINYINT"}});
+    auto rowset = std::static_pointer_cast<BetaRowset>(
+            write_rowset(schema, {{{1, 10, 0}, {2, 20, 0}}, {{1, 11, 0}}}, 
/*version=*/2));
+    auto read_schema = std::make_shared<ReadSchema>(schema->columns());
+    OlapReaderStatistics stats;
+    StorageReadOptions opts(stats);
+
+    for (int64_t pos = 0; pos < rowset->num_segments(); ++pos) {
+        SCOPED_TRACE("segment pos=" + std::to_string(pos));
+        const RowsetSegmentRef segment = 
rowset->segment(static_cast<size_t>(pos)).ref();
+        segment_v2::LazyInitSegmentIterator iter(rowset, segment, 
/*should_use_cache=*/false,
+                                                 read_schema, opts);
+        EXPECT_EQ(iter.data_id(), static_cast<uint64_t>(segment.id));
+
+        ASSERT_TRUE(iter.init(opts).ok());
+        Block block = read_schema->create_read_block();
+        ASSERT_TRUE(iter.next_batch(&block).ok());
+        EXPECT_EQ(iter.data_id(), static_cast<uint64_t>(segment.id));
+    }
+}
+
+// Merge-on-read UNIQUE_KEYS without a sequence column: keys 1 and 3 sit in 
both overlapping
+// segments of one rowset, and the rows of segment 1 are the newer ones that a 
read keeps.
+TEST_F(BlockReaderOverlappingSegmentsTest, 
UniqueKeysKeepTheRowOfTheLaterSegment) {
+    auto schema = make_schema(KeysType::UNIQUE_KEYS,
+                              {{"k", "INT", true}, {"v", "INT"}, {DELETE_SIGN, 
"TINYINT"}});
+    auto tablet = create_tablet(*schema);
+    std::vector<RowsetSharedPtr> rowsets = {
+            write_rowset(schema, {{{1, 10, 0}, {2, 20, 0}, {3, 30, 0}}, {{1, 
11, 0}, {3, 31, 0}}},
+                         /*version=*/2),
+    };
+
+    for (ReaderType reader_type : kReaderTypes) {
+        for (int batch_size : kBatchSizes) {
+            SCOPED_TRACE(trace(reader_type, batch_size));
+            EXPECT_EQ(read(tablet, schema, rowsets, reader_type, batch_size),
+                      (std::vector<Row> {{1, 11, 0}, {2, 20, 0}, {3, 31, 0}}));
+        }
+    }
+}
+
+// AGG_KEYS: both overlapping segments of the lowest-version rowset hold keys 
1..3, so its
+// segment merge yields 1 1 2 2 3 3 and Blocks of 1, 2 or 3 rows cut key 
groups in two. Every key
+// must still come back once, with the SUM of all its rows and the REPLACE 
value of its newest
+// row: the later segment within the rowset, the newer rowset when there is 
one.
+TEST_F(BlockReaderOverlappingSegmentsTest, AggKeysFoldEveryKeyGroupOnce) {
+    auto schema = make_schema(
+            KeysType::AGG_KEYS,
+            {{"k", "INT", true}, {"s", "BIGINT", false, "SUM"}, {"r", "INT", 
false, "REPLACE"}});
+    auto tablet = create_tablet(*schema);
+    auto overlapping = write_rowset(
+            schema, {{{1, 1, 10}, {2, 2, 20}, {3, 3, 30}}, {{1, 10, 11}, {2, 
20, 21}, {3, 30, 31}}},
+            /*version=*/2);
+    auto newer = write_rowset(schema, {{{2, 200, 22}, {3, 300, 32}}}, 
/*version=*/3);
+    const std::vector<std::pair<std::vector<RowsetSharedPtr>, 
std::vector<Row>>> cases = {
+            {{overlapping}, {{1, 11, 11}, {2, 22, 21}, {3, 33, 31}}},
+            {{overlapping, newer}, {{1, 11, 11}, {2, 222, 22}, {3, 333, 32}}},
+    };
+
+    for (const auto& [rowsets, expected] : cases) {
+        for (ReaderType reader_type : kReaderTypes) {
+            for (int batch_size : kBatchSizes) {
+                SCOPED_TRACE("rowsets=" + std::to_string(rowsets.size()) + " " 
+
+                             trace(reader_type, batch_size));
+                EXPECT_EQ(read(tablet, schema, rowsets, reader_type, 
batch_size), expected);
+            }
+        }
+    }
+}
+
+// UNIQUE_KEYS with the sequence map {s1 -> v1, s2 -> v2}: every column group 
takes the values of
+// the row with its own largest sequence value, so the read must see every row 
of a key. Key 1
+// sits in both overlapping segments of one rowset and, in the second case, in 
a newer rowset too:
+// s1 is largest in segment 0, s2 in segment 1 or in the newer rowset, so no 
single row holds the
+// result.
+TEST_F(BlockReaderOverlappingSegmentsTest, SequenceMapMergesEveryColumnGroup) {
+    auto schema = make_schema(KeysType::UNIQUE_KEYS,
+                              {{"k", "INT", true},
+                               {"v1", "INT"},
+                               {"s1", "BIGINT"},
+                               {"v2", "INT"},
+                               {"s2", "BIGINT"},
+                               {DELETE_SIGN, "TINYINT"}},
+                              {{"s1", "v1"}, {"s2", "v2"}});
+    ASSERT_TRUE(schema->has_seq_map());
+    auto tablet = create_tablet(*schema);
+    auto overlapping = write_rowset(
+            schema, {{{1, 10, 5, 100, 1, 0}, {2, 20, 1, 200, 1, 0}}, {{1, 11, 
3, 101, 7, 0}}},
+            /*version=*/2);
+    auto newer = write_rowset(schema, {{{1, 12, 4, 102, 9, 0}}}, 
/*version=*/3);
+    const std::vector<std::pair<std::vector<RowsetSharedPtr>, 
std::vector<Row>>> cases = {
+            {{overlapping}, {{1, 10, 5, 101, 7, 0}, {2, 20, 1, 200, 1, 0}}},
+            {{overlapping, newer}, {{1, 10, 5, 102, 9, 0}, {2, 20, 1, 200, 1, 
0}}},
+    };
+
+    for (const auto& [rowsets, expected] : cases) {
+        for (ReaderType reader_type : kReaderTypes) {
+            for (int batch_size : kBatchSizes) {
+                SCOPED_TRACE("rowsets=" + std::to_string(rowsets.size()) + " " 
+
+                             trace(reader_type, batch_size));
+                EXPECT_EQ(read(tablet, schema, rowsets, reader_type, 
batch_size), expected);
+            }
+        }
+    }
+}
+
+} // namespace doris
diff --git a/be/test/storage/rowset/beta_rowset_test.cpp 
b/be/test/storage/rowset/beta_rowset_test.cpp
index 52e3e46e05f..1eee35733c6 100644
--- a/be/test/storage/rowset/beta_rowset_test.cpp
+++ b/be/test/storage/rowset/beta_rowset_test.cpp
@@ -33,6 +33,7 @@
 #include <unistd.h>
 
 #include <algorithm>
+#include <array>
 #include <memory>
 #include <string>
 #include <tuple>
@@ -41,6 +42,7 @@
 
 #include "common/config.h"
 #include "common/status.h"
+#include "core/block/block.h"
 #include "cpp/obj-storage/client/s3_obj_storage_client.h"
 #include "cpp/obj-storage/parser/obj_storage_config.h"
 #include "cpp/sync_point.h"
@@ -55,9 +57,12 @@
 #include "storage/options.h"
 #include "storage/rowset/beta_rowset_writer.h"
 #include "storage/rowset/rowset.h"
+#include "storage/rowset/rowset_factory.h"
 #include "storage/rowset/rowset_meta.h"
 #include "storage/rowset/rowset_reader.h"
+#include "storage/rowset/rowset_reader_context.h"
 #include "storage/rowset/rowset_writer_context.h"
+#include "storage/schema.h"
 #include "storage/segment/segment.h"
 #include "storage/storage_engine.h"
 #include "storage/storage_policy.h"
@@ -176,6 +181,102 @@ protected:
         EXPECT_EQ(Status::OK(), s);
     }
 
+    // (k1 int, k2 int, v int) unique key (k1, k2)
+    void create_unique_tablet_schema(TabletSchemaSPtr tablet_schema) {
+        TabletSchemaPB tablet_schema_pb;
+        tablet_schema_pb.set_keys_type(UNIQUE_KEYS);
+        tablet_schema_pb.set_num_short_key_columns(2);
+        tablet_schema_pb.set_num_rows_per_row_block(1024);
+        tablet_schema_pb.set_compress_kind(COMPRESS_NONE);
+        tablet_schema_pb.set_next_column_unique_id(4);
+        const std::array<const char*, 3> names {"k1", "k2", "v"};
+        for (int32_t i = 0; i < 3; ++i) {
+            ColumnPB* column = tablet_schema_pb.add_column();
+            column->set_unique_id(i + 1);
+            column->set_name(names[i]);
+            column->set_type("INT");
+            column->set_is_key(i < 2);
+            column->set_length(4);
+            column->set_index_length(4);
+            column->set_is_nullable(false);
+            column->set_is_bf_column(false);
+        }
+        tablet_schema->init_from_pb(tablet_schema_pb);
+    }
+
+    // The rowset one load wrote when it flushed several memtables: segment i 
holds the rows
+    // (k1, k2, v) of `segments[i]`, and the segments overlap on keys.
+    void write_overlapping_rowset(StorageEngine& engine, TabletSchemaSPtr 
tablet_schema,
+                                  int64_t rowset_id,
+                                  const 
std::vector<std::vector<std::array<int32_t, 3>>>& segments,
+                                  RowsetSharedPtr* rowset) {
+        RowsetWriterContext context;
+        create_rowset_writer_context(tablet_schema, &context);
+        context.rowset_id.init(rowset_id);
+        context.segments_overlap = OVERLAPPING;
+        auto writer = RowsetFactory::create_rowset_writer(engine, context, 
false);
+        ASSERT_TRUE(writer.has_value()) << writer.error();
+        for (const auto& rows : segments) {
+            Block block = tablet_schema->create_storage_block();
+            {
+                auto columns_guard = block.mutate_columns_scoped();
+                auto& columns = columns_guard.mutable_columns();
+                for (const auto& row : rows) {
+                    for (size_t i = 0; i < row.size(); ++i) {
+                        columns[i]->insert_data(reinterpret_cast<const 
char*>(&row[i]),
+                                                sizeof(int32_t));
+                    }
+                }
+            }
+            auto st = writer.value()->add_block(&block);
+            ASSERT_TRUE(st.ok()) << st;
+            st = writer.value()->flush();
+            ASSERT_TRUE(st.ok()) << st;
+        }
+        auto st = writer.value()->build(*rowset);
+        ASSERT_TRUE(st.ok()) << st;
+    }
+
+    // The (k1, k2) of every row a reader of `rowset` initialized with 
`context` returns.
+    std::vector<std::pair<int32_t, int32_t>> read_keys(Rowset* rowset,
+                                                       RowsetReaderContext& 
context) {
+        RowsetReaderSharedPtr reader;
+        create_and_init_rowset_reader(rowset, context, &reader);
+        std::vector<std::pair<int32_t, int32_t>> keys;
+        Status st;
+        do {
+            Block block = context.read_schema->create_read_block();
+            st = reader->next_batch(&block);
+            for (size_t row = 0; row < block.rows(); ++row) {
+                keys.emplace_back(
+                        
static_cast<int32_t>(block.get_by_position(0).column->get_int(row)),
+                        
static_cast<int32_t>(block.get_by_position(1).column->get_int(row)));
+            }
+        } while (st.ok());
+        EXPECT_TRUE(st.is<END_OF_FILE>()) << st;
+        return keys;
+    }
+
+    // The reader context of a read of every column of `tablet_schema` that 
merges the overlapping
+    // segments of a UNIQUE_KEYS rowset, by `orderby_key_columns` when not 
null and by the whole
+    // key otherwise.
+    RowsetReaderContext unique_merge_context(const TabletSchema& tablet_schema,
+                                             std::vector<uint32_t>* 
orderby_key_columns) {
+        auto read_schema = 
std::make_shared<ReadSchema>(tablet_schema.columns());
+        EXPECT_TRUE(read_schema
+                            ->init_from_tablet_schema(tablet_schema,
+                                                      
/*merge_by_sequence_mapping=*/false,
+                                                      
/*map_changelog_columns=*/false)
+                            .ok());
+        RowsetReaderContext context;
+        context.read_schema = read_schema;
+        context.stats = &_stats;
+        context.need_ordered_result = true;
+        context.is_unique = true;
+        context.read_orderby_key_columns = orderby_key_columns;
+        return context;
+    }
+
     void init_rs_meta(RowsetMetaSharedPtr& pb1, int64_t start, int64_t end) {
         std::string json_rowset_meta = R"({
             "rowset_id": 540085,
@@ -763,4 +864,59 @@ TEST_F(BetaRowsetTest, GetNumSegmentRowsAPI) {
     ASSERT_EQ(segment_rows[2], 300);
 }
 
+// A merge-on-write SELECT ... ORDER BY k1 LIMIT n is read by a storage TopN, 
which merges the
+// overlapping segments of a rowset by the ORDER BY prefix 
(read_orderby_key_columns). Rows equal
+// on k1 are different keys, so the merge keeps all of them although the table 
is UNIQUE_KEYS:
+// one load wrote (k1 = i, k2 = i) into the first segment and (k1 = i, k2 = i 
+ 20) into the
+// second, and all 40 rows come back in k1 order.
+TEST_F(BetaRowsetTest, OrderByKeyPrefixMergeKeepsRowsEqualOnThePrefix) {
+    auto tablet_schema = std::make_shared<TabletSchema>();
+    create_unique_tablet_schema(tablet_schema);
+    std::vector<std::vector<std::array<int32_t, 3>>> segments(2);
+    std::vector<std::pair<int32_t, int32_t>> expected_keys;
+    for (int32_t i = 0; i < 20; ++i) {
+        segments[0].push_back({i, i, i});
+        segments[1].push_back({i, i + 20, i + 20});
+        expected_keys.emplace_back(i, i);
+        expected_keys.emplace_back(i, i + 20);
+    }
+    EngineOptions options;
+    StorageEngine engine(options);
+    RowsetSharedPtr rowset;
+    ASSERT_NO_FATAL_FAILURE(
+            write_overlapping_rowset(engine, tablet_schema, 10100, segments, 
&rowset));
+    ASSERT_TRUE(rowset->is_segments_overlapping());
+
+    std::vector<uint32_t> orderby_key_columns {0};
+    auto context = unique_merge_context(*tablet_schema, &orderby_key_columns);
+    auto keys = read_keys(rowset.get(), context);
+    EXPECT_TRUE(std::ranges::is_sorted(keys, {}, &std::pair<int32_t, 
int32_t>::first));
+    // Rows equal on k1 come out in either order.
+    std::ranges::sort(keys);
+    EXPECT_EQ(keys, expected_keys);
+}
+
+// A merge by the whole key keeps one row of each key that both overlapping 
segments of a
+// UNIQUE_KEYS rowset hold.
+TEST_F(BetaRowsetTest, WholeKeyMergeKeepsOneRowPerKey) {
+    auto tablet_schema = std::make_shared<TabletSchema>();
+    create_unique_tablet_schema(tablet_schema);
+    std::vector<std::vector<std::array<int32_t, 3>>> segments(2);
+    std::vector<std::pair<int32_t, int32_t>> expected_keys;
+    for (int32_t i = 0; i < 20; ++i) {
+        segments[0].push_back({i, i, i});
+        segments[1].push_back({i, i, i + 20});
+        expected_keys.emplace_back(i, i);
+    }
+    EngineOptions options;
+    StorageEngine engine(options);
+    RowsetSharedPtr rowset;
+    ASSERT_NO_FATAL_FAILURE(
+            write_overlapping_rowset(engine, tablet_schema, 10101, segments, 
&rowset));
+    ASSERT_TRUE(rowset->is_segments_overlapping());
+
+    auto context = unique_merge_context(*tablet_schema, nullptr);
+    EXPECT_EQ(read_keys(rowset.get(), context), expected_keys);
+}
+
 } // namespace doris
diff --git 
a/regression-test/data/fault_injection_p0/test_mow_topn_key_prefix_overlapping_segments.out
 
b/regression-test/data/fault_injection_p0/test_mow_topn_key_prefix_overlapping_segments.out
new file mode 100644
index 00000000000..e2105962d3b
--- /dev/null
+++ 
b/regression-test/data/fault_injection_p0/test_mow_topn_key_prefix_overlapping_segments.out
@@ -0,0 +1,76 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !count --
+16384
+
+-- !topn_prefix --
+0      0
+0      8192
+1      1
+1      8193
+2      2
+2      8194
+3      3
+3      8195
+4      4
+4      8196
+
+-- !topn_prefix_desc --
+8187   16379
+8187   8187
+8188   16380
+8188   8188
+8189   16381
+8189   8189
+8190   16382
+8190   8190
+8191   16383
+8191   8191
+
+-- !topn_whole_key --
+0      0
+0      8192
+1      1
+1      8193
+2      2
+2      8194
+3      3
+3      8195
+4      4
+4      8196
+
+-- !no_storage_topn --
+0      0
+0      8192
+1      1
+1      8193
+2      2
+2      8194
+3      3
+3      8195
+4      4
+4      8196
+
+-- !same_keys_topn_prefix --
+0      0       8192
+1      1       8193
+2      2       8194
+3      3       8195
+4      4       8196
+5      5       8197
+6      6       8198
+7      7       8199
+8      8       8200
+9      9       8201
+
+-- !cluster_key_topn_prefix --
+0      0
+1      1
+2      2
+3      3
+4      4
+8192   0
+8193   1
+8194   2
+8195   3
+8196   4
+
diff --git 
a/regression-test/data/fault_injection_p0/test_overlapping_segments_merge.out 
b/regression-test/data/fault_injection_p0/test_overlapping_segments_merge.out
new file mode 100644
index 00000000000..84019fc5e33
--- /dev/null
+++ 
b/regression-test/data/fault_injection_p0/test_overlapping_segments_merge.out
@@ -0,0 +1,45 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !seq_map --
+0      0       2       20      2
+1      1       2       21      2
+10     10      2       30      2
+11     11      2       31      2
+12     12      2       32      2
+13     13      2       33      2
+14     14      2       34      2
+15     15      2       35      2
+16     16      2       36      2
+17     17      2       37      2
+18     18      2       38      2
+19     19      2       39      2
+2      2       2       22      2
+3      3       2       23      2
+4      4       2       24      2
+5      5       2       25      2
+6      6       2       26      2
+7      7       2       27      2
+8      8       2       28      2
+9      9       2       29      2
+
+-- !seq_map_after_compaction --
+0      0       2       20      2
+1      1       2       21      2
+10     10      2       30      2
+11     11      2       31      2
+12     12      2       32      2
+13     13      2       33      2
+14     14      2       34      2
+15     15      2       35      2
+16     16      2       36      2
+17     17      2       37      2
+18     18      2       38      2
+19     19      2       39      2
+2      2       2       22      2
+20     20      1       20      1
+3      3       2       23      2
+4      4       2       24      2
+5      5       2       25      2
+6      6       2       26      2
+7      7       2       27      2
+8      8       2       28      2
+9      9       2       29      2
diff --git 
a/regression-test/suites/fault_injection_p0/test_mow_topn_key_prefix_overlapping_segments.groovy
 
b/regression-test/suites/fault_injection_p0/test_mow_topn_key_prefix_overlapping_segments.groovy
new file mode 100644
index 00000000000..f798b6c0f74
--- /dev/null
+++ 
b/regression-test/suites/fault_injection_p0/test_mow_topn_key_prefix_overlapping_segments.groovy
@@ -0,0 +1,123 @@
+// 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.
+
+// ORDER BY <key prefix> LIMIT n pushed down to the storage layer on a 
merge-on-write table
+// whose rowset has two segments that overlap on keys. The storage TopN merges 
the segments of
+// a rowset by the ORDER BY columns; rows that are equal on them but differ in 
the rest of the
+// key are different rows and must all come back. Before the fix the merge 
dropped them as
+// older versions of one key: ORDER BY k1 LIMIT 10 returned k1 = 0..9 once 
each instead of
+// k1 = 0..4 twice each.
+suite("test_mow_topn_key_prefix_overlapping_segments", "nonConcurrent") {
+    // Run `insertSql` with MemTable.need_flush on, which flushes every write 
into its own segment:
+    // the 16384 rows of numbers("number" = "16384") become two segments of 
one rowset. One sink
+    // task writes the Blocks in order, and a Block of 8192 rows is one write 
on both sinks: the
+    // legacy sink sends a Block once it holds 8192 rows (VNodeChannel floors 
its batch size at
+    // 8192), and the sink with the memtable on it writes every Block. The 
test is void unless the
+    // load really wrote an OVERLAPPING rowset with two segments.
+    def loadTwoOverlappingSegments = { String table, String insertSql ->
+        try {
+            GetDebugPoint().enableDebugPointForAllBEs("MemTable.need_flush")
+            sql "SET parallel_pipeline_task_num = 1"
+            sql "SET batch_size = 8192"
+            sql insertSql
+        } finally {
+            GetDebugPoint().disableDebugPointForAllBEs("MemTable.need_flush")
+        }
+        sql "sync"
+        def tablets = sql_return_maparray("SHOW TABLETS FROM ${table}")
+        def (code, out, err) = curl("GET", tablets[0].MetaUrl)
+        assertEquals(0, code)
+        def hasMergeLayout = parseJson(out.trim()).rs_metas.any { meta ->
+            meta.segments_overlap_pb == "OVERLAPPING" && meta.num_segments > 1
+        }
+        assertTrue(hasMergeLayout, "expected an OVERLAPPING rowset with 
num_segments > 1 in ${table}")
+    }
+    // The storage TopN below needs the segment limit pushdown, which the 
fuzzy session
+    // variables may turn off.
+    sql "SET enable_segment_limit_pushdown = true"
+    // The fuzzy session variables may also hand the two segments of the 
rowset to different
+    // parallel scanners, each reading one segment alone, so that no scanner 
merges them.
+    sql "SET enable_parallel_scan = false"
+
+    // Both segments hold k1 = 0..8191: k2 = k1 in the first one, k2 = k1 + 
8192 in the second.
+    sql "DROP TABLE IF EXISTS test_mow_topn_key_prefix_overlapping_segments"
+    sql """
+        CREATE TABLE test_mow_topn_key_prefix_overlapping_segments (k1 INT, k2 
INT, v INT)
+        UNIQUE KEY(k1, k2)
+        DISTRIBUTED BY HASH(k1) BUCKETS 1
+        PROPERTIES ("replication_num" = "1", 
"enable_unique_key_merge_on_write" = "true",
+                    "disable_auto_compaction" = "true")
+    """
+    
loadTwoOverlappingSegments("test_mow_topn_key_prefix_overlapping_segments", """
+        INSERT INTO test_mow_topn_key_prefix_overlapping_segments
+        SELECT number % 8192, number, number FROM numbers("number" = "16384")
+    """)
+    // The TopN reaches the scan, so the storage layer reads it.
+    explain {
+        sql "SELECT k1, k2 FROM test_mow_topn_key_prefix_overlapping_segments 
ORDER BY k1 LIMIT 10"
+        contains "SORT LIMIT: 10"
+    }
+    qt_count "SELECT count(*) FROM 
test_mow_topn_key_prefix_overlapping_segments"
+    // Storage TopN by the key prefix k1: every k1 appears twice (k2 = k1 and 
k2 = k1 + 8192).
+    order_qt_topn_prefix "SELECT k1, k2 FROM 
test_mow_topn_key_prefix_overlapping_segments ORDER BY k1 LIMIT 10"
+    order_qt_topn_prefix_desc "SELECT k1, k2 FROM 
test_mow_topn_key_prefix_overlapping_segments ORDER BY k1 DESC LIMIT 10"
+    // Storage TopN by the whole key.
+    qt_topn_whole_key "SELECT k1, k2 FROM 
test_mow_topn_key_prefix_overlapping_segments ORDER BY k1, k2 LIMIT 10"
+    // The same query without the storage TopN, for comparison.
+    order_qt_no_storage_topn """
+        SELECT /*+ SET_VAR(topn_opt_limit_threshold = 0) */ k1, k2
+        FROM test_mow_topn_key_prefix_overlapping_segments ORDER BY k1 LIMIT 10
+    """
+
+    // Both segments hold the same full keys. The storage TopN keeps the rows 
equal on the ORDER BY
+    // columns, and the delete bitmap of the merge-on-write table hides the 
older row of each key:
+    // every key comes back once, with the value written last (v = k1 + 8192).
+    sql "DROP TABLE IF EXISTS test_mow_topn_key_prefix_same_keys"
+    sql """
+        CREATE TABLE test_mow_topn_key_prefix_same_keys (k1 INT, k2 INT, v INT)
+        UNIQUE KEY(k1, k2)
+        DISTRIBUTED BY HASH(k1) BUCKETS 1
+        PROPERTIES ("replication_num" = "1", 
"enable_unique_key_merge_on_write" = "true",
+                    "disable_auto_compaction" = "true")
+    """
+    loadTwoOverlappingSegments("test_mow_topn_key_prefix_same_keys", """
+        INSERT INTO test_mow_topn_key_prefix_same_keys
+        SELECT number % 8192, number % 8192, number FROM numbers("number" = 
"16384")
+    """)
+    order_qt_same_keys_topn_prefix "SELECT k1, k2, v FROM 
test_mow_topn_key_prefix_same_keys ORDER BY k1 LIMIT 10"
+
+    // A cluster key table pushes the TopN down by its cluster key, which 
identifies no row: both
+    // segments hold v = 0..8191, with k = v in the first one and k = v + 8192 
in the second.
+    sql "DROP TABLE IF EXISTS test_mow_topn_cluster_key_prefix"
+    sql """
+        CREATE TABLE test_mow_topn_cluster_key_prefix (k INT, v INT, w INT)
+        UNIQUE KEY(k)
+        ORDER BY(v, w)
+        DISTRIBUTED BY HASH(k) BUCKETS 1
+        PROPERTIES ("replication_num" = "1", 
"enable_unique_key_merge_on_write" = "true",
+                    "disable_auto_compaction" = "true")
+    """
+    loadTwoOverlappingSegments("test_mow_topn_cluster_key_prefix", """
+        INSERT INTO test_mow_topn_cluster_key_prefix
+        SELECT number, number % 8192, number FROM numbers("number" = "16384")
+    """)
+    explain {
+        sql "SELECT k, v FROM test_mow_topn_cluster_key_prefix ORDER BY v 
LIMIT 10"
+        contains "SORT LIMIT: 10"
+    }
+    order_qt_cluster_key_topn_prefix "SELECT k, v FROM 
test_mow_topn_cluster_key_prefix ORDER BY v LIMIT 10"
+}
diff --git 
a/regression-test/suites/fault_injection_p0/test_overlapping_segments_merge.groovy
 
b/regression-test/suites/fault_injection_p0/test_overlapping_segments_merge.groovy
new file mode 100644
index 00000000000..0dfc8007017
--- /dev/null
+++ 
b/regression-test/suites/fault_injection_p0/test_overlapping_segments_merge.groovy
@@ -0,0 +1,172 @@
+// 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.
+
+// One load that flushes several memtables writes a rowset whose segments 
overlap on keys, and
+// reading it merges the segments before the rowsets. Each table below gets 
one such rowset in
+// which every key sits in both segments, and the later segment holds the 
newer rows:
+//   - AGG_KEYS: every key folds into one row, REPLACE takes the newer 
segment's value;
+//   - merge-on-read UNIQUE_KEYS: the newer segment's row wins;
+//   - UNIQUE_KEYS with a sequence map: each column group takes the row with 
its own largest
+//     sequence value, which is in a different segment for each group.
+// The expected AGG_KEYS and UNIQUE_KEYS rows come from the rows in storage 
order, so they do not
+// depend on which Block the load writes first. The queries read with Blocks 
of 3 rows, so key groups
+// are cut by Block boundaries, and the results must stay the same after a 
full compaction rewrites
+// the rowset.
+suite("test_overlapping_segments_merge", "nonConcurrent") {
+    sql "DROP TABLE IF EXISTS test_overlapping_segments_merge_agg"
+    sql "DROP TABLE IF EXISTS test_overlapping_segments_merge_uniq"
+    sql "DROP TABLE IF EXISTS test_overlapping_segments_merge_seq_map"
+    sql """
+        CREATE TABLE test_overlapping_segments_merge_agg (
+            k INT,
+            s BIGINT SUM,
+            r INT REPLACE
+        ) AGGREGATE KEY(k)
+        DISTRIBUTED BY HASH(k) BUCKETS 1
+        PROPERTIES ("replication_num" = "1", "disable_auto_compaction" = 
"true")
+    """
+    sql """
+        CREATE TABLE test_overlapping_segments_merge_uniq (
+            k INT,
+            v INT
+        ) UNIQUE KEY(k)
+        DISTRIBUTED BY HASH(k) BUCKETS 1
+        PROPERTIES (
+            "replication_num" = "1",
+            "enable_unique_key_merge_on_write" = "false",
+            "disable_auto_compaction" = "true"
+        )
+    """
+    sql """
+        CREATE TABLE test_overlapping_segments_merge_seq_map (
+            k INT,
+            v1 INT,
+            s1 BIGINT,
+            v2 INT,
+            s2 BIGINT
+        ) UNIQUE KEY(k)
+        DISTRIBUTED BY HASH(k) BUCKETS 1
+        PROPERTIES (
+            "replication_num" = "1",
+            "enable_unique_key_merge_on_write" = "false",
+            "light_schema_change" = "true",
+            "sequence_mapping.s1" = "v1",
+            "sequence_mapping.s2" = "v2",
+            "disable_auto_compaction" = "true"
+        )
+    """
+
+    try {
+        // MemTable.need_flush flushes every write into its own segment. One 
sink task writes
+        // numbers 0..8191 and 8192..16383 as two Blocks of 8192 rows, and a 
Block of 8192 rows is
+        // one write on both sinks: the legacy sink, the only one in cloud 
mode, sends a Block once
+        // it holds 8192 rows (VNodeChannel floors its batch size at 8192), 
and the sink with the
+        // memtable on it writes every Block. The memtable folds each write 
into keys 0..19
+        // (k = number % 20), so the two segments both hold every key. A value 
is k in the rows of
+        // numbers 0..8191 and k + 20 in those of 8192..16383, the same in 
every row of a key that
+        // one write folds.
+        GetDebugPoint().enableDebugPointForAllBEs("MemTable.need_flush")
+        sql "SET parallel_pipeline_task_num = 1"
+        sql "SET batch_size = 8192"
+        sql """
+            INSERT INTO test_overlapping_segments_merge_agg
+            SELECT number % 20, 1, if(number < 8192, number % 20, number % 20 
+ 20)
+            FROM numbers("number" = "16384")
+        """
+        sql """
+            INSERT INTO test_overlapping_segments_merge_uniq
+            SELECT number % 20, if(number < 8192, number % 20, number % 20 + 
20)
+            FROM numbers("number" = "16384")
+        """
+        // s1 is larger in the rows of numbers 0..8191 and s2 in those of 
8192..16383, so v1 and v2
+        // of every key come from different rows, whichever segment holds them.
+        sql """
+            INSERT INTO test_overlapping_segments_merge_seq_map
+            SELECT number % 20, if(number < 8192, number % 20, number % 20 + 
20),
+                   if(number < 8192, 2, 1), if(number < 8192, number % 20, 
number % 20 + 20),
+                   if(number < 8192, 1, 2)
+            FROM numbers("number" = "16384")
+        """
+    } finally {
+        GetDebugPoint().disableDebugPointForAllBEs("MemTable.need_flush")
+    }
+    sql "sync"
+
+    def tables = ["test_overlapping_segments_merge_agg", 
"test_overlapping_segments_merge_uniq",
+                  "test_overlapping_segments_merge_seq_map"]
+    // The test is void unless the load really wrote an OVERLAPPING rowset 
with several segments:
+    // only then does the rowset reader merge segments.
+    for (def tbl : tables) {
+        def tablets = sql_return_maparray("SHOW TABLETS FROM ${tbl}")
+        def (code, out, err) = curl("GET", tablets[0].MetaUrl)
+        assertEquals(0, code)
+        def jsonMeta = parseJson(out.trim())
+        def hasMergeLayout = jsonMeta.rs_metas.any { meta ->
+            meta.segments_overlap_pb == "OVERLAPPING" && meta.num_segments > 1
+        }
+        assertTrue(hasMergeLayout,
+                "expected an OVERLAPPING rowset with num_segments > 1 in 
${tbl}, "
+                        + "check the MemTable.need_flush debug point")
+    }
+
+    // Without an aggregation above it, the scan of the AGG_KEYS table folds 
the rows itself.
+    explain {
+        sql "SELECT k, s, r FROM test_overlapping_segments_merge_agg"
+        contains "PREAGGREGATION: OFF"
+    }
+
+    // The newer row of a key is the one in the later segment: read the rows 
in storage order,
+    // without the merge, to know it.
+    sql "SET skip_storage_engine_merge = true"
+    sql "SET parallel_pipeline_task_num = 1"
+    def aggRows = sql "SELECT k, s, r FROM test_overlapping_segments_merge_agg"
+    def uniqRows = sql "SELECT k, v FROM test_overlapping_segments_merge_uniq"
+    sql "SET skip_storage_engine_merge = false"
+    assertEquals(40, aggRows.size(), "expected both rows of every key without 
the merge")
+    assertEquals(40, uniqRows.size(), "expected both rows of every key without 
the merge")
+    def expectedAgg = aggRows.groupBy { it[0] }
+            .collect { k, rows -> [k, rows.sum { it[1] }, rows.last()[2]] }
+            .sort { it[0] }
+    def expectedUniq = uniqRows.groupBy { it[0] }.collect { k, rows -> 
rows.last() }.sort { it[0] }
+
+    // The segment merge yields 0 0 1 1 ... 19 19; Blocks of 3 rows cut every 
other key group.
+    sql "SET batch_size = 3"
+    assertEquals(expectedAgg, sql("SELECT k, s, r FROM 
test_overlapping_segments_merge_agg ORDER BY k"))
+    assertEquals(expectedUniq, sql("SELECT k, v FROM 
test_overlapping_segments_merge_uniq ORDER BY k"))
+    order_qt_seq_map "SELECT k, v1, s1, v2, s2 FROM 
test_overlapping_segments_merge_seq_map"
+
+    // A second rowset gives the full compaction something to merge; it 
rewrites both rowsets
+    // into one, reading the overlapping segments the same way.
+    sql "INSERT INTO test_overlapping_segments_merge_agg VALUES (20, 1, 20)"
+    sql "INSERT INTO test_overlapping_segments_merge_uniq VALUES (20, 20)"
+    sql "INSERT INTO test_overlapping_segments_merge_seq_map VALUES (20, 20, 
1, 20, 1)"
+    for (def tbl : tables) {
+        trigger_and_wait_compaction(tbl, "full")
+        def tablets = sql_return_maparray("SHOW TABLETS FROM ${tbl}")
+        def (code, out, err) = curl("GET", tablets[0].MetaUrl)
+        assertEquals(0, code)
+        def rsMetas = parseJson(out.trim()).rs_metas
+        assertEquals(1, rsMetas.size(), "expected the full compaction to leave 
one rowset in ${tbl}")
+    }
+    assertEquals(expectedAgg + [[20, 1L, 20]],
+            sql("SELECT k, s, r FROM test_overlapping_segments_merge_agg ORDER 
BY k"))
+    assertEquals(expectedUniq + [[20, 20]],
+            sql("SELECT k, v FROM test_overlapping_segments_merge_uniq ORDER 
BY k"))
+    order_qt_seq_map_after_compaction """
+        SELECT k, v1, s1, v2, s2 FROM test_overlapping_segments_merge_seq_map
+    """
+}


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

Reply via email to