Coverage Report

Created: 2026-07-15 04:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/exprs/vexpr_context.h
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
#pragma once
19
20
#include <glog/logging.h>
21
22
#include <algorithm>
23
#include <cstddef>
24
#include <memory>
25
#include <unordered_map>
26
#include <utility>
27
#include <vector>
28
29
#include "common/factory_creator.h"
30
#include "common/status.h"
31
#include "core/block/block.h"
32
#include "core/block/column_with_type_and_name.h"
33
#include "core/column/column.h"
34
#include "exec/runtime_filter/runtime_filter_selectivity.h"
35
#include "exprs/expr_zonemap_filter.h"
36
#include "exprs/function_context.h"
37
#include "exprs/vexpr_fwd.h"
38
#include "runtime/runtime_state.h"
39
#include "storage/index/ann/ann_range_search_runtime.h"
40
#include "storage/index/ann/ann_search_params.h"
41
#include "storage/index/inverted/inverted_index_reader.h"
42
#include "storage/index/zone_map/zonemap_filter_result.h"
43
#include "storage/segment/column_reader.h"
44
45
namespace doris {
46
class RowDescriptor;
47
class RuntimeState;
48
class ZoneMapEvalContext;
49
} // namespace doris
50
51
namespace doris::segment_v2 {
52
class Segment;
53
class ColumnIterator;
54
class Segment;
55
} // namespace doris::segment_v2
56
57
namespace doris {
58
59
class ScoreRuntime;
60
using ScoreRuntimeSPtr = std::shared_ptr<ScoreRuntime>;
61
62
class IndexExecContext {
63
public:
64
    IndexExecContext(const std::vector<ColumnId>& col_ids,
65
                     const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& index_iterators,
66
                     const std::vector<IndexFieldNameAndTypePair>& storage_name_and_type_vec,
67
                     std::unordered_map<ColumnId, std::unordered_map<const VExpr*, bool>>&
68
                             common_expr_index_status,
69
                     ScoreRuntimeSPtr score_runtime, segment_v2::Segment* segment = nullptr,
70
                     const segment_v2::ColumnIteratorOptions& column_iter_opts = {})
71
3.06k
            : _col_ids(col_ids),
72
3.06k
              _index_iterators(index_iterators),
73
3.06k
              _storage_name_and_type(storage_name_and_type_vec),
74
3.06k
              _expr_index_status(common_expr_index_status),
75
3.06k
              _score_runtime(std::move(score_runtime)),
76
3.06k
              _segment(segment),
77
3.06k
              _column_iter_opts(column_iter_opts) {}
78
79
21
    segment_v2::IndexIterator* get_inverted_index_iterator_by_column_id(int column_index) const {
80
21
        if (column_index < 0 || column_index >= _col_ids.size()) {
81
0
            return nullptr;
82
0
        }
83
21
        const auto& column_id = _col_ids[column_index];
84
21
        if (column_id >= _index_iterators.size()) {
85
0
            return nullptr;
86
0
        }
87
21
        if (!_index_iterators[column_id]) {
88
5
            return nullptr;
89
5
        }
90
16
        return _index_iterators[column_id].get();
91
21
    }
92
93
0
    segment_v2::IndexIterator* get_inverted_index_iterator_by_id(ColumnId column_id) const {
94
0
        if (column_id >= _index_iterators.size()) {
95
0
            return nullptr;
96
0
        }
97
0
        if (!_index_iterators[column_id]) {
98
0
            return nullptr;
99
0
        }
100
0
        return _index_iterators[column_id].get();
101
0
    }
102
103
    const IndexFieldNameAndTypePair* get_storage_name_and_type_by_column_id(
104
17
            int column_index) const {
105
17
        if (column_index < 0 || column_index >= _col_ids.size()) {
106
0
            return nullptr;
107
0
        }
108
17
        const auto& column_id = _col_ids[column_index];
109
17
        if (column_id >= _storage_name_and_type.size()) {
110
2
            return nullptr;
111
2
        }
112
15
        return &_storage_name_and_type[column_id];
113
17
    }
114
115
0
    const IndexFieldNameAndTypePair* get_storage_name_and_type_by_id(ColumnId column_id) const {
116
0
        if (column_id >= _storage_name_and_type.size()) {
117
0
            return nullptr;
118
0
        }
119
0
        return &_storage_name_and_type[column_id];
120
0
    }
121
122
0
    int column_index_by_id(ColumnId column_id) const {
123
0
        for (int i = 0; i < _col_ids.size(); ++i) {
124
0
            if (_col_ids[i] == column_id) {
125
0
                return i;
126
0
            }
127
0
        }
128
0
        return -1;
129
0
    }
130
131
0
    bool get_column_id(int column_index, ColumnId* column_id) const {
132
0
        if (column_id == nullptr) {
133
0
            return false;
134
0
        }
135
0
        if (column_index < 0 || column_index >= _col_ids.size()) {
136
0
            return false;
137
0
        }
138
0
        *column_id = _col_ids[column_index];
139
0
        return true;
140
0
    }
141
142
0
    segment_v2::Segment* segment() const { return _segment; }
143
144
0
    const segment_v2::ColumnIteratorOptions& column_iter_opts() const { return _column_iter_opts; }
145
146
20
    bool has_index_result_for_expr(const VExpr* expr) const {
147
20
        return _index_result_bitmap.contains(expr);
148
20
    }
149
150
    void set_index_result_for_expr(const VExpr* expr,
151
19
                                   segment_v2::InvertedIndexResultBitmap bitmap) {
152
19
        _index_result_bitmap[expr] = std::move(bitmap);
153
19
    }
154
155
    std::unordered_map<const VExpr*, segment_v2::InvertedIndexResultBitmap>&
156
6
    get_index_result_bitmap() {
157
6
        return _index_result_bitmap;
158
6
    }
159
160
8
    std::unordered_map<const VExpr*, ColumnPtr>& get_index_result_column() {
161
8
        return _index_result_column;
162
8
    }
163
164
16
    const segment_v2::InvertedIndexResultBitmap* get_index_result_for_expr(const VExpr* expr) {
165
16
        auto iter = _index_result_bitmap.find(expr);
166
16
        if (iter == _index_result_bitmap.end()) {
167
0
            return nullptr;
168
0
        }
169
16
        return &iter->second;
170
16
    }
171
172
1
    void set_index_result_column_for_expr(const VExpr* expr, ColumnPtr column) {
173
1
        _index_result_column[expr] = std::move(column);
174
1
    }
175
176
15
    void set_true_for_index_status(const VExpr* expr, int column_index) {
177
15
        if (column_index < 0 || column_index >= _col_ids.size()) {
178
0
            return;
179
0
        }
180
15
        const auto& column_id = _col_ids[column_index];
181
15
        if (_expr_index_status.contains(column_id)) {
182
15
            if (_expr_index_status[column_id].contains(expr)) {
183
15
                _expr_index_status[column_id][expr] = true;
184
15
            }
185
15
        }
186
15
    }
187
188
0
    ScoreRuntimeSPtr get_score_runtime() const { return _score_runtime; }
189
190
0
    void set_analyzer_ctx_for_expr(const VExpr* expr, InvertedIndexAnalyzerCtxSPtr analyzer_ctx) {
191
0
        if (expr == nullptr || analyzer_ctx == nullptr) {
192
0
            return;
193
0
        }
194
0
        _expr_analyzer_ctx[expr] = std::move(analyzer_ctx);
195
0
    }
196
197
14
    const InvertedIndexAnalyzerCtx* get_analyzer_ctx_for_expr(const VExpr* expr) const {
198
14
        auto iter = _expr_analyzer_ctx.find(expr);
199
14
        if (iter == _expr_analyzer_ctx.end()) {
200
14
            return nullptr;
201
14
        }
202
0
        return iter->second.get();
203
14
    }
204
205
3.04k
    void set_index_query_context(segment_v2::IndexQueryContextPtr index_query_context) {
206
3.04k
        _index_query_context = index_query_context;
207
3.04k
    }
208
209
3
    const segment_v2::IndexQueryContextPtr& get_index_query_context() const {
210
3
        return _index_query_context;
211
3
    }
212
213
0
    segment_v2::Segment* get_segment() const { return _segment; }
214
215
0
    const segment_v2::ColumnIteratorOptions& get_column_iter_opts() const {
216
0
        return _column_iter_opts;
217
0
    }
218
219
private:
220
    // A reference to a vector of column IDs for the current expression's output columns.
221
    const std::vector<ColumnId>& _col_ids;
222
223
    // A reference to a vector of unique pointers to index iterators.
224
    const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& _index_iterators;
225
226
    // A reference to a vector of storage name and type pairs related to schema.
227
    const std::vector<IndexFieldNameAndTypePair>& _storage_name_and_type;
228
229
    // A map of expressions to their corresponding inverted index result bitmaps.
230
    std::unordered_map<const VExpr*, segment_v2::InvertedIndexResultBitmap> _index_result_bitmap;
231
232
    // A map of expressions to their corresponding result columns.
233
    std::unordered_map<const VExpr*, ColumnPtr> _index_result_column;
234
235
    // Per-expression analyzer context for inverted index evaluation.
236
    std::unordered_map<const VExpr*, InvertedIndexAnalyzerCtxSPtr> _expr_analyzer_ctx;
237
238
    // A reference to a map of common expressions to their inverted index evaluation status.
239
    std::unordered_map<ColumnId, std::unordered_map<const VExpr*, bool>>& _expr_index_status;
240
241
    ScoreRuntimeSPtr _score_runtime;
242
243
    segment_v2::Segment* _segment = nullptr; // Ref
244
    segment_v2::ColumnIteratorOptions _column_iter_opts;
245
    segment_v2::IndexQueryContextPtr _index_query_context;
246
};
247
248
class VExprContext {
249
    ENABLE_FACTORY_CREATOR(VExprContext);
250
251
public:
252
656k
    VExprContext(VExprSPtr expr) : _root(std::move(expr)) {}
253
    ~VExprContext();
254
    [[nodiscard]] Status prepare(RuntimeState* state, const RowDescriptor& row_desc);
255
    [[nodiscard]] Status open(RuntimeState* state);
256
    [[nodiscard]] Status clone(RuntimeState* state, VExprContextSPtr& new_ctx);
257
    [[nodiscard]] Status execute(Block* block, int* result_column_id);
258
    [[nodiscard]] Status execute(const Block* block, ColumnPtr& result_column);
259
    [[nodiscard]] Status execute(const Block* block, ColumnWithTypeAndName& result_data);
260
    [[nodiscard]] DataTypePtr execute_type(const Block* block);
261
    [[nodiscard]] const std::string& expr_name() const;
262
    [[nodiscard]] bool is_blockable() const;
263
264
    [[nodiscard]] Status execute_const_expr(ColumnWithTypeAndName& result);
265
266
    double execute_cost() const;
267
268
723k
    VExprSPtr root() { return _root; }
269
0
    void set_root(const VExprSPtr& expr) { _root = expr; }
270
46
    void set_index_context(std::shared_ptr<IndexExecContext> index_context) {
271
46
        _index_context = std::move(index_context);
272
46
    }
273
274
234
    std::shared_ptr<IndexExecContext> get_index_context() const { return _index_context; }
275
276
    /// Creates a FunctionContext, and returns the index that's passed to fn_context() to
277
    /// retrieve the created context. Exprs that need a FunctionContext should call this in
278
    /// Prepare() and save the returned index. 'varargs_buffer_size', if specified, is the
279
    /// size of the varargs buffer in the created FunctionContext (see udf-internal.h).
280
    int register_function_context(RuntimeState* state, const DataTypePtr& return_type,
281
                                  const std::vector<DataTypePtr>& arg_types);
282
283
    /// Retrieves a registered FunctionContext. 'i' is the index returned by the call to
284
    /// register_function_context(). This should only be called by VExprs.
285
695
    FunctionContext* fn_context(int i) {
286
695
        if (i < 0 || i >= _fn_contexts.size()) {
287
0
            throw Exception(ErrorCode::INTERNAL_ERROR,
288
0
                            "fn_context index invalid, index={}, _fn_contexts.size()={}", i,
289
0
                            _fn_contexts.size());
290
0
        }
291
695
        return _fn_contexts[i].get();
292
695
    }
293
294
    // execute expr with inverted index which column a, b has inverted indexes
295
    //  but some situation although column b has indexes, but apply index is not useful, we should
296
    //  skip this expr, just do not apply index anymore.
297
    [[nodiscard]] Status evaluate_inverted_index(uint32_t segment_num_rows);
298
299
    [[nodiscard]] static ZoneMapFilterResult evaluate_zonemap_filter(
300
            const VExprContextSPtrs& conjuncts, const ZoneMapEvalContext& ctx);
301
    [[nodiscard]] static ZoneMapFilterResult evaluate_dictionary_filter(
302
            const VExprContextSPtrs& conjuncts, const DictionaryEvalContext& ctx);
303
    [[nodiscard]] static ZoneMapFilterResult evaluate_bloom_filter(
304
            const VExprContextSPtrs& conjuncts, const BloomFilterEvalContext& ctx);
305
306
    bool all_expr_inverted_index_evaluated();
307
308
    Status execute_filter(const Block* block, uint8_t* __restrict result_filter_data, size_t rows,
309
                          bool accept_null, bool* can_filter_all);
310
311
    [[nodiscard]] static Status filter_block(VExprContext* vexpr_ctx, Block* block);
312
313
    [[nodiscard]] static Status filter_block(const VExprContextSPtrs& expr_contexts, Block* block,
314
                                             size_t column_to_keep);
315
316
    [[nodiscard]] static Status execute_conjuncts(const VExprContextSPtrs& ctxs,
317
                                                  const std::vector<IColumn::Filter*>* filters,
318
                                                  bool accept_null, const Block* block,
319
                                                  IColumn::Filter* result_filter,
320
                                                  bool* can_filter_all);
321
322
    [[nodiscard]] static Status execute_conjuncts(const VExprContextSPtrs& conjuncts,
323
                                                  const Block* block, ColumnUInt8& null_map,
324
                                                  IColumn::Filter& result_filter);
325
326
    static Status execute_conjuncts(const VExprContextSPtrs& ctxs,
327
                                    const std::vector<IColumn::Filter*>* filters, Block* block,
328
                                    IColumn::Filter* result_filter, bool* can_filter_all);
329
330
    [[nodiscard]] static Status execute_conjuncts_and_filter_block(
331
            const VExprContextSPtrs& ctxs, Block* block, std::vector<uint32_t>& columns_to_filter,
332
            int column_to_keep);
333
334
    static Status execute_conjuncts_and_filter_block(const VExprContextSPtrs& ctxs, Block* block,
335
                                                     std::vector<uint32_t>& columns_to_filter,
336
                                                     int column_to_keep, IColumn::Filter& filter);
337
338
    [[nodiscard]] static Status get_output_block_after_execute_exprs(const VExprContextSPtrs&,
339
                                                                     const Block&, Block*,
340
                                                                     bool do_projection = false);
341
342
6
    int get_last_result_column_id() const {
343
6
        DCHECK(_last_result_column_id != -1);
344
6
        return _last_result_column_id;
345
6
    }
346
347
23
    RuntimeFilterSelectivity& get_runtime_filter_selectivity() {
348
23
        if (!_rf_selectivity) {
349
0
            throw Exception(ErrorCode::INTERNAL_ERROR, "RuntimeFilterSelectivity is null");
350
0
        }
351
23
        return *_rf_selectivity;
352
23
    }
353
354
0
    FunctionContext::FunctionStateScope get_function_state_scope() const {
355
0
        return _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
356
0
    }
357
358
    void clone_fn_contexts(VExprContext* other);
359
360
0
    VExprContext& operator=(const VExprContext& other) {
361
0
        if (this == &other) {
362
0
            return *this;
363
0
        }
364
0
365
0
        _root = other._root;
366
0
        _is_clone = other._is_clone;
367
0
        _prepared = other._prepared;
368
0
        _opened = other._opened;
369
0
370
0
        for (const auto& fn : other._fn_contexts) {
371
0
            _fn_contexts.emplace_back(fn->clone());
372
0
        }
373
0
374
0
        _last_result_column_id = other._last_result_column_id;
375
0
        _depth_num = other._depth_num;
376
0
        return *this;
377
0
    }
378
379
0
    VExprContext& operator=(VExprContext&& other) {
380
0
        _root = other._root;
381
0
        other._root = nullptr;
382
0
        _is_clone = other._is_clone;
383
0
        _prepared = other._prepared;
384
0
        _opened = other._opened;
385
0
        _fn_contexts = std::move(other._fn_contexts);
386
0
        _last_result_column_id = other._last_result_column_id;
387
0
        _depth_num = other._depth_num;
388
0
        return *this;
389
0
    }
390
391
136
    [[nodiscard]] static size_t get_memory_usage(const VExprContextSPtrs& contexts) {
392
136
        size_t usage = 0;
393
136
        std::for_each(contexts.cbegin(), contexts.cend(),
394
136
                      [&usage](auto&& context) { usage += context->_memory_usage; });
395
136
        return usage;
396
136
    }
397
398
0
    [[nodiscard]] size_t get_memory_usage() const { return _memory_usage; }
399
400
    void prepare_ann_range_search(const doris::VectorSearchUserParams& params);
401
402
    Status evaluate_ann_range_search(
403
            const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& cid_to_index_iterators,
404
            const std::vector<ColumnId>& idx_to_cid,
405
            const std::vector<std::unique_ptr<segment_v2::ColumnIterator>>& column_iterators,
406
            const std::unordered_map<VExprContext*, std::unordered_map<ColumnId, VExpr*>>&
407
                    common_expr_to_slotref_map,
408
            size_t rows_of_segment, roaring::Roaring& row_bitmap,
409
            segment_v2::AnnIndexStats& ann_index_stats, bool* ann_range_search_executed);
410
411
    uint64_t get_digest(uint64_t seed) const;
412
413
private:
414
    // Close method is called in vexpr context dector, not need call expicility
415
    void close();
416
417
    static void _reset_memory_usage(const VExprContextSPtrs& contexts);
418
419
    friend class VExpr;
420
421
    /// The expr tree this context is for.
422
    VExprSPtr _root;
423
424
    /// True if this context came from a Clone() call. Used to manage FunctionStateScope.
425
    bool _is_clone = false;
426
427
    /// Variables keeping track of current state.
428
    bool _prepared = false;
429
    bool _opened = false;
430
431
    /// FunctionContexts for each registered expression. The FunctionContexts are created
432
    /// and owned by this VExprContext.
433
    std::vector<std::unique_ptr<FunctionContext>> _fn_contexts;
434
435
    int _last_result_column_id = -1;
436
437
    /// The depth of expression-tree.
438
    int _depth_num = 0;
439
440
    std::shared_ptr<IndexExecContext> _index_context;
441
    size_t _memory_usage = 0;
442
443
    segment_v2::AnnRangeSearchRuntime _ann_range_search_runtime;
444
    bool _suitable_for_ann_index = true;
445
446
    std::unique_ptr<RuntimeFilterSelectivity> _rf_selectivity =
447
            std::make_unique<RuntimeFilterSelectivity>();
448
};
449
} // namespace doris