Coverage Report

Created: 2026-11-05 16:04

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