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


##########
be/src/storage/iterator/changelog_min_delta_block_iterator.cpp:
##########
@@ -0,0 +1,225 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/changelog_min_delta_block_iterator.h"
+
+#include <glog/logging.h>
+
+#include <utility>
+
+#include "common/exception.h"
+#include "core/column/column_nullable.h"
+#include "storage/changelog_types.h"
+#include "storage/iterator/block_key_utils.h"
+#include "storage/iterator/changelog_block_reader_utils.h"
+#include "util/simd/bits.h"
+
+namespace doris {
+
+ChangelogMinDeltaBlockIterator::ChangelogMinDeltaBlockIterator(std::unique_ptr<BlockIterator>
 input,
+                                                               BlockBatchLimit 
batch_limit,
+                                                               ReadSchemaSPtr 
read_schema)
+        : _cursor(std::move(input), *read_schema, batch_limit),
+          _read_schema(std::move(read_schema)),
+          _num_key_columns(_read_schema->num_key_columns()),
+          _op_col_idx(_read_schema->op_ordinal()),
+          _tso_col_idx(_read_schema->tso_ordinal()),
+          _lsn_col_idx(_read_schema->lsn_ordinal()) {
+    DORIS_CHECK_GE(_op_col_idx, 0);
+}
+
+void ChangelogMinDeltaBlockIterator::_mark_block_same_keys() {
+    mark_same_keys_in_block(_cursor.block(), _num_key_columns, &_same_key);
+    _same_key[0] = !_group_columns[0]->empty() &&
+                   row_matches_first_key(_group_columns, 0, _cursor.block(), 
_num_key_columns);
+}
+
+void ChangelogMinDeltaBlockIterator::_set_group_row(size_t row_pos, bool 
replace_last) {
+    const Block& block = _cursor.block();
+    for (size_t col_idx = 0; col_idx < _group_columns.size(); ++col_idx) {
+        if (replace_last) {
+            _group_columns[col_idx]->pop_back(1);
+        }
+        
_group_columns[col_idx]->insert_from(*block.get_by_position(col_idx).column, 
row_pos);
+    }
+}
+
+Status ChangelogMinDeltaBlockIterator::_collect_group() {
+    if (_same_key.empty()) {
+        _mark_block_same_keys();
+    }
+    const size_t first_pos = _cursor.row_pos();
+    _set_group_row(first_pos, /*replace_last=*/false);
+
+    size_t search_from = first_pos + 1;
+    while (true) {
+        const size_t block_rows = _cursor.block().rows();
+        const size_t next_diff = simd::find_zero(_same_key, search_from);
+        if (next_diff > search_from) {
+            _set_group_row(next_diff - 1, 
/*replace_last=*/_group_columns[0]->size() > 1);
+        }
+        RETURN_IF_ERROR(_cursor.advance_to(next_diff));
+        if (next_diff < block_rows || _cursor.eof()) {
+            return Status::OK();
+        }
+        _mark_block_same_keys();
+        search_from = 0;
+    }
+}
+
+bool ChangelogMinDeltaBlockIterator::_group_values_unchanged() {
+    const auto& value_column_pairs = 
_read_schema->changelog_value_column_pairs();
+    if (!_read_schema->changelog_value_pairs_complete() || 
_value_compare_unsupported) {
+        return false;
+    }
+    DCHECK(!value_column_pairs.empty());

Review Comment:
   [P2] Allow MIN_DELTA on key-only changelog tables
   
   `ReadSchema` marks an empty pair list complete when the read contains only 
keys and changelog metadata. A DELETE followed by reinsertion of the same key 
in a MIN_DELTA window then calls this function and reaches the DCHECK. The new 
`MinDeltaAndDetailCoverEdgeBranchesAndStrings` unit test already takes this 
path with a key-only schema and an UPDATE. Restore the legacy empty-pair guard 
so DCHECK-enabled BEs emit the pair.



##########
be/src/storage/iterator/block_reader.cpp:
##########
@@ -587,27 +568,29 @@ Status BlockReader::init(const ReaderParams& read_params) 
{
         _min_delta_value_compare_unsupported = false;
     }
 
-    // Every merge and caller Block has the exact read-schema layout. Cache 
only
-    // the non-key columns of AGG tables that go through the aggregate 
machinery.
-    const auto num_block_columns = 
static_cast<uint32_t>(_read_schema->num_block_columns());
-    const bool is_agg_keys = _tablet->keys_type() == AGG_KEYS;
-    for (uint32_t ordinal = 0; ordinal < num_block_columns; ++ordinal) {
-        if (is_agg_keys && !_read_schema->column(ordinal)->is_key()) {
-            _agg_columns_idx.emplace_back(ordinal);
-        }
-    }
-
-    auto status = _init_collect_iter(read_params);
+    // Decided once, as config::enable_new_block_iterator is mutable at 
runtime.
+    const bool use_new_block_iter = config::enable_new_block_iterator;

Review Comment:
   [P2] Synchronize reads of the live rollback flag
   
   `DEFINE_mBool` stores a plain `bool`. An HTTP config update writes it under 
`mutable_string_config_lock` in `config::set_config()`, while scanner and 
compaction threads read it here without that lock. Taking the snapshot once 
still races with an operator changing the flag on a live BE. Read it under the 
same lock, or use an atomic value published by the config update callback as 
`get_inverted_index_candidate_pushdown_ratio()` does.



##########
be/src/storage/iterator/block_iterator_builder.cpp:
##########
@@ -0,0 +1,414 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/block_iterator_builder.h"
+
+#include <fmt/format.h>
+#include <gen_cpp/PlanNodes_types.h>
+#include <gen_cpp/olap_file.pb.h>
+#include <glog/logging.h>
+
+#include <algorithm>
+#include <map>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+#include "common/cast_set.h"
+#include "common/exception.h"
+#include "core/data_type/data_type.h"
+#include "core/field.h"
+#include "exprs/vexpr.h"
+#include "exprs/vexpr_context.h"
+#include "runtime/query_context.h"
+#include "runtime/runtime_predicate.h"
+#include "runtime/runtime_state.h"
+#include "storage/iterator/agg_key_block_iterator.h"
+#include "storage/iterator/changelog_detail_block_iterator.h"
+#include "storage/iterator/changelog_min_delta_block_iterator.h"
+#include "storage/iterator/direct_iterator.h"
+#include "storage/iterator/heap_merge_iterator.h"
+#include "storage/iterator/merge_block_iterator.h"
+#include "storage/iterator/sequence_map_block_iterator.h"
+#include "storage/iterator/topn_block_iterator.h"
+#include "storage/iterator/unique_key_block_iterator.h"
+#include "storage/iterators.h"
+#include "storage/olap_common.h"
+#include "storage/rowset/rowset.h"
+#include "storage/rowset/rowset_reader.h"
+#include "storage/rowset/rowset_reader_context.h"
+#include "storage/tablet/base_tablet.h"
+#include "storage/tablet/tablet_schema.h"
+#include "util/slice.h"
+
+namespace doris {
+
+namespace {
+
+// Pins `rs_reader` (its rowset and StorageReadOptions) until `inner` is 
destroyed at segment EOF,
+// so merged reads release each RowsetReader as soon as its last segment child 
finishes.
+class RowsetBoundIterator final : public RowwiseIterator {
+public:
+    RowsetBoundIterator(RowsetReaderSharedPtr rs_reader, RowwiseIteratorUPtr 
inner)
+            : _rs_reader(std::move(rs_reader)), _inner(std::move(inner)) {}
+
+    Status next_batch(Block* block) override { return 
_inner->next_batch(block); }
+    const ReadSchema& schema() const override { return _inner->schema(); }
+    void update_profile(RuntimeProfile* profile) override { 
_inner->update_profile(profile); }
+
+private:
+    // Declared before `_inner` so `_inner` is destroyed first while 
`_rs_reader` is still alive.
+    RowsetReaderSharedPtr _rs_reader;
+    RowwiseIteratorUPtr _inner;
+};
+
+} // namespace
+
+BlockIteratorBuilder::BlockIteratorBuilder(const TabletReader::ReaderParams& 
read_params,
+                                           const BaseTablet& tablet, 
ReadSchemaSPtr read_schema,
+                                           RowsetReaderContext* reader_context,
+                                           OlapReaderStatistics* stats, 
uint64_t* merged_rows,
+                                           BlockBatchLimit batch_limit)
+        : _read_params(read_params),
+          _tablet(tablet),
+          _read_schema(std::move(read_schema)),
+          _reader_context(reader_context),
+          _stats(stats),
+          _merged_rows(merged_rows),
+          _batch_limit(batch_limit) {}
+
+Status BlockIteratorBuilder::build(Mode mode, std::unique_ptr<BlockIterator>* 
out_iter) {
+    switch (mode) {
+    case Mode::TOPN:
+        return _init_topn_iter(out_iter);
+    case Mode::CHANGELOG_MIN_DELTA: {
+        std::unique_ptr<BlockIterator> input;
+        RETURN_IF_ERROR(_init_changelog_input_iter(&input));
+        *out_iter = 
std::make_unique<ChangelogMinDeltaBlockIterator>(std::move(input), _batch_limit,
+                                                                     
_read_schema);
+        return Status::OK();
+    }
+    case Mode::CHANGELOG_DETAIL: {
+        std::unique_ptr<BlockIterator> input;
+        RETURN_IF_ERROR(_init_changelog_input_iter(&input));
+        *out_iter = 
std::make_unique<ChangelogDetailBlockIterator>(std::move(input), _batch_limit,
+                                                                   
_read_schema);
+        return Status::OK();
+    }
+    case Mode::DIRECT:
+        return _init_direct_iter(out_iter);
+    case Mode::KEY_ORDERED:
+        return _init_key_ordered_iter(out_iter);
+    case Mode::UNIQUE_NEWEST:
+        return _init_unique_key_iter(out_iter);
+    case Mode::SEQUENCE_MAP:
+        return _init_sequence_map_iter(out_iter);
+    case Mode::AGG_FOLD:
+        break;
+    }
+    DORIS_CHECK_EQ(static_cast<uint8_t>(mode), 
static_cast<uint8_t>(Mode::AGG_FOLD));
+    return _init_agg_key_iter(out_iter);
+}
+
+Status BlockIteratorBuilder::_validate_merge_schema(const HeapMergeOrder& 
order) const {
+    const size_t num_block_columns = _read_schema->num_block_columns();
+    const size_t num_key_columns = _read_schema->num_key_columns();
+    auto contract_error = [&](std::string_view detail) {
+        return Status::InternalError(
+                "merge heap compare contract violated: {}, tablet_id={}, 
read_columns={}, "
+                "num_key_columns={}",
+                detail, _tablet.tablet_id(), num_block_columns, 
num_key_columns);
+    };
+    if (num_key_columns > num_block_columns) {
+        return contract_error("read schema has fewer columns than the key 
prefix");
+    }
+    for (size_t col_idx = 0; col_idx < num_key_columns; ++col_idx) {
+        if (!_read_schema->column(col_idx)->is_key()) {
+            return contract_error("read schema key prefix contains a non-key 
column");
+        }
+    }
+    for (const auto& [col_idx, _] : order.resolve_sort_cols(num_key_columns)) {
+        if (col_idx >= num_block_columns) {
+            return contract_error("compare column index out of range");
+        }
+    }
+    return Status::OK();
+}
+
+Status BlockIteratorBuilder::_build_heap_merge_iter(HeapMergeOrder order,
+                                                    RowwiseIteratorUPtr* 
merge_iter) {
+    RETURN_IF_ERROR(_validate_merge_schema(order));
+    std::vector<RowwiseIteratorUPtr> children;
+    RuntimeState* runtime_state = _read_params.runtime_state;
+    {
+        SCOPED_RAW_TIMER(&_stats->block_reader_rs_readers_init_timer_ns);
+        int64_t previous_start_version = -1;
+        std::vector<RowwiseIteratorUPtr> rs_children;
+        for (const auto& rs_split : _read_params.rs_splits) {
+            if (runtime_state != nullptr && runtime_state->is_cancelled()) {
+                return runtime_state->cancel_reason();
+            }
+            const RowsetReaderSharedPtr& rs_reader = rs_split.rs_reader;
+            RETURN_IF_ERROR(rs_reader->init(_reader_context, rs_split));
+            DORIS_CHECK_GE(rs_reader->rowset()->start_version(), 
previous_start_version);
+            previous_start_version = rs_reader->rowset()->start_version();
+            rs_children.clear();
+            
RETURN_IF_ERROR(rs_reader->get_key_ordered_iterators(_reader_context, 
&rs_children));
+            for (auto& child : rs_children) {
+                children.push_back(
+                        std::make_unique<RowsetBoundIterator>(rs_reader, 
std::move(child)));
+            }
+        }
+    }
+
+    SCOPED_RAW_TIMER(&_stats->block_reader_build_heap_init_timer_ns);
+    *merge_iter = std::make_unique<VHeapMergeIterator>(std::move(children), 
_read_schema, order);
+    StorageReadOptions opts(*_stats);
+    opts.block_row_max = cast_set<uint32_t>(_batch_limit.max_rows());
+    opts.preferred_block_size_bytes = _batch_limit.preferred_bytes();
+    opts.runtime_state = runtime_state;
+    return (*merge_iter)->init(opts);
+}
+
+Status BlockIteratorBuilder::_init_direct_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    const size_t read_limit = _reader_context->general_read_limit > 0
+                                      ? 
static_cast<size_t>(_reader_context->general_read_limit)
+                                      : 0;
+    std::vector<RowsetReaderSharedPtr> rs_readers;
+    rs_readers.reserve(_read_params.rs_splits.size());
+    RuntimeState* runtime_state = _read_params.runtime_state;
+    {
+        SCOPED_RAW_TIMER(&_stats->block_reader_rs_readers_init_timer_ns);
+        for (const auto& rs_split : _read_params.rs_splits) {
+            if (runtime_state != nullptr && runtime_state->is_cancelled()) {
+                return runtime_state->cancel_reason();
+            }
+            if (read_limit > 0) {
+                rs_split.rs_reader->set_topn_limit(read_limit);
+            }
+            RETURN_IF_ERROR(rs_split.rs_reader->init(_reader_context, 
rs_split));
+            rs_readers.push_back(rs_split.rs_reader);
+        }
+    }
+    *out_iter = std::make_unique<DirectIterator>(std::move(rs_readers), 
_reader_context, _stats);
+    return Status::OK();
+}
+
+Status BlockIteratorBuilder::_init_ordered_block_iter(HeapMergeOrder order,
+                                                      
std::unique_ptr<BlockIterator>* out_iter) {
+    if (!rowsets_not_mono_asc_disjoint(_read_params)) {
+        return _init_direct_iter(out_iter);
+    }
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(order, &merge_iter));
+    *out_iter = std::make_unique<MergeBlockIterator>(std::move(merge_iter));
+    return Status::OK();
+}
+
+Status 
BlockIteratorBuilder::_init_changelog_input_iter(std::unique_ptr<BlockIterator>*
 out_iter) {
+    const int32_t tso_col_idx = _read_schema->tso_ordinal();
+    HeapMergeOrder order = tso_col_idx >= 0
+                                   ? 
HeapMergeOrder::by_all_keys_and_same_key_col(
+                                             tso_col_idx, SortDirection::ASC, 
SortDirection::ASC)
+                                   : 
HeapMergeOrder::by_all_keys(SortDirection::ASC);
+    return _init_ordered_block_iter(order, out_iter);
+}
+
+Status 
BlockIteratorBuilder::_init_key_ordered_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    const auto child_direction =
+            _reader_context->use_insert_order_when_same ? SortDirection::ASC : 
SortDirection::DESC;
+    const int32_t tso_col_idx = _read_schema->tso_ordinal();
+    const int32_t seq_col_idx = _read_schema->sequence_ordinal();
+    HeapMergeOrder order;
+    if (tso_col_idx >= 0) {
+        order = HeapMergeOrder::by_all_keys_and_same_key_col(tso_col_idx, 
SortDirection::ASC,
+                                                             child_direction);
+    } else if (seq_col_idx >= 0) {
+        order = HeapMergeOrder::by_all_keys_and_same_key_col(seq_col_idx, 
SortDirection::DESC,
+                                                             child_direction);
+    } else {
+        order = HeapMergeOrder::by_all_keys(child_direction);
+    }
+    return _init_ordered_block_iter(order, out_iter);
+}
+
+Status 
BlockIteratorBuilder::_init_unique_key_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    DORIS_CHECK(!_reader_context->read_changelog);
+    DORIS_CHECK(!_read_params.read_orderby_key);
+
+    if (!rowsets_not_mono_asc_disjoint(_read_params)) {
+        return _init_direct_iter(out_iter);
+    }
+
+    const int32_t seq_col_idx = _read_schema->sequence_ordinal();
+    HeapMergeOrder order = seq_col_idx >= 0 ? 
HeapMergeOrder::by_all_keys_and_same_key_col(
+                                                      seq_col_idx, 
SortDirection::DESC)
+                                            : HeapMergeOrder::by_all_keys();
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(order, &merge_iter));
+    *out_iter = 
std::make_unique<UniqueKeyBlockIterator>(std::move(merge_iter), _merged_rows);
+    return Status::OK();
+}
+
+Status 
BlockIteratorBuilder::_init_sequence_map_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    DORIS_CHECK(!_reader_context->read_changelog);
+    DORIS_CHECK(!_read_params.read_orderby_key);
+
+    if (!rowsets_not_mono_asc_disjoint(_read_params)) {
+        return _init_direct_iter(out_iter);
+    }
+
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(HeapMergeOrder::by_all_keys(), 
&merge_iter));
+    *out_iter = 
std::make_unique<SequenceMapBlockIterator>(std::move(merge_iter), _batch_limit,
+                                                           _read_schema, 
_merged_rows);
+    return Status::OK();
+}
+
+Status 
BlockIteratorBuilder::_init_agg_key_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    DORIS_CHECK(!_reader_context->read_changelog);
+    DORIS_CHECK(!_read_params.read_orderby_key);
+    DORIS_CHECK(_reader_context->general_read_limit <= 0);
+
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(HeapMergeOrder::by_all_keys(), 
&merge_iter));

Review Comment:
   [P1] Preserve lazy reads for disjoint AGG rowsets
   
   This builds a heap even when the rowsets are strictly ascending and 
disjoint. The legacy union opens only its first nonempty input, while 
`VHeapMergeIterator::init()` reads and retains a block from every child before 
the scanner can return a row. A one-tablet AGG_KEYS scan with PREAGGREGATION 
OFF can receive all rowsets in one scanner. With 500 separately loaded key 
ranges and enough roughly 4 KiB values per range, the default 8 MiB preferred 
batch size can leave roughly 4 GiB of input blocks pinned, even for a small 
query LIMIT. This can fail scans that fit the memory limit with the legacy 
reader. Feed the aggregator from a lazy ordered input when the disjointness 
check succeeds.



##########
be/src/storage/iterator/block_iterator_builder.cpp:
##########
@@ -0,0 +1,414 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/block_iterator_builder.h"
+
+#include <fmt/format.h>
+#include <gen_cpp/PlanNodes_types.h>
+#include <gen_cpp/olap_file.pb.h>
+#include <glog/logging.h>
+
+#include <algorithm>
+#include <map>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+#include "common/cast_set.h"
+#include "common/exception.h"
+#include "core/data_type/data_type.h"
+#include "core/field.h"
+#include "exprs/vexpr.h"
+#include "exprs/vexpr_context.h"
+#include "runtime/query_context.h"
+#include "runtime/runtime_predicate.h"
+#include "runtime/runtime_state.h"
+#include "storage/iterator/agg_key_block_iterator.h"
+#include "storage/iterator/changelog_detail_block_iterator.h"
+#include "storage/iterator/changelog_min_delta_block_iterator.h"
+#include "storage/iterator/direct_iterator.h"
+#include "storage/iterator/heap_merge_iterator.h"
+#include "storage/iterator/merge_block_iterator.h"
+#include "storage/iterator/sequence_map_block_iterator.h"
+#include "storage/iterator/topn_block_iterator.h"
+#include "storage/iterator/unique_key_block_iterator.h"
+#include "storage/iterators.h"
+#include "storage/olap_common.h"
+#include "storage/rowset/rowset.h"
+#include "storage/rowset/rowset_reader.h"
+#include "storage/rowset/rowset_reader_context.h"
+#include "storage/tablet/base_tablet.h"
+#include "storage/tablet/tablet_schema.h"
+#include "util/slice.h"
+
+namespace doris {
+
+namespace {
+
+// Pins `rs_reader` (its rowset and StorageReadOptions) until `inner` is 
destroyed at segment EOF,
+// so merged reads release each RowsetReader as soon as its last segment child 
finishes.
+class RowsetBoundIterator final : public RowwiseIterator {
+public:
+    RowsetBoundIterator(RowsetReaderSharedPtr rs_reader, RowwiseIteratorUPtr 
inner)
+            : _rs_reader(std::move(rs_reader)), _inner(std::move(inner)) {}
+
+    Status next_batch(Block* block) override { return 
_inner->next_batch(block); }
+    const ReadSchema& schema() const override { return _inner->schema(); }
+    void update_profile(RuntimeProfile* profile) override { 
_inner->update_profile(profile); }
+
+private:
+    // Declared before `_inner` so `_inner` is destroyed first while 
`_rs_reader` is still alive.
+    RowsetReaderSharedPtr _rs_reader;
+    RowwiseIteratorUPtr _inner;
+};
+
+} // namespace
+
+BlockIteratorBuilder::BlockIteratorBuilder(const TabletReader::ReaderParams& 
read_params,
+                                           const BaseTablet& tablet, 
ReadSchemaSPtr read_schema,
+                                           RowsetReaderContext* reader_context,
+                                           OlapReaderStatistics* stats, 
uint64_t* merged_rows,
+                                           BlockBatchLimit batch_limit)
+        : _read_params(read_params),
+          _tablet(tablet),
+          _read_schema(std::move(read_schema)),
+          _reader_context(reader_context),
+          _stats(stats),
+          _merged_rows(merged_rows),
+          _batch_limit(batch_limit) {}
+
+Status BlockIteratorBuilder::build(Mode mode, std::unique_ptr<BlockIterator>* 
out_iter) {
+    switch (mode) {
+    case Mode::TOPN:
+        return _init_topn_iter(out_iter);
+    case Mode::CHANGELOG_MIN_DELTA: {
+        std::unique_ptr<BlockIterator> input;
+        RETURN_IF_ERROR(_init_changelog_input_iter(&input));
+        *out_iter = 
std::make_unique<ChangelogMinDeltaBlockIterator>(std::move(input), _batch_limit,
+                                                                     
_read_schema);
+        return Status::OK();
+    }
+    case Mode::CHANGELOG_DETAIL: {
+        std::unique_ptr<BlockIterator> input;
+        RETURN_IF_ERROR(_init_changelog_input_iter(&input));
+        *out_iter = 
std::make_unique<ChangelogDetailBlockIterator>(std::move(input), _batch_limit,
+                                                                   
_read_schema);
+        return Status::OK();
+    }
+    case Mode::DIRECT:
+        return _init_direct_iter(out_iter);
+    case Mode::KEY_ORDERED:
+        return _init_key_ordered_iter(out_iter);
+    case Mode::UNIQUE_NEWEST:
+        return _init_unique_key_iter(out_iter);
+    case Mode::SEQUENCE_MAP:
+        return _init_sequence_map_iter(out_iter);
+    case Mode::AGG_FOLD:
+        break;
+    }
+    DORIS_CHECK_EQ(static_cast<uint8_t>(mode), 
static_cast<uint8_t>(Mode::AGG_FOLD));
+    return _init_agg_key_iter(out_iter);
+}
+
+Status BlockIteratorBuilder::_validate_merge_schema(const HeapMergeOrder& 
order) const {
+    const size_t num_block_columns = _read_schema->num_block_columns();
+    const size_t num_key_columns = _read_schema->num_key_columns();
+    auto contract_error = [&](std::string_view detail) {
+        return Status::InternalError(
+                "merge heap compare contract violated: {}, tablet_id={}, 
read_columns={}, "
+                "num_key_columns={}",
+                detail, _tablet.tablet_id(), num_block_columns, 
num_key_columns);
+    };
+    if (num_key_columns > num_block_columns) {
+        return contract_error("read schema has fewer columns than the key 
prefix");
+    }
+    for (size_t col_idx = 0; col_idx < num_key_columns; ++col_idx) {
+        if (!_read_schema->column(col_idx)->is_key()) {
+            return contract_error("read schema key prefix contains a non-key 
column");
+        }
+    }
+    for (const auto& [col_idx, _] : order.resolve_sort_cols(num_key_columns)) {
+        if (col_idx >= num_block_columns) {
+            return contract_error("compare column index out of range");
+        }
+    }
+    return Status::OK();
+}
+
+Status BlockIteratorBuilder::_build_heap_merge_iter(HeapMergeOrder order,
+                                                    RowwiseIteratorUPtr* 
merge_iter) {
+    RETURN_IF_ERROR(_validate_merge_schema(order));
+    std::vector<RowwiseIteratorUPtr> children;
+    RuntimeState* runtime_state = _read_params.runtime_state;
+    {
+        SCOPED_RAW_TIMER(&_stats->block_reader_rs_readers_init_timer_ns);
+        int64_t previous_start_version = -1;
+        std::vector<RowwiseIteratorUPtr> rs_children;
+        for (const auto& rs_split : _read_params.rs_splits) {
+            if (runtime_state != nullptr && runtime_state->is_cancelled()) {
+                return runtime_state->cancel_reason();
+            }
+            const RowsetReaderSharedPtr& rs_reader = rs_split.rs_reader;
+            RETURN_IF_ERROR(rs_reader->init(_reader_context, rs_split));
+            DORIS_CHECK_GE(rs_reader->rowset()->start_version(), 
previous_start_version);
+            previous_start_version = rs_reader->rowset()->start_version();
+            rs_children.clear();
+            
RETURN_IF_ERROR(rs_reader->get_key_ordered_iterators(_reader_context, 
&rs_children));
+            for (auto& child : rs_children) {
+                children.push_back(
+                        std::make_unique<RowsetBoundIterator>(rs_reader, 
std::move(child)));
+            }
+        }
+    }
+
+    SCOPED_RAW_TIMER(&_stats->block_reader_build_heap_init_timer_ns);
+    *merge_iter = std::make_unique<VHeapMergeIterator>(std::move(children), 
_read_schema, order);
+    StorageReadOptions opts(*_stats);
+    opts.block_row_max = cast_set<uint32_t>(_batch_limit.max_rows());
+    opts.preferred_block_size_bytes = _batch_limit.preferred_bytes();
+    opts.runtime_state = runtime_state;
+    return (*merge_iter)->init(opts);
+}
+
+Status BlockIteratorBuilder::_init_direct_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    const size_t read_limit = _reader_context->general_read_limit > 0
+                                      ? 
static_cast<size_t>(_reader_context->general_read_limit)
+                                      : 0;
+    std::vector<RowsetReaderSharedPtr> rs_readers;
+    rs_readers.reserve(_read_params.rs_splits.size());
+    RuntimeState* runtime_state = _read_params.runtime_state;
+    {
+        SCOPED_RAW_TIMER(&_stats->block_reader_rs_readers_init_timer_ns);
+        for (const auto& rs_split : _read_params.rs_splits) {
+            if (runtime_state != nullptr && runtime_state->is_cancelled()) {
+                return runtime_state->cancel_reason();
+            }
+            if (read_limit > 0) {
+                rs_split.rs_reader->set_topn_limit(read_limit);
+            }
+            RETURN_IF_ERROR(rs_split.rs_reader->init(_reader_context, 
rs_split));
+            rs_readers.push_back(rs_split.rs_reader);
+        }
+    }
+    *out_iter = std::make_unique<DirectIterator>(std::move(rs_readers), 
_reader_context, _stats);
+    return Status::OK();
+}
+
+Status BlockIteratorBuilder::_init_ordered_block_iter(HeapMergeOrder order,
+                                                      
std::unique_ptr<BlockIterator>* out_iter) {
+    if (!rowsets_not_mono_asc_disjoint(_read_params)) {
+        return _init_direct_iter(out_iter);
+    }
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(order, &merge_iter));
+    *out_iter = std::make_unique<MergeBlockIterator>(std::move(merge_iter));
+    return Status::OK();
+}
+
+Status 
BlockIteratorBuilder::_init_changelog_input_iter(std::unique_ptr<BlockIterator>*
 out_iter) {
+    const int32_t tso_col_idx = _read_schema->tso_ordinal();
+    HeapMergeOrder order = tso_col_idx >= 0
+                                   ? 
HeapMergeOrder::by_all_keys_and_same_key_col(
+                                             tso_col_idx, SortDirection::ASC, 
SortDirection::ASC)
+                                   : 
HeapMergeOrder::by_all_keys(SortDirection::ASC);
+    return _init_ordered_block_iter(order, out_iter);
+}
+
+Status 
BlockIteratorBuilder::_init_key_ordered_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    const auto child_direction =
+            _reader_context->use_insert_order_when_same ? SortDirection::ASC : 
SortDirection::DESC;
+    const int32_t tso_col_idx = _read_schema->tso_ordinal();
+    const int32_t seq_col_idx = _read_schema->sequence_ordinal();
+    HeapMergeOrder order;
+    if (tso_col_idx >= 0) {
+        order = HeapMergeOrder::by_all_keys_and_same_key_col(tso_col_idx, 
SortDirection::ASC,
+                                                             child_direction);
+    } else if (seq_col_idx >= 0) {
+        order = HeapMergeOrder::by_all_keys_and_same_key_col(seq_col_idx, 
SortDirection::DESC,
+                                                             child_direction);
+    } else {
+        order = HeapMergeOrder::by_all_keys(child_direction);
+    }
+    return _init_ordered_block_iter(order, out_iter);
+}
+
+Status 
BlockIteratorBuilder::_init_unique_key_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    DORIS_CHECK(!_reader_context->read_changelog);
+    DORIS_CHECK(!_read_params.read_orderby_key);
+
+    if (!rowsets_not_mono_asc_disjoint(_read_params)) {
+        return _init_direct_iter(out_iter);
+    }
+
+    const int32_t seq_col_idx = _read_schema->sequence_ordinal();
+    HeapMergeOrder order = seq_col_idx >= 0 ? 
HeapMergeOrder::by_all_keys_and_same_key_col(
+                                                      seq_col_idx, 
SortDirection::DESC)
+                                            : HeapMergeOrder::by_all_keys();
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(order, &merge_iter));
+    *out_iter = 
std::make_unique<UniqueKeyBlockIterator>(std::move(merge_iter), _merged_rows);
+    return Status::OK();
+}
+
+Status 
BlockIteratorBuilder::_init_sequence_map_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    DORIS_CHECK(!_reader_context->read_changelog);
+    DORIS_CHECK(!_read_params.read_orderby_key);
+
+    if (!rowsets_not_mono_asc_disjoint(_read_params)) {
+        return _init_direct_iter(out_iter);
+    }
+
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(HeapMergeOrder::by_all_keys(), 
&merge_iter));
+    *out_iter = 
std::make_unique<SequenceMapBlockIterator>(std::move(merge_iter), _batch_limit,
+                                                           _read_schema, 
_merged_rows);
+    return Status::OK();
+}
+
+Status 
BlockIteratorBuilder::_init_agg_key_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    DORIS_CHECK(!_reader_context->read_changelog);
+    DORIS_CHECK(!_read_params.read_orderby_key);
+    DORIS_CHECK(_reader_context->general_read_limit <= 0);
+
+    RowwiseIteratorUPtr merge_iter;
+    RETURN_IF_ERROR(_build_heap_merge_iter(HeapMergeOrder::by_all_keys(), 
&merge_iter));
+    auto agg_iter = 
std::make_unique<AggKeyBlockIterator>(std::move(merge_iter), _batch_limit,
+                                                          _read_schema, 
_merged_rows);
+    Status st = agg_iter->init(_read_params.get_be_exec_version());
+    if (!st.ok()) {
+        st.prepend(fmt::format(
+                "Failed to init reader when init agg state: tablet_id: {}, 
schema_hash: {}, "
+                "reader_type: {}, version: {}: ",
+                _read_params.tablet->tablet_id(), 
_read_params.tablet->schema_hash(),
+                int(_read_params.reader_type), 
_read_params.version.to_string()));
+        return st;
+    }
+    *out_iter = std::move(agg_iter);
+    return Status::OK();
+}
+
+Status BlockIteratorBuilder::_init_topn_iter(std::unique_ptr<BlockIterator>* 
out_iter) {
+    // The scanner pushes a TopN down only without a LIMIT, and TabletReader 
sets up its ORDER BY
+    // columns.
+    RowsetReaderContext* reader_ctx = _reader_context;
+    DORIS_CHECK(reader_ctx->general_read_limit <= 0);
+    DORIS_CHECK(reader_ctx->read_orderby_key_columns != nullptr);
+    const size_t num_block_columns = _read_schema->num_block_columns();
+    for (uint32_t position : *reader_ctx->read_orderby_key_columns) {
+        DORIS_CHECK_LT(position, num_block_columns);
+    }
+    const size_t limit = reader_ctx->read_orderby_key_limit;
+    std::vector<TopNBlockIterator::RowsetOpener> rowsets;
+    for (const auto& rs_split : _read_params.rs_splits) {
+        // A segment gives `limit` rows at most: its later rows cannot be 
among the first `limit`.
+        rs_split.rs_reader->set_topn_limit(limit);
+        rowsets.emplace_back([reader_ctx, 
rs_split](std::vector<RowwiseIteratorUPtr>* streams) {
+            RETURN_IF_ERROR(rs_split.rs_reader->init(reader_ctx, rs_split));
+            // Each stream gives its rows in key order, which the ORDER BY 
columns lead.
+            return rs_split.rs_reader->get_key_ordered_iterators(reader_ctx, 
streams);
+        });
+    }
+    // Newer rowsets tend to hold larger keys, so a descending read starts 
from the newest.
+    const SortDirection direction =
+            reader_ctx->read_orderby_key_reverse ? SortDirection::DESC : 
SortDirection::ASC;
+    if (direction == SortDirection::DESC) {
+        std::ranges::reverse(rowsets);
+    }
+    std::map<uint32_t, DataTypePtr> virtual_column_types;
+    for (const auto& [position, expr_ctx] : reader_ctx->virtual_column_exprs) {
+        virtual_column_types.emplace(position, expr_ctx->root()->data_type());
+    }
+    TopNBlockIterator::FilterUpdater update_filter;
+    if (!reader_ctx->topn_filter_source_node_ids.empty()) {
+        update_filter = [reader_ctx](const Field& value) {
+            auto* query_ctx = reader_ctx->runtime_state->get_query_ctx();
+            for (int id : reader_ctx->topn_filter_source_node_ids) {
+                
RETURN_IF_ERROR(query_ctx->get_runtime_predicate(id).update(value));
+            }
+            return Status::OK();
+        };
+    }
+    *out_iter = std::make_unique<TopNBlockIterator>(
+            std::move(rowsets), limit, *reader_ctx->read_orderby_key_columns, 
direction,
+            std::move(virtual_column_types), std::move(update_filter));
+    return Status::OK();
+}
+
+bool BlockIteratorBuilder::rowsets_not_mono_asc_disjoint(
+        const TabletReader::ReaderParams& read_params) {
+    std::string pre_rs_last_key;
+    bool pre_rs_key_bounds_truncated {false};
+    for (const auto& rs_split : read_params.rs_splits) {
+        if (rs_split.rs_reader->rowset()->num_rows() == 0) {
+            continue;
+        }
+        if (rs_split.rs_reader->rowset()->is_segments_overlapping()) {
+            return true;
+        }
+        std::string rs_first_key;
+        if (!rs_split.rs_reader->rowset()->first_key(&rs_first_key)) {
+            return true;
+        }
+        const bool cur_rs_key_bounds_truncated =
+                
rs_split.rs_reader->rowset()->is_segments_key_bounds_truncated();
+        if (!Slice::lhs_is_strictly_less_than_rhs(Slice {pre_rs_last_key},
+                                                  pre_rs_key_bounds_truncated, 
Slice {rs_first_key},
+                                                  
cur_rs_key_bounds_truncated)) {
+            return true;
+        }
+        const bool has_last_key = 
rs_split.rs_reader->rowset()->last_key(&pre_rs_last_key);
+        pre_rs_key_bounds_truncated = cur_rs_key_bounds_truncated;
+        CHECK(has_last_key);
+    }
+    return false;
+}
+
+BlockIteratorBuilder::Mode BlockIteratorBuilder::select_mode(
+        const TabletReader::ReaderParams& read_params, const BaseTablet& 
tablet,
+        const TabletSchema& tablet_schema, const ReadSchema& read_schema, bool 
direct_mode,
+        bool merge_by_sequence_mapping) {
+    // From read_params: _reader_context gets the limit only in 
_capture_rs_readers().
+    if (read_params.read_orderby_key_limit > 0) {
+        return Mode::TOPN;
+    }
+    if (read_params.changelog_scan_type == TChangelogScanType::MIN_DELTA) {
+        return Mode::CHANGELOG_MIN_DELTA;
+    }
+    if (read_params.changelog_scan_type == TChangelogScanType::DETAIL) {
+        return Mode::CHANGELOG_DETAIL;
+    }
+    if (direct_mode || tablet_schema.keys_type() == KeysType::DUP_KEYS ||
+        (read_params.reader_type == ReaderType::READER_QUERY &&
+         tablet.enable_unique_key_merge_on_write())) {
+        if (read_params.read_orderby_key) {
+            return Mode::KEY_ORDERED;
+        }
+        if (read_params.reader_type == ReaderType::READER_QUERY || direct_mode 
||
+            read_params.read_changelog || read_schema.num_key_columns() == 0) {

Review Comment:
   [P2] Preserve keyless replica checksums across iterator modes
   
   This sends `READER_CHECKSUM` for a keyless DUP_KEYS tablet through the same 
ascending rowset path as horizontal compaction. For two nonempty rowsets at 
versions 2 and 3, the legacy path sees non-disjoint empty key bounds and breaks 
ties newest first. The new path visits version 2 first. `EngineChecksumTask` 
feeds the ordered row stream into SipHash, and the FE persists an inconsistent 
result when replica checksums differ. Identical replicas can therefore be 
flagged during a rolling upgrade or a staged change to the BE flag. Preserve 
checksum ordering and cover it with a two-rowset test under both settings.



##########
be/src/storage/iterator/agg_key_block_aggregator.cpp:
##########
@@ -0,0 +1,200 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/agg_key_block_aggregator.h"
+
+#include <glog/logging.h>
+
+#include <utility>
+
+#include "common/cast_set.h"
+#include "exprs/aggregate/aggregate_function_reader.h"
+#include "storage/iterator/block_key_utils.h"
+#include "storage/tablet/tablet_schema.h"
+
+namespace doris {
+
+AggKeyBlockAggregator::AggKeyBlockAggregator(ReadSchemaSPtr read_schema, 
uint64_t* merged_rows)
+        : _read_schema(std::move(read_schema)),
+          _num_key_columns(_read_schema->num_key_columns()),
+          _merged_rows(merged_rows) {}
+
+AggKeyBlockAggregator::~AggKeyBlockAggregator() {
+    for (auto& aggregation : _aggregations) {
+        aggregation.function->destroy(aggregation.place);
+    }
+}
+
+Status AggKeyBlockAggregator::init(int be_exec_version) {
+    DCHECK(_aggregations.empty());
+    const auto num_block_columns = 
static_cast<uint32_t>(_read_schema->num_block_columns());
+    _aggregations.reserve(num_block_columns - _num_key_columns);
+    for (auto ordinal = static_cast<uint32_t>(_num_key_columns); ordinal < 
num_block_columns;
+         ++ordinal) {
+        const auto& tablet_column = *_read_schema->column(ordinal);
+        const auto& data_type = _read_schema->data_type(ordinal);
+        AggregateFunctionPtr function =
+                tablet_column.get_aggregate_function(AGG_READER_SUFFIX, 
be_exec_version, data_type);
+        if (!function) {
+            return Status::InternalError(
+                    "Failed to init the aggregate function of column {} 
(ordinal {})",
+                    tablet_column.name(), ordinal);
+        }
+        const auto column = data_type->create_column();
+        const IColumn* columns[] = {column.get()};
+        function->check_input_columns_type(columns);
+        function->check_result_column_type(*column);
+
+        AggregateDataPtr place =
+                _state_arena.aligned_alloc(function->size_of_data(), 
function->align_of_data());
+        // A throwing create() leaves the memory to the arena; the places 
created before are in
+        // _aggregations, which is reserved, and the destructor destroys them.
+        function->create(place);
+        _aggregations.push_back(
+                {.ordinal = ordinal, .function = std::move(function), .place = 
place});
+    }
+    _batch_columns = _read_schema->create_read_block().mutate_columns();
+    return Status::OK();
+}
+
+void AggKeyBlockAggregator::_mark_same_keys(const Block& source) {
+    mark_same_keys_in_block(source, _num_key_columns, &_same_key);
+    // The first row goes on with the batch's last key when it has that key.
+    _same_key[0] = _batch_rows > 0 &&
+                   row_matches_first_key(_batch_columns, _batch_rows - 1, 
source, _num_key_columns);
+}
+
+void AggKeyBlockAggregator::aggregate(const Block& source) {
+    const size_t rows = source.rows();
+    DCHECK_GT(rows, 0);
+    _mark_same_keys(source);
+    // The source starts with a new key: the batch's last key is complete.
+    const bool previous_neq = _batch_rows > 0 && !_same_key[0];
+    // 1. The first row of every new key, and the row count of every key. When 
the source goes on
+    // with the batch's last key, its rows are the first count, which has no 
first row.
+    _selective_index.clear();
+    _aggregate_loops.clear();
+    if (_same_key[0]) {
+        _aggregate_loops.push_back(0);
+    }
+    for (size_t pos = 0; pos < rows; ++pos) {
+        if (!_same_key[pos]) {
+            _selective_index.push_back(cast_set<uint32_t>(pos));
+            _aggregate_loops.push_back(0);
+        }
+        ++_aggregate_loops.back();
+    }
+    _batch_rows += _selective_index.size();
+    // Every row but the first of a key is folded into it.
+    *_merged_rows += rows - _selective_index.size();
+    // 2. The key columns of the new keys, as one range when each of them has 
one row.
+    if (!_selective_index.empty()) {
+        const bool every_key_has_one_row =
+                _selective_index.size() == rows - _selective_index.front();
+        for (size_t ordinal = 0; ordinal < _num_key_columns; ++ordinal) {
+            const IColumn& key = *source.get_by_position(ordinal).column;
+            if (every_key_has_one_row) {
+                _batch_columns[ordinal]->insert_range_from(key, 
_selective_index.front(),
+                                                           
_selective_index.size());
+                continue;
+            }
+            _batch_columns[ordinal]->insert_indices_from(
+                    key, _selective_index.data(),
+                    _selective_index.data() + _selective_index.size());
+        }
+    }
+    // 3. The value columns, column by column: every key but the last is 
complete and appended.
+    // The last one stays in the states, as the next source may go on with it.
+    const size_t last_key_start = rows - _aggregate_loops.back();
+    const size_t complete_keys = _aggregate_loops.size() - 1;
+    if (previous_neq || complete_keys > 0) {
+        for (ValueAggregation& aggregation : _aggregations) {
+            if (previous_neq) {
+                _output_value_to_batch(aggregation);
+            }
+            const IColumn& values = 
*source.get_by_position(aggregation.ordinal).column;
+            // A key's own rows are checked for NULLs only when the rows of 
all keys hold one.
+            const bool has_null = values.has_null(0, last_key_start);
+            size_t begin = 0;
+            for (size_t key = 0; key < complete_keys; ++key) {
+                const size_t end = begin + _aggregate_loops[key];
+                _aggregate_range(aggregation, values, begin, end,
+                                 has_null && values.has_null(begin, end));
+                _output_value_to_batch(aggregation);

Review Comment:
   [P2] Reuse AGG scratch as each key finishes
   
   After each finished key is written and reset, its scratch survives until the 
end of the input block. For an `AGG_STATE<collect_set(STRING)>` value, merging 
copies each string into this arena. A fixed batch of about 4,000 distinct keys 
with one 32 KiB value each retains roughly 128 MiB of completed-key scratch 
before the clear, and `Arena::clear()` retains the head chunk. The legacy 
reader clears the arena after each completed key. Give completed keys reusable 
scratch while preserving the state of the key that can span input blocks.



##########
be/src/storage/iterator/topn_block_iterator.cpp:
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/topn_block_iterator.h"
+
+#include <algorithm>
+#include <iterator>
+#include <utility>
+
+#include "common/cast_set.h"
+#include "common/exception.h"
+#include "core/column/column.h"
+#include "core/field.h"
+
+namespace doris {
+
+TopNBlockIterator::TopNBlockIterator(std::vector<RowsetOpener> rowsets, size_t 
limit,
+                                     std::vector<uint32_t> sort_columns, 
SortDirection direction,
+                                     std::map<uint32_t, DataTypePtr> 
virtual_column_types,
+                                     FilterUpdater update_filter)
+        : _rowsets(std::move(rowsets)),
+          _limit(limit),
+          _sort_columns(std::move(sort_columns)),
+          _direction(direction),
+          _virtual_column_types(std::move(virtual_column_types)),
+          _update_filter(std::move(update_filter)) {
+    DORIS_CHECK_GT(_limit, 0);
+    DORIS_CHECK(!_sort_columns.empty());
+}
+
+bool TopNBlockIterator::RowOrder::operator()(size_t lhs, size_t rhs) const {
+    // NULLs are the smallest (-1).
+    const int r = topn->_rows.compare_at(lhs, rhs, &topn->_sort_columns, 
topn->_rows, -1);
+    return topn->_direction == SortDirection::DESC ? r > 0 : r < 0;
+}
+
+bool TopNBlockIterator::_sorts_before(const Block& block, size_t row, size_t 
top_row) const {
+    for (uint32_t position : _sort_columns) {
+        const int r = block.get_by_position(position).column->compare_at(
+                row, top_row, *_rows.get_column_by_position(position), -1);
+        if (r != 0) {
+            return _direction == SortDirection::DESC ? r > 0 : r < 0;
+        }
+    }
+    return false;
+}
+
+Status TopNBlockIterator::next_block(Block* block, bool* eof) {
+    if (_done) {
+        *eof = true;
+        return Status::OK();
+    }
+    _done = true;
+    RETURN_IF_ERROR_OR_CATCH_EXCEPTION([&]() -> Status {
+        // A virtual column holds an empty placeholder in the read Blocks 
until a segment fills it;
+        // the rows kept need a column of its type.
+        Block empty_rows = block->clone_empty();
+        for (const auto& [position, type] : _virtual_column_types) {
+            DORIS_CHECK_LT(position, empty_rows.columns());
+            empty_rows.get_by_position(position).column = 
type->create_column();
+        }
+        _rows = MutableBlock::build_mutable_block(std::move(empty_rows));
+
+        for (RowsetOpener& open_rowset : _rowsets) {
+            {
+                std::vector<RowwiseIteratorUPtr> streams;
+                RETURN_IF_ERROR(open_rowset(&streams));
+                for (RowwiseIteratorUPtr& stream : streams) {
+                    RETURN_IF_ERROR(_read_stream(stream.get(), block));
+                    // Release a segment once it is read, not at the end of 
its rowset.
+                    stream.reset();
+                }
+            }
+            // Release the opener's captured RowsetReader once all of its 
segments are closed.
+            open_rowset = nullptr;
+        }
+        _rowsets = {};
+        _remove_dropped_rows();
+        *block = _rows.to_block();
+        _selected_indices = {};
+        _top_rows.clear();
+        return Status::OK();
+    }());
+    *eof = block->rows() == 0;
+    return Status::OK();
+}
+
+Status TopNBlockIterator::_read_stream(RowwiseIterator* stream, Block* block) {
+    size_t read_rows = 0;
+    while (read_rows < _limit) {
+        block->clear_column_data();
+        Status st = stream->next_batch(block);
+        if (st.is<ErrorCode::END_OF_FILE>()) {
+            break;
+        }
+        RETURN_IF_ERROR(st);
+        read_rows += block->rows();
+        RETURN_IF_ERROR(_keep_top_rows(*block));

Review Comment:
   [P2] Stop reading sorted TopN streams after the cutoff
   
   Once a full TopN rejects a row from a sorted stream, every later row in that 
stream is also outside the cutoff. The loop still reads up to LIMIT rows from 
each segment. For an ascending TopN with limit K, the first segment of an 
overlapping rowset can supply all K winners while other segments start above 
the cutoff. With the runtime filter disabled, for example with 
`topn_filter_ratio=0`, this reads up to K extra rows per losing segment. The 
legacy rowset heap consumed roughly one initial batch from each losing segment 
in this case. Distinguish an empty filtered batch from reaching the cutoff, and 
stop the stream when its first losing row is encountered.



##########
be/src/storage/iterator/heap_merge_iterator.cpp:
##########
@@ -0,0 +1,243 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/heap_merge_iterator.h"
+
+#include <algorithm>
+#include <utility>
+
+#include "common/cast_set.h"
+#include "common/exception.h"
+#include "common/status.h"
+#include "core/block/block.h"
+#include "core/column/column.h"
+#include "runtime/runtime_profile.h"
+#include "runtime/runtime_state.h"
+#include "storage/iterators.h"
+#include "storage/schema.h"
+#include "storage/tablet/tablet_schema.h"
+
+namespace doris {
+using namespace ErrorCode;
+
+HeapMergeOrder HeapMergeOrder::by_all_keys(SortDirection 
child_iterator_direction) {
+    HeapMergeOrder order;
+    order._child_iterator_direction = child_iterator_direction;
+    return order;
+}
+
+HeapMergeOrder HeapMergeOrder::by_all_keys_and_same_key_col(
+        int32_t same_key_sort_col_idx, SortDirection same_key_sort_direction,
+        SortDirection child_iterator_direction) {
+    DORIS_CHECK_GE(same_key_sort_col_idx, 0);
+    HeapMergeOrder order;
+    order._same_key_sort_col_idx = same_key_sort_col_idx;
+    order._same_key_sort_direction = same_key_sort_direction;
+    order._child_iterator_direction = child_iterator_direction;
+    return order;
+}
+
+std::vector<HeapSortCol> HeapMergeOrder::resolve_sort_cols(size_t 
num_key_columns) const {
+    std::vector<HeapSortCol> cols;
+    cols.reserve(num_key_columns + (_same_key_sort_col_idx >= 0 ? 1 : 0));
+    for (size_t col_idx = 0; col_idx < num_key_columns; ++col_idx) {
+        cols.push_back({cast_set<uint32_t>(col_idx), SortDirection::ASC});
+    }
+    if (_same_key_sort_col_idx >= 0) {
+        cols.push_back({static_cast<uint32_t>(_same_key_sort_col_idx), 
_same_key_sort_direction});
+    }
+    return cols;
+}
+
+VHeapMergeIterator::VHeapMergeIterator(std::vector<RowwiseIteratorUPtr> 
children,
+                                       ReadSchemaSPtr read_schema, 
HeapMergeOrder order)
+        : _read_schema(std::move(read_schema)),
+          _sort_cols(order.resolve_sort_cols(_read_schema->num_key_columns())),
+          _child_iterator_direction(order.child_iterator_direction()) {
+    _children.reserve(children.size());
+    for (auto& child : children) {
+        _children.emplace_back();
+        _children.back().iter = std::move(child);
+    }
+}
+
+Status VHeapMergeIterator::init(const StorageReadOptions& opts) {
+    _batch_limit = BlockBatchLimit(opts.block_row_max, 
opts.preferred_block_size_bytes);
+    _runtime_state = opts.runtime_state;
+    _stats = opts.stats;
+
+    for (size_t index = 0; index < _children.size(); ++index) {
+        // An empty Block is used up: the child reads its first Block.
+        _children[index].block = _read_schema->create_read_block();
+        RETURN_IF_ERROR(_push_back_to_heap(cast_set<uint32_t>(index)));
+    }
+    return Status::OK();
+}
+
+Status VHeapMergeIterator::_push_back_to_heap(uint32_t child) {
+    Child& current = _children[child];
+    if (current.pos == current.block.rows()) {
+        bool eof = false;
+        RETURN_IF_ERROR(_read_next_block(&current, &eof));
+        if (eof) {
+            // The child is done: release its segment and its Block now, not 
at the end of the
+            // merge.
+            current.iter.reset();
+            current.block.clear();
+            return Status::OK();
+        }
+    }
+    _heap.push(child);
+    return Status::OK();
+}
+
+Status VHeapMergeIterator::_read_next_block(Child* child, bool* eof) {
+    SCOPED_RAW_TIMER(&_stats->block_fetch_ns);
+    // A segment returns an empty batch when its predicates filter out every 
row it read.
+    do {
+        child->block.clear_column_data();
+        Status st = child->iter->next_batch(&child->block);
+        if (st.is<END_OF_FILE>()) {
+            DCHECK_EQ(child->block.rows(), 0);
+            *eof = true;
+            return Status::OK();
+        }
+        RETURN_IF_ERROR(st);
+        if (_runtime_state != nullptr && _runtime_state->is_cancelled()) 
[[unlikely]] {
+            return _runtime_state->cancel_reason();
+        }
+    } while (child->block.rows() == 0);
+    DCHECK_EQ(child->block.columns(), _read_schema->num_block_columns());
+    child->pos = 0;
+    *eof = false;
+    return Status::OK();
+}
+
+bool VHeapMergeIterator::_less_than_current_row(uint32_t child, size_t row, 
uint32_t other) const {
+    const Block& block = _children[child].block;
+    const Child& other_child = _children[other];
+    for (const auto& [col_idx, direction] : _sort_cols) {
+        // NULLs are smallest (-1).
+        const int r = block.get_by_position(col_idx).column->compare_at(
+                row, other_child.pos, 
*other_child.block.get_by_position(col_idx).column, -1);
+        if (r != 0) {
+            return direction == SortDirection::ASC ? r < 0 : r > 0;
+        }
+    }
+    return _child_iterator_direction == SortDirection::ASC ? child < other : 
child > other;
+}
+
+size_t VHeapMergeIterator::_rows_before_next_child(uint32_t child, size_t 
limit) const {
+    DCHECK(!_heap.empty());
+    const Child& current = _children[child];
+    limit = std::min(limit, current.block.rows() - current.pos);
+    // The current row goes first, as the child was on top of the heap.
+    const uint32_t next = _heap.top();
+    size_t rows = 1;
+    while (rows < limit && _less_than_current_row(child, current.pos + rows, 
next)) {
+        ++rows;
+    }
+    return rows;
+}
+
+size_t VHeapMergeIterator::_output_row_limit() const {
+    if (_batch_limit.preferred_bytes() == 0) [[unlikely]] {
+        return _batch_limit.max_rows();
+    }
+    // A child that is done holds an empty Block.
+    size_t bytes = 0;
+    size_t rows = 0;
+    for (const Child& child : _children) {

Review Comment:
   [P2] Maintain running totals for adaptive heap sizing
   
   The adaptive path walks every child and every column in its current block 
before each output, including revisiting retired child slots. With N one-block 
children whose ranges are mostly disjoint and one overlap forcing the heap, 
whole-block transfers can produce about N outputs. That drives quadratic child 
visits and column size calls. Adaptive sizing is enabled by default, and a 
tablet can hold thousands of rowsets. Update the total rows and bytes when a 
child block is loaded or retired so choosing the next output size is constant 
time.



##########
be/src/storage/iterator/agg_key_block_iterator.cpp:
##########
@@ -0,0 +1,62 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/agg_key_block_iterator.h"
+
+#include <utility>
+
+#include "common/exception.h"
+#include "storage/iterators.h"
+
+namespace doris {
+
+AggKeyBlockIterator::AggKeyBlockIterator(RowwiseIteratorUPtr input, 
BlockBatchLimit batch_limit,
+                                         ReadSchemaSPtr read_schema, uint64_t* 
merged_rows)
+        : _input(std::move(input)),
+          _batch_limit(batch_limit),
+          _input_block(read_schema->create_read_block()),
+          _aggregator(std::move(read_schema), merged_rows) {}
+
+Status AggKeyBlockIterator::init(int be_exec_version) {
+    return _aggregator.init(be_exec_version);
+}
+
+Status AggKeyBlockIterator::next_block(Block* block, bool* eof) {
+    *eof = false;
+    while (true) {
+        _input_block.clear_column_data();
+        Status st = _input->next_batch(&_input_block);
+        if (st.is<ErrorCode::END_OF_FILE>()) {
+            break;
+        }
+        RETURN_IF_ERROR(st);
+        RETURN_IF_CATCH_EXCEPTION(_aggregator.aggregate(_input_block));
+        // The last key may go on in the next merged Block, so it stays for 
the next batch.
+        if (_aggregator.batch_rows() > _batch_limit.row_limit(_input_block)) {

Review Comment:
   [P2] Keep AGG and sequence-map output within the row cap
   
   With a row cap of 3, two consecutive three-row input blocks with six 
distinct keys leave six buffered keys. This branch emits five rows because it 
keeps only the last key. `SequenceMapBlockIterator::next_block()` has the same 
pattern on overlapping rowsets. The legacy readers stop at `batch_max_rows()`, 
and the configured ceiling can be exceeded by nearly 2x here. Carry excess 
finished keys into the next output block or stop folding the current input at 
the output boundary. Test consecutive full input blocks that share no boundary 
key.



##########
be/src/storage/iterator/topn_block_iterator.cpp:
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/iterator/topn_block_iterator.h"
+
+#include <algorithm>
+#include <iterator>
+#include <utility>
+
+#include "common/cast_set.h"
+#include "common/exception.h"
+#include "core/column/column.h"
+#include "core/field.h"
+
+namespace doris {
+
+TopNBlockIterator::TopNBlockIterator(std::vector<RowsetOpener> rowsets, size_t 
limit,
+                                     std::vector<uint32_t> sort_columns, 
SortDirection direction,
+                                     std::map<uint32_t, DataTypePtr> 
virtual_column_types,
+                                     FilterUpdater update_filter)
+        : _rowsets(std::move(rowsets)),
+          _limit(limit),
+          _sort_columns(std::move(sort_columns)),
+          _direction(direction),
+          _virtual_column_types(std::move(virtual_column_types)),
+          _update_filter(std::move(update_filter)) {
+    DORIS_CHECK_GT(_limit, 0);
+    DORIS_CHECK(!_sort_columns.empty());
+}
+
+bool TopNBlockIterator::RowOrder::operator()(size_t lhs, size_t rhs) const {
+    // NULLs are the smallest (-1).
+    const int r = topn->_rows.compare_at(lhs, rhs, &topn->_sort_columns, 
topn->_rows, -1);
+    return topn->_direction == SortDirection::DESC ? r > 0 : r < 0;
+}
+
+bool TopNBlockIterator::_sorts_before(const Block& block, size_t row, size_t 
top_row) const {
+    for (uint32_t position : _sort_columns) {
+        const int r = block.get_by_position(position).column->compare_at(
+                row, top_row, *_rows.get_column_by_position(position), -1);
+        if (r != 0) {
+            return _direction == SortDirection::DESC ? r > 0 : r < 0;
+        }
+    }
+    return false;
+}
+
+Status TopNBlockIterator::next_block(Block* block, bool* eof) {
+    if (_done) {
+        *eof = true;
+        return Status::OK();
+    }
+    _done = true;
+    RETURN_IF_ERROR_OR_CATCH_EXCEPTION([&]() -> Status {
+        // A virtual column holds an empty placeholder in the read Blocks 
until a segment fills it;
+        // the rows kept need a column of its type.
+        Block empty_rows = block->clone_empty();
+        for (const auto& [position, type] : _virtual_column_types) {
+            DORIS_CHECK_LT(position, empty_rows.columns());
+            empty_rows.get_by_position(position).column = 
type->create_column();
+        }
+        _rows = MutableBlock::build_mutable_block(std::move(empty_rows));
+
+        for (RowsetOpener& open_rowset : _rowsets) {
+            {
+                std::vector<RowwiseIteratorUPtr> streams;
+                RETURN_IF_ERROR(open_rowset(&streams));
+                for (RowwiseIteratorUPtr& stream : streams) {
+                    RETURN_IF_ERROR(_read_stream(stream.get(), block));
+                    // Release a segment once it is read, not at the end of 
its rowset.
+                    stream.reset();
+                }
+            }
+            // Release the opener's captured RowsetReader once all of its 
segments are closed.
+            open_rowset = nullptr;
+        }
+        _rowsets = {};
+        _remove_dropped_rows();
+        *block = _rows.to_block();
+        _selected_indices = {};
+        _top_rows.clear();
+        return Status::OK();
+    }());
+    *eof = block->rows() == 0;
+    return Status::OK();
+}
+
+Status TopNBlockIterator::_read_stream(RowwiseIterator* stream, Block* block) {
+    size_t read_rows = 0;
+    while (read_rows < _limit) {
+        block->clear_column_data();
+        Status st = stream->next_batch(block);

Review Comment:
   [P2] Poll cancellation inside storage TopN
   
   The legacy TopN called `BetaRowsetReader::next_batch()`, which checks the 
runtime state after each successful input batch. This now reads raw segment or 
union streams. Those can keep reading local files after cancellation, and the 
scanner cannot poll until this call returns. Check cancellation before opening 
a rowset and between input batches so a cancelled query releases its scan 
worker promptly.



##########
be/src/storage/iterator/changelog_detail_block_iterator.h:
##########
@@ -0,0 +1,68 @@
+// 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.
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+#include "common/status.h"
+#include "core/block/block.h"
+#include "core/column/column.h"
+#include "core/custom_allocator.h"
+#include "storage/changelog_types.h"
+#include "storage/iterator/block_batch_limit.h"
+#include "storage/iterator/block_iterator.h"
+#include "storage/iterator/changelog_iterator_utils.h"
+#include "storage/schema.h"
+
+namespace doris {
+
+// Emits every recorded changelog event in (key, TSO) order for DETAIL scans: 
APPEND -> INSERT,
+// DELETE -> DELETE (with before image), UPDATE -> UPDATE_BEFORE + 
UPDATE_AFTER (always kept
+// together in the same output Block, so an output Block holds at most 
`row_limit + 1` rows).
+// Processes each input Block slice column-by-column using range, index, or 
multi-column copies.
+class ChangelogDetailBlockIterator final : public BlockIterator {
+public:
+    ChangelogDetailBlockIterator(std::unique_ptr<BlockIterator> input, 
BlockBatchLimit batch_limit,
+                                 ReadSchemaSPtr read_schema);
+
+    Status next_block(Block* block, bool* eof) override;
+
+    void update_profile(RuntimeProfile* profile) override { 
_cursor.update_profile(profile); }
+
+private:
+    size_t _collect_slice(const Block& src_block, size_t start_pos, size_t 
remaining);
+    Status _copy_slice(const Block& src_block, size_t start_pos, size_t 
end_pos,
+                       MutableColumns* target_columns);
+    Status _emit_block_slice(MutableColumns* target_columns, size_t* 
output_rows);
+
+    changelog::ChangelogInputCursor _cursor;
+    const ReadSchemaSPtr _read_schema;
+    const int32_t _op_col_idx;
+
+    // Reusable per-slice batch buffers to keep column copies vectorized 
without heap churn.
+    DorisVector<uint32_t> _src_row_indices;
+    DorisVector<changelog::StreamChangeOp> _output_ops;
+    // IColumn::insert_from_multi_column requires std::vector with default 
allocator.
+    std::vector<const IColumn*> _multi_srcs;

Review Comment:
   [P2] Account for the DETAIL gather buffers
   
   A mixed DETAIL batch resizes both scratch vectors to the output row count. 
With the supported `batch_size=65535`, update expansion can bring that to 
65,536 entries, roughly 1 MiB of untracked memory per scanner on a 64-bit BE. 
These default-allocator vectors keep their capacity across batches. Accept 
read-only spans in `insert_from_multi_column()` and use `DorisVector` for both 
buffers so concurrent DETAIL scans are charged to the query memory tracker.



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to