Coverage Report

Created: 2026-07-27 20:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/rowset/beta_rowset_reader.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "storage/rowset/beta_rowset_reader.h"
19
20
#include <stddef.h>
21
22
#include <algorithm>
23
#include <memory>
24
#include <ostream>
25
#include <roaring/roaring.hh>
26
#include <set>
27
#include <string>
28
#include <unordered_map>
29
#include <utility>
30
31
#include "common/logging.h"
32
#include "common/status.h"
33
#include "core/block/block.h"
34
#include "io/io_common.h"
35
#include "runtime/descriptors.h"
36
#include "runtime/query_context.h"
37
#include "runtime/runtime_profile.h"
38
#include "storage/binlog.h"
39
#include "storage/delete/delete_handler.h"
40
#include "storage/iterator/vgeneric_iterators.h"
41
#include "storage/olap_define.h"
42
#include "storage/predicate/block_column_predicate.h"
43
#include "storage/predicate/column_predicate.h"
44
#include "storage/row_cursor.h"
45
#include "storage/rowset/rowset_meta.h"
46
#include "storage/rowset/rowset_reader_context.h"
47
#include "storage/schema.h"
48
#include "storage/segment/lazy_init_segment_iterator.h"
49
#include "storage/segment/segment.h"
50
#include "storage/tablet/tablet_meta.h"
51
#include "storage/tablet/tablet_schema.h"
52
53
namespace doris {
54
using namespace ErrorCode;
55
56
BetaRowsetReader::BetaRowsetReader(BetaRowsetSharedPtr rowset)
57
2.16k
        : _read_context(nullptr), _rowset(std::move(rowset)), _stats(&_owned_stats) {
58
2.16k
    _rowset->acquire();
59
2.16k
}
60
61
2.08k
void BetaRowsetReader::reset_read_options() {
62
2.08k
    _read_options.delete_condition_predicates = AndBlockColumnPredicate::create_shared();
63
2.08k
    _read_options.column_predicates.clear();
64
2.08k
    _read_options.col_id_to_predicates.clear();
65
2.08k
    _read_options.del_predicates_for_zone_map.clear();
66
2.08k
    _read_options.key_ranges.clear();
67
2.08k
}
68
69
0
RowsetReaderSharedPtr BetaRowsetReader::clone() {
70
0
    return RowsetReaderSharedPtr(new BetaRowsetReader(_rowset));
71
0
}
72
73
0
void BetaRowsetReader::update_profile(RuntimeProfile* profile) {
74
0
    if (_iterator != nullptr) {
75
0
        _iterator->update_profile(profile);
76
0
    }
77
0
}
78
79
Status BetaRowsetReader::get_segment_iterators(RowsetReaderContext* read_context,
80
                                               std::vector<RowwiseIteratorUPtr>* out_iters,
81
2.79k
                                               bool use_cache) {
82
2.79k
    _read_context = read_context;
83
    // The segment iterator is created with its own statistics,
84
    // and the member variable '_stats'  is initialized by '_stats(&owned_stats)'.
85
    // The choice of statistics used depends on the workload of the rowset reader.
86
    // For instance, if it's for query, the get_segment_iterators function
87
    // will receive one valid read_context with corresponding valid statistics,
88
    // and we will use those statistics.
89
    // However, for compaction or schema change workloads,
90
    // the read_context passed to the function will have null statistics,
91
    // and in such cases we will try to use the beta rowset reader's own statistics.
92
2.79k
    if (_read_context->stats != nullptr) {
93
2.60k
        _stats = _read_context->stats;
94
2.60k
    }
95
2.79k
    SCOPED_RAW_TIMER(&_stats->rowset_reader_get_segment_iterators_timer_ns);
96
97
2.79k
    RETURN_IF_ERROR(_rowset->load());
98
99
    // convert RowsetReaderContext to StorageReadOptions
100
2.79k
    _read_options.block_row_max = read_context->batch_size;
101
2.79k
    _read_options.preferred_block_size_bytes = read_context->preferred_block_size_bytes;
102
2.79k
    _read_options.stats = _stats;
103
2.79k
    _read_options.push_down_agg_type_opt = _read_context->push_down_agg_type_opt;
104
2.79k
    _read_options.common_expr_ctxs_push_down = _read_context->common_expr_ctxs_push_down;
105
2.79k
    _read_options.virtual_column_exprs = _read_context->virtual_column_exprs;
106
107
2.79k
    _read_options.all_access_paths = _read_context->all_access_paths;
108
2.79k
    _read_options.predicate_access_paths = _read_context->predicate_access_paths;
109
110
2.79k
    _read_options.ann_topn_runtime = _read_context->ann_topn_runtime;
111
2.79k
    _read_options.score_runtime = _read_context->score_runtime;
112
2.79k
    _read_options.collection_statistics = _read_context->collection_statistics;
113
2.79k
    _read_options.rowset_id = _rowset->rowset_id();
114
2.79k
    _read_options.version = _rowset->version();
115
2.79k
    _read_options.commit_tso = _rowset->rowset_meta()->commit_tso();
116
2.79k
    _read_options.tablet_id = _rowset->rowset_meta()->tablet_id();
117
2.79k
    _read_options.read_limit = _topn_limit;
118
2.79k
    if (_read_context->lower_bound_keys != nullptr) {
119
2.37k
        for (int i = 0; i < _read_context->lower_bound_keys->size(); ++i) {
120
0
            _read_options.key_ranges.emplace_back(&_read_context->lower_bound_keys->at(i),
121
0
                                                  _read_context->is_lower_keys_included->at(i),
122
0
                                                  &_read_context->upper_bound_keys->at(i),
123
0
                                                  _read_context->is_upper_keys_included->at(i));
124
0
        }
125
2.37k
    }
126
127
    // delete_hanlder is always set, but it maybe not init, so that it will return empty conditions
128
    // or predicates when it is not inited.
129
2.79k
    if (_read_context->delete_handler != nullptr) {
130
2.37k
        _read_context->delete_handler->get_delete_conditions_after_version(
131
2.37k
                _rowset->end_version(), _read_options.delete_condition_predicates.get(),
132
2.37k
                &_read_options.del_predicates_for_zone_map);
133
2.37k
    }
134
135
2.79k
    std::vector<uint32_t> read_columns;
136
2.79k
    std::set<uint32_t> read_columns_set;
137
2.79k
    std::set<uint32_t> delete_columns_set;
138
11.1k
    for (int i = 0; i < _read_context->return_columns->size(); ++i) {
139
8.33k
        read_columns.push_back(_read_context->return_columns->at(i));
140
8.33k
        read_columns_set.insert(_read_context->return_columns->at(i));
141
8.33k
    }
142
2.79k
    _read_options.delete_condition_predicates->get_all_column_ids(delete_columns_set);
143
2.79k
    for (auto cid : delete_columns_set) {
144
812
        if (read_columns_set.find(cid) == read_columns_set.end()) {
145
508
            read_columns.push_back(cid);
146
508
        }
147
812
    }
148
2.79k
    if (_read_context->tso_predicate_column_id.has_value()) {
149
0
        read_columns.push_back(*_read_context->tso_predicate_column_id);
150
0
    }
151
    // disable condition cache if you have delete condition
152
2.79k
    _read_context->condition_cache_digest =
153
2.79k
            delete_columns_set.empty() ? _read_context->condition_cache_digest : 0;
154
    // create segment iterators
155
2.79k
    VLOG_NOTICE << "read columns size: " << read_columns.size();
156
2.79k
    _input_schema = std::make_shared<Schema>(_read_context->tablet_schema->columns(), read_columns);
157
2.79k
    _read_options.extra_columns = _read_context->extra_columns;
158
    // output_schema only contains return_columns (excludes extra columns like delete-predicate
159
    // columns and the TSO predicate-only column).
160
    // It is used by merge/union iterators to determine how many columns to copy to the output block.
161
2.79k
    _output_schema = std::make_shared<Schema>(_read_context->tablet_schema->columns(),
162
2.79k
                                              *(_read_context->return_columns));
163
2.79k
    if (_read_context->predicates != nullptr) {
164
2.58k
        _read_options.column_predicates.insert(_read_options.column_predicates.end(),
165
2.58k
                                               _read_context->predicates->begin(),
166
2.58k
                                               _read_context->predicates->end());
167
2.58k
        for (auto pred : *(_read_context->predicates)) {
168
126
            if (_read_options.col_id_to_predicates.count(pred->column_id()) < 1) {
169
126
                _read_options.col_id_to_predicates.insert(
170
126
                        {pred->column_id(), AndBlockColumnPredicate::create_shared()});
171
126
            }
172
126
            _read_options.col_id_to_predicates[pred->column_id()]->add_column_predicate(
173
126
                    SingleColumnBlockPredicate::create_unique(pred));
174
126
        }
175
2.58k
    }
176
177
    // Take a delete-bitmap for each segment, the bitmap contains all deletes
178
    // until the max read version, which is read_context->version.second
179
2.79k
    if (_read_context->delete_bitmap != nullptr) {
180
10
        {
181
10
            SCOPED_RAW_TIMER(&_stats->delete_bitmap_get_agg_ns);
182
10
            RowsetId rowset_id = rowset()->rowset_id();
183
78
            for (uint32_t seg_id = 0; seg_id < rowset()->num_segments(); ++seg_id) {
184
68
                auto d = _read_context->delete_bitmap->get_agg(
185
68
                        {rowset_id, seg_id, _read_context->version.second});
186
68
                if (d->isEmpty()) {
187
22
                    continue; // Empty delete bitmap for the segment
188
22
                }
189
46
                VLOG_TRACE << "Get the delete bitmap for rowset: " << rowset_id.to_string()
190
0
                           << ", segment id:" << seg_id << ", size:" << d->cardinality();
191
46
                _read_options.delete_bitmap.emplace(seg_id, std::move(d));
192
46
            }
193
10
        }
194
10
    }
195
196
2.79k
    if (_should_push_down_value_predicates()) {
197
        // sequence mapping currently only support merge on read, so can not push down value predicates
198
1.20k
        if (_read_context->value_predicates != nullptr &&
199
1.20k
            !read_context->tablet_schema->has_seq_map()) {
200
1.07k
            _read_options.column_predicates.insert(_read_options.column_predicates.end(),
201
1.07k
                                                   _read_context->value_predicates->begin(),
202
1.07k
                                                   _read_context->value_predicates->end());
203
1.07k
            for (auto pred : *(_read_context->value_predicates)) {
204
0
                if (_read_options.col_id_to_predicates.count(pred->column_id()) < 1) {
205
0
                    _read_options.col_id_to_predicates.insert(
206
0
                            {pred->column_id(), AndBlockColumnPredicate::create_shared()});
207
0
                }
208
0
                _read_options.col_id_to_predicates[pred->column_id()]->add_column_predicate(
209
0
                        SingleColumnBlockPredicate::create_unique(pred));
210
0
            }
211
1.07k
        }
212
1.20k
    }
213
2.79k
    _read_options.use_page_cache = _read_context->use_page_cache;
214
2.79k
    _read_options.tablet_schema = _read_context->tablet_schema;
215
2.79k
    _read_options.enable_unique_key_merge_on_write =
216
2.79k
            _read_context->enable_unique_key_merge_on_write;
217
2.79k
    _read_options.record_rowids = _read_context->record_rowids;
218
2.79k
    _read_options.topn_filter_source_node_ids = _read_context->topn_filter_source_node_ids;
219
2.79k
    _read_options.topn_filter_target_node_id = _read_context->topn_filter_target_node_id;
220
2.79k
    _read_options.read_orderby_key_reverse = _read_context->read_orderby_key_reverse;
221
2.79k
    _read_options.use_insert_order_when_same = _read_context->use_insert_order_when_same;
222
2.79k
    int32_t tso_col_id = _read_context->tablet_schema->binlog_tso_col_idx();
223
2.79k
    if (tso_col_id >= 0) {
224
10
        for (size_t i = 0; i < _read_context->return_columns->size(); ++i) {
225
10
            if (_read_context->return_columns->at(i) == static_cast<uint32_t>(tso_col_id)) {
226
2
                _read_options.binlog_tso_idx = static_cast<int>(i);
227
2
                break;
228
2
            }
229
10
        }
230
2
    }
231
2.79k
    _read_options.read_orderby_key_columns = _read_context->read_orderby_key_columns;
232
2.79k
    _read_options.io_ctx.reader_type = _read_context->reader_type;
233
2.79k
    _read_options.io_ctx.file_cache_stats = &_stats->file_cache_stats;
234
2.79k
    _read_options.runtime_state = _read_context->runtime_state;
235
2.79k
    _read_options.output_columns = _read_context->output_columns;
236
2.79k
    _read_options.io_ctx.reader_type = _read_context->reader_type;
237
2.79k
    _read_options.io_ctx.is_disposable = _read_context->reader_type != ReaderType::READER_QUERY;
238
2.79k
    _read_options.target_cast_type_for_variants = _read_context->target_cast_type_for_variants;
239
2.79k
    if (_read_context->runtime_state != nullptr) {
240
212
        _read_options.io_ctx.query_id = &_read_context->runtime_state->query_id();
241
212
        _read_options.io_ctx.read_file_cache =
242
212
                _read_context->runtime_state->query_options().enable_file_cache;
243
212
        _read_options.io_ctx.is_disposable =
244
212
                _read_context->runtime_state->query_options().disable_file_cache;
245
212
        auto* query_ctx = _read_context->runtime_state->get_query_ctx();
246
212
        if (_read_context->reader_type == ReaderType::READER_QUERY && query_ctx != nullptr) {
247
0
            _read_options.io_ctx.remote_scan_cache_write_limiter =
248
0
                    query_ctx->remote_scan_cache_write_limiter();
249
0
        }
250
212
    }
251
252
2.79k
    if (_read_context->condition_cache_digest) {
253
0
        for (const auto& key_range : _read_options.key_ranges) {
254
0
            _read_context->condition_cache_digest =
255
0
                    key_range.get_digest(_read_context->condition_cache_digest);
256
0
        }
257
0
        _read_options.condition_cache_digest = _read_context->condition_cache_digest;
258
0
    }
259
260
2.79k
    _read_options.io_ctx.expiration_time = read_context->ttl_seconds;
261
262
2.79k
    bool enable_segment_cache = true;
263
2.79k
    auto* state = read_context->runtime_state;
264
2.79k
    if (state != nullptr) {
265
212
        enable_segment_cache = state->query_options().__isset.enable_segment_cache
266
212
                                       ? state->query_options().enable_segment_cache
267
212
                                       : true;
268
212
    }
269
    // When reader type is for query, session variable `enable_segment_cache` should be respected.
270
2.79k
    bool should_use_cache = use_cache || (_read_context->reader_type == ReaderType::READER_QUERY &&
271
2.79k
                                          enable_segment_cache);
272
273
2.79k
    auto segment_count = _rowset->num_segments();
274
2.79k
    auto [seg_start, seg_end] = _segment_offsets;
275
    // If seg_start == seg_end, it means that the segments of a rowset is not
276
    // split scanned by multiple scanners, and the rowset reader is used to read the whole rowset.
277
2.79k
    if (seg_start == seg_end) {
278
2.79k
        seg_start = 0;
279
2.79k
        seg_end = segment_count;
280
2.79k
    }
281
2.79k
    if (_read_context->record_rowids && _read_context->rowid_conversion) {
282
        // init segment rowid map for rowid conversion
283
796
        std::vector<uint32_t> segment_rows;
284
796
        RETURN_IF_ERROR(_rowset->get_segment_num_rows(&segment_rows, should_use_cache, _stats));
285
796
        RETURN_IF_ERROR(_read_context->rowid_conversion->init_segment_map(rowset()->rowset_id(),
286
796
                                                                          segment_rows));
287
796
    }
288
289
8.80k
    for (int64_t i = seg_start; i < seg_end; i++) {
290
6.01k
        SCOPED_RAW_TIMER(&_stats->rowset_reader_create_iterators_timer_ns);
291
6.01k
        std::unique_ptr<RowwiseIterator> iter;
292
293
        /// For iterators, we don't need to initialize them all at once when creating them.
294
        /// Instead, we should initialize each iterator separately when really using them.
295
        /// This optimization minimizes the lifecycle of resources like column readers
296
        /// and prevents excessive memory consumption, especially for wide tables.
297
6.01k
        if (_segment_row_ranges.empty()) {
298
6.01k
            _read_options.row_ranges.clear();
299
6.01k
            iter = std::make_unique<LazyInitSegmentIterator>(_rowset, i, should_use_cache,
300
6.01k
                                                             _input_schema, _read_options);
301
6.01k
        } else {
302
0
            DCHECK_EQ(seg_end - seg_start, _segment_row_ranges.size());
303
0
            auto local_options = _read_options;
304
0
            local_options.row_ranges = _segment_row_ranges[i - seg_start];
305
0
            if (local_options.condition_cache_digest) {
306
0
                local_options.condition_cache_digest =
307
0
                        local_options.row_ranges.get_digest(local_options.condition_cache_digest);
308
0
            }
309
0
            iter = std::make_unique<LazyInitSegmentIterator>(_rowset, i, should_use_cache,
310
0
                                                             _input_schema, local_options);
311
0
        }
312
313
6.01k
        if (iter->empty()) {
314
0
            continue;
315
0
        }
316
6.01k
        out_iters->push_back(std::move(iter));
317
6.01k
    }
318
319
2.79k
    return Status::OK();
320
2.79k
}
321
322
708
Status BetaRowsetReader::init(RowsetReaderContext* read_context, const RowSetSplits& rs_splits) {
323
708
    _read_context = read_context;
324
708
    _read_context->rowset_id = _rowset->rowset_id();
325
708
    _segment_offsets = rs_splits.segment_offsets;
326
708
    _segment_row_ranges = rs_splits.segment_row_ranges;
327
708
    return Status::OK();
328
708
}
329
330
13.7k
Status BetaRowsetReader::_init_iterator_once() {
331
13.7k
    return _init_iter_once.call([this] { return _init_iterator(); });
332
13.7k
}
333
334
708
Status BetaRowsetReader::_init_iterator() {
335
708
    std::vector<RowwiseIteratorUPtr> iterators;
336
708
    RETURN_IF_ERROR(get_segment_iterators(_read_context, &iterators));
337
338
708
    SCOPED_RAW_TIMER(&_stats->rowset_reader_init_iterators_timer_ns);
339
340
708
    if (_read_context->merged_rows == nullptr) {
341
420
        _read_context->merged_rows = &_merged_rows;
342
420
    }
343
    // merge or union segment iterator
344
708
    if (is_merge_iterator()) {
345
16
        auto sequence_loc = -1;
346
16
        if (_read_context->sequence_id_idx != -1) {
347
0
            for (int loc = 0; loc < _read_context->return_columns->size(); loc++) {
348
0
                if (_read_context->return_columns->at(loc) == _read_context->sequence_id_idx) {
349
0
                    sequence_loc = loc;
350
0
                    break;
351
0
                }
352
0
            }
353
0
        }
354
16
        if (_read_options.binlog_tso_idx != -1) {
355
0
            sequence_loc = _read_options.binlog_tso_idx;
356
0
        }
357
16
        _iterator = new_merge_iterator(std::move(iterators), sequence_loc, _read_context->is_unique,
358
16
                                       _read_context->read_orderby_key_reverse,
359
16
                                       _read_context->merged_rows, _output_schema,
360
16
                                       _read_options.binlog_tso_idx != -1);
361
692
    } else {
362
692
        if (_read_context->read_orderby_key_reverse) {
363
            // reverse iterators to read backward for ORDER BY key DESC
364
0
            std::reverse(iterators.begin(), iterators.end());
365
0
        }
366
692
        _iterator = new_union_iterator(std::move(iterators), _output_schema);
367
692
    }
368
369
708
    auto s = _iterator->init(_read_options);
370
708
    if (!s.ok()) {
371
0
        LOG(WARNING) << "failed to init iterator: " << s.to_string();
372
0
        _iterator.reset();
373
0
        return Status::Error<ROWSET_READER_INIT>(s.to_string());
374
0
    }
375
708
    return Status::OK();
376
708
}
377
378
2.79k
bool BetaRowsetReader::_should_push_down_value_predicates() const {
379
    // if unique table with rowset [0-x] or [0-1] [2-y] [...],
380
    // value column predicates can be pushdown on rowset [0-x] or [2-y], [2-y]
381
    // must be compaction, not overlapping and don't have sequence column
382
2.79k
    return _rowset->keys_type() == UNIQUE_KEYS &&
383
2.79k
           (((_rowset->start_version() == 0 || _rowset->start_version() == 2) &&
384
1.34k
             !_rowset->_rowset_meta->is_segments_overlapping() &&
385
1.34k
             _read_context->sequence_id_idx == -1) ||
386
1.34k
            _read_context->enable_unique_key_merge_on_write ||
387
1.34k
            _read_context->enable_mor_value_predicate_pushdown);
388
2.79k
}
389
} // namespace doris