Coverage Report

Created: 2026-09-29 02:27

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