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

yiguolei 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 d7b4ff46d5e branch-4.2: [fix](storage) Fix reading a rowset whose 
segments overlap on keys #69797 (#70926)
d7b4ff46d5e is described below

commit d7b4ff46d5ed2c8355e901f0b9f54e3d3ed09791
Author: Chenyang Sun <[email protected]>
AuthorDate: Tue Dec 1 08:38:38 2026 +0800

    branch-4.2: [fix](storage) Fix reading a rowset whose segments overlap on 
keys #69797 (#70926)
    
    Cherry-picked from master #69797
---
 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 +
 .../block_reader_overlapping_segments_test.cpp     | 424 +++++++++++++++++++++
 be/test/storage/rowset/beta_rowset_test.cpp        | 153 ++++++++
 ...st_mow_topn_key_prefix_overlapping_segments.out |  76 ++++
 ...mow_topn_key_prefix_overlapping_segments.groovy | 123 ++++++
 .../test_overlapping_segments_merge.groovy         | 136 +++++++
 8 files changed, 927 insertions(+), 4 deletions(-)

diff --git a/be/src/storage/iterator/vcollect_iterator.cpp 
b/be/src/storage/iterator/vcollect_iterator.cpp
index fc00060f1d0..bbcf57bb11f 100644
--- a/be/src/storage/iterator/vcollect_iterator.cpp
+++ b/be/src/storage/iterator/vcollect_iterator.cpp
@@ -553,15 +553,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 e2e3f7512c1..a27154d23b1 100644
--- a/be/src/storage/rowset/beta_rowset_reader.cpp
+++ b/be/src/storage/rowset/beta_rowset_reader.cpp
@@ -338,7 +338,12 @@ Status BetaRowsetReader::_init_iterator() {
                 }
             }
         }
-        _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, 
_output_schema);
     } else {
diff --git a/be/src/storage/segment/lazy_init_segment_iterator.h 
b/be/src/storage/segment/lazy_init_segment_iterator.h
index 147480e0e85..2974fdcc448 100644
--- a/be/src/storage/segment/lazy_init_segment_iterator.h
+++ b/be/src/storage/segment/lazy_init_segment_iterator.h
@@ -48,6 +48,10 @@ public:
 
     const Schema& 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); }
+
     Status current_block_row_locations(std::vector<RowLocation>* locations) 
override {
         return _inner_iterator->current_block_row_locations(locations);
     }
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..47795027f37
--- /dev/null
+++ b/be/test/storage/iterator/block_reader_overlapping_segments_test.cpp
@@ -0,0 +1,424 @@
+// 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 and merge-on-read 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.
+
+#include <gen_cpp/olap_file.pb.h>
+#include <gtest/gtest.h>
+#include <unistd.h>
+
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <numeric>
+#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>;
+
+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) {
+        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()));
+        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);
+            }
+        }
+        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_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.return_columns.resize(schema->num_columns());
+        std::iota(params.return_columns.begin(), params.return_columns.end(), 
0);
+        params.origin_return_columns = &params.return_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 = schema->create_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));
+    std::vector<ColumnId> col_ids(schema->num_columns());
+    std::iota(col_ids.begin(), col_ids.end(), 0);
+    auto iter_schema = std::make_shared<Schema>(schema->columns(), col_ids);
+    OlapReaderStatistics stats;
+    StorageReadOptions opts;
+    opts.stats = &stats;
+    opts.tablet_schema = schema;
+
+    for (int64_t pos = 0; pos < rowset->num_segments(); ++pos) {
+        SCOPED_TRACE("segment pos=" + std::to_string(pos));
+        segment_v2::LazyInitSegmentIterator iter(rowset, pos, 
/*should_use_cache=*/false,
+                                                 iter_schema, opts);
+        EXPECT_EQ(iter.data_id(), static_cast<uint64_t>(pos));
+
+        ASSERT_TRUE(iter.init(opts).ok());
+        Block block = schema->create_block();
+        ASSERT_TRUE(iter.next_batch(&block).ok());
+        EXPECT_EQ(iter.data_id(), static_cast<uint64_t>(pos));
+    }
+}
+
+// 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);
+            }
+        }
+    }
+}
+
+} // namespace doris
diff --git a/be/test/storage/rowset/beta_rowset_test.cpp 
b/be/test/storage/rowset/beta_rowset_test.cpp
index 6402c5eccc6..76a85388e5f 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 <utility>
@@ -40,6 +41,7 @@
 
 #include "common/config.h"
 #include "common/status.h"
+#include "core/block/block.h"
 #include "cpp/obj-client/s3_obj_storage_client.h"
 #include "cpp/sync_point.h"
 #include "gtest/gtest_pred_impl.h"
@@ -53,8 +55,10 @@
 #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/segment/segment.h"
 #include "storage/storage_engine.h"
@@ -174,6 +178,98 @@ 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_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.tablet_schema->create_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(TabletSchemaSPtr tablet_schema,
+                                             const std::vector<uint32_t>* 
return_columns,
+                                             std::vector<uint32_t>* 
orderby_key_columns) {
+        RowsetReaderContext context;
+        context.tablet_schema = std::move(tablet_schema);
+        context.return_columns = return_columns;
+        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,
@@ -663,4 +759,61 @@ 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());
+
+    const std::vector<uint32_t> return_columns {0, 1, 2};
+    std::vector<uint32_t> orderby_key_columns {0};
+    auto context = unique_merge_context(tablet_schema, &return_columns, 
&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());
+
+    const std::vector<uint32_t> return_columns {0, 1, 2};
+    auto context = unique_merge_context(tablet_schema, &return_columns, 
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/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..8b400426b5d
--- /dev/null
+++ 
b/regression-test/suites/fault_injection_p0/test_overlapping_segments_merge.groovy
@@ -0,0 +1,136 @@
+// 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.
+// 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 """
+        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"
+        )
+    """
+
+    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")
+        """
+    } finally {
+        GetDebugPoint().disableDebugPointForAllBEs("MemTable.need_flush")
+    }
+    sql "sync"
+
+    def tables = ["test_overlapping_segments_merge_agg", 
"test_overlapping_segments_merge_uniq"]
+    // 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"))
+
+    // 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)"
+    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"))
+}


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

Reply via email to