Coverage Report

Created: 2026-07-17 19:45

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