Coverage Report

Created: 2026-09-14 02:39

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<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,
70
                     const segment_v2::ColumnIteratorOptions& column_iter_opts)
71
4.51k
            : _index_iterators(index_iterators),
72
4.51k
              _storage_name_and_type(storage_name_and_type_vec),
73
4.51k
              _expr_index_status(common_expr_index_status),
74
4.51k
              _score_runtime(std::move(score_runtime)),
75
4.51k
              _segment(segment),
76
4.51k
              _column_iter_opts(column_iter_opts) {}
77
78
41
    segment_v2::IndexIterator* get_inverted_index_iterator(int32_t read_ordinal) const {
79
41
        if (read_ordinal < 0 || static_cast<size_t>(read_ordinal) >= _index_iterators.size()) {
80
0
            return nullptr;
81
0
        }
82
41
        const auto& iterator = _index_iterators[read_ordinal];
83
41
        if (!iterator) {
84
6
            return nullptr;
85
6
        }
86
35
        return iterator.get();
87
41
    }
88
89
35
    const IndexFieldNameAndTypePair* get_storage_name_and_type(int32_t read_ordinal) const {
90
35
        if (read_ordinal < 0 ||
91
35
            static_cast<size_t>(read_ordinal) >= _storage_name_and_type.size()) {
92
1
            return nullptr;
93
1
        }
94
34
        return &_storage_name_and_type[read_ordinal];
95
35
    }
96
97
0
    segment_v2::Segment* segment() const { return _segment; }
98
99
0
    const segment_v2::ColumnIteratorOptions& column_iter_opts() const { return _column_iter_opts; }
100
101
60
    bool has_index_result_for_expr(const VExpr* expr) const {
102
60
        return _index_result_bitmap.contains(expr);
103
60
    }
104
105
    void set_index_result_for_expr(const VExpr* expr,
106
30
                                   segment_v2::InvertedIndexResultBitmap bitmap) {
107
30
        _index_result_bitmap[expr] = std::move(bitmap);
108
30
    }
109
110
    std::unordered_map<const VExpr*, segment_v2::InvertedIndexResultBitmap>&
111
8
    get_index_result_bitmap() {
112
8
        return _index_result_bitmap;
113
8
    }
114
115
25
    std::unordered_map<const VExpr*, ColumnPtr>& get_index_result_column() {
116
25
        return _index_result_column;
117
25
    }
118
119
28
    const segment_v2::InvertedIndexResultBitmap* get_index_result_for_expr(const VExpr* expr) {
120
28
        auto iter = _index_result_bitmap.find(expr);
121
28
        if (iter == _index_result_bitmap.end()) {
122
1
            return nullptr;
123
1
        }
124
27
        return &iter->second;
125
28
    }
126
127
    // Dedicated entry point for approximate (superset) index results, kept strictly apart from
128
    // the exact result map above.
129
    void set_approx_index_result_for_expr(const VExpr* expr,
130
22
                                          segment_v2::InvertedIndexResultBitmap bitmap) {
131
22
        _approx_index_result_bitmap[expr] = std::move(bitmap);
132
22
    }
133
134
    const segment_v2::InvertedIndexResultBitmap* get_approx_index_result_for_expr(
135
31
            const VExpr* expr) const {
136
31
        auto iter = _approx_index_result_bitmap.find(expr);
137
31
        if (iter == _approx_index_result_bitmap.end()) {
138
10
            return nullptr;
139
10
        }
140
21
        return &iter->second;
141
31
    }
142
143
1
    void set_index_result_column_for_expr(const VExpr* expr, ColumnPtr column) {
144
1
        _index_result_column[expr] = std::move(column);
145
1
    }
146
147
16
    void set_true_for_index_status(const VExpr* expr, int32_t read_ordinal) {
148
16
        if (_expr_index_status.contains(read_ordinal)) {
149
16
            if (_expr_index_status[read_ordinal].contains(expr)) {
150
16
                _expr_index_status[read_ordinal][expr] = true;
151
16
            }
152
16
        }
153
16
    }
154
155
0
    ScoreRuntimeSPtr get_score_runtime() const { return _score_runtime; }
156
157
0
    void set_analyzer_ctx_for_expr(const VExpr* expr, InvertedIndexAnalyzerCtxSPtr analyzer_ctx) {
158
0
        if (expr == nullptr || analyzer_ctx == nullptr) {
159
0
            return;
160
0
        }
161
0
        _expr_analyzer_ctx[expr] = std::move(analyzer_ctx);
162
0
    }
163
164
30
    const InvertedIndexAnalyzerCtx* get_analyzer_ctx_for_expr(const VExpr* expr) const {
165
30
        auto iter = _expr_analyzer_ctx.find(expr);
166
30
        if (iter == _expr_analyzer_ctx.end()) {
167
30
            return nullptr;
168
30
        }
169
0
        return iter->second.get();
170
30
    }
171
172
4.46k
    void set_index_query_context(segment_v2::IndexQueryContextPtr index_query_context) {
173
4.46k
        _index_query_context = index_query_context;
174
4.46k
    }
175
176
8
    const segment_v2::IndexQueryContextPtr& get_index_query_context() const {
177
8
        return _index_query_context;
178
8
    }
179
180
private:
181
    // A reference to a vector of unique pointers to index iterators.
182
    const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& _index_iterators;
183
184
    // A reference to a vector of storage name and type pairs related to schema.
185
    const std::vector<IndexFieldNameAndTypePair>& _storage_name_and_type;
186
187
    // A map of expressions to their corresponding inverted index result bitmaps.
188
    std::unordered_map<const VExpr*, segment_v2::InvertedIndexResultBitmap> _index_result_bitmap;
189
190
    // A map of expressions to their corresponding result columns.
191
    std::unordered_map<const VExpr*, ColumnPtr> _index_result_column;
192
193
    // Approximate (superset) index results: rows outside the bitmap certainly do not match, but
194
    // rows inside it may not match either, so it may only be used to prune candidate rows and
195
    // the expression must stay in the push-down list to re-verify them. Three invariants:
196
    // (a) never write into _index_result_bitmap / _index_result_column -- VExpr::fast_execute
197
    //     would then pass the candidate bitmap off as the function result, and
198
    //     _output_index_result_column would materialize it as a result column;
199
    // (b) never call set_true_for_index_status -- the column would then be judged
200
    //     need_read_data=false and there would be no column left to read during re-verification;
201
    // (c) intersecting with _row_bitmap is allowed only when the expression happens to be the
202
    //     root of the VExprContext (a top-level AND context); wrapped in NOT/OR, VCompoundPred
203
    //     never sees this map, so it simply does not apply.
204
    std::unordered_map<const VExpr*, segment_v2::InvertedIndexResultBitmap>
205
            _approx_index_result_bitmap;
206
207
    // Per-expression analyzer context for inverted index evaluation.
208
    std::unordered_map<const VExpr*, InvertedIndexAnalyzerCtxSPtr> _expr_analyzer_ctx;
209
210
    // A reference to a map of common expressions to their inverted index evaluation status.
211
    std::unordered_map<ColumnId, std::unordered_map<const VExpr*, bool>>& _expr_index_status;
212
213
    ScoreRuntimeSPtr _score_runtime;
214
215
    segment_v2::Segment* _segment = nullptr; // Ref
216
    segment_v2::ColumnIteratorOptions _column_iter_opts;
217
    segment_v2::IndexQueryContextPtr _index_query_context;
218
};
219
220
class VExprContext {
221
    ENABLE_FACTORY_CREATOR(VExprContext);
222
223
public:
224
    VExprContext(VExprSPtr expr);
225
    ~VExprContext();
226
    [[nodiscard]] Status prepare(RuntimeState* state, const RowDescriptor& row_desc);
227
    [[nodiscard]] Status open(RuntimeState* state);
228
    [[nodiscard]] Status clone(RuntimeState* state, VExprContextSPtr& new_ctx);
229
    [[nodiscard]] Status execute(Block* block, int* result_column_id);
230
    [[nodiscard]] Status execute(const Block* block, ColumnPtr& result_column);
231
    [[nodiscard]] Status execute(const Block* block, ColumnWithTypeAndName& result_data);
232
    [[nodiscard]] DataTypePtr execute_type(const Block* block);
233
    [[nodiscard]] const std::string& expr_name() const;
234
    [[nodiscard]] bool is_blockable() const;
235
236
    [[nodiscard]] Status execute_const_expr(ColumnWithTypeAndName& result);
237
238
    double execute_cost() const;
239
240
729k
    VExprSPtr root() { return _root; }
241
0
    void set_root(const VExprSPtr& expr) { _root = expr; }
242
74
    void set_index_context(std::shared_ptr<IndexExecContext> index_context) {
243
74
        _index_context = std::move(index_context);
244
74
    }
245
246
387
    std::shared_ptr<IndexExecContext> get_index_context() const { return _index_context; }
247
248
    LambdaExecutionContext& lambda_execution_context();
249
250
    /// Creates a FunctionContext, and returns the index that's passed to fn_context() to
251
    /// retrieve the created context. Exprs that need a FunctionContext should call this in
252
    /// Prepare() and save the returned index. 'varargs_buffer_size', if specified, is the
253
    /// size of the varargs buffer in the created FunctionContext (see udf-internal.h).
254
    int register_function_context(RuntimeState* state, const DataTypePtr& return_type,
255
                                  const std::vector<DataTypePtr>& arg_types);
256
257
    /// Retrieves a registered FunctionContext. 'i' is the index returned by the call to
258
    /// register_function_context(). This should only be called by VExprs.
259
1.19k
    FunctionContext* fn_context(int i) {
260
1.19k
        if (i < 0 || i >= _fn_contexts.size()) {
261
2
            throw Exception(ErrorCode::INTERNAL_ERROR,
262
2
                            "fn_context index invalid, index={}, _fn_contexts.size()={}", i,
263
2
                            _fn_contexts.size());
264
2
        }
265
1.19k
        return _fn_contexts[i].get();
266
1.19k
    }
267
268
2
    void set_auto_partition_boundary_context() {
269
2
        for (auto& fn_context : _fn_contexts) {
270
0
            fn_context->set_auto_partition_boundary_context();
271
0
        }
272
2
    }
273
274
    // execute expr with inverted index which column a, b has inverted indexes
275
    //  but some situation although column b has indexes, but apply index is not useful, we should
276
    //  skip this expr, just do not apply index anymore.
277
    [[nodiscard]] Status evaluate_inverted_index(uint32_t segment_num_rows);
278
279
    // The one expression whose approximate (superset) index result this caller will read back,
280
    // or null when it reads none. SegmentIterator names the root of a pushed-down conjunct,
281
    // because _apply_approx_index_result looks the result up by exactly that pointer; its
282
    // virtual column loop names nothing, because it only materializes exact results. For any
283
    // other expression -- an operand of a compound predicate, a nested child push-down -- the
284
    // result would be stored under its own pointer and never read again, so a function that can
285
    // only answer approximately skips the evaluation instead of paying for the index reads.
286
50
    void set_approx_index_result_consumer(const VExpr* expr) {
287
50
        _approx_index_result_consumer = expr;
288
50
    }
289
20
    const VExpr* approx_index_result_consumer() const { return _approx_index_result_consumer; }
290
291
    [[nodiscard]] static ZoneMapFilterResult evaluate_zonemap_filter(
292
            const VExprContextSPtrs& conjuncts, const ZoneMapEvalContext& ctx);
293
    [[nodiscard]] static ZoneMapFilterResult evaluate_dictionary_filter(
294
            const VExprContextSPtrs& conjuncts, const DictionaryEvalContext& ctx);
295
    [[nodiscard]] static ZoneMapFilterResult evaluate_bloom_filter(
296
            const VExprContextSPtrs& conjuncts, const BloomFilterEvalContext& ctx);
297
298
    bool all_expr_inverted_index_evaluated();
299
300
    Status execute_filter(const Block* block, uint8_t* __restrict result_filter_data, size_t rows,
301
                          bool accept_null, bool* can_filter_all);
302
303
    [[nodiscard]] static Status filter_block(VExprContext* vexpr_ctx, Block* block);
304
305
    [[nodiscard]] static Status filter_block(const VExprContextSPtrs& expr_contexts, Block* block,
306
                                             size_t column_to_keep);
307
308
    [[nodiscard]] static Status execute_conjuncts(const VExprContextSPtrs& ctxs,
309
                                                  const std::vector<IColumn::Filter*>* filters,
310
                                                  bool accept_null, const Block* block,
311
                                                  IColumn::Filter* result_filter,
312
                                                  bool* can_filter_all);
313
314
    [[nodiscard]] static Status execute_conjuncts(const VExprContextSPtrs& conjuncts,
315
                                                  const Block* block, ColumnUInt8& null_map,
316
                                                  IColumn::Filter& result_filter);
317
318
    static Status execute_conjuncts(const VExprContextSPtrs& ctxs,
319
                                    const std::vector<IColumn::Filter*>* filters, Block* block,
320
                                    IColumn::Filter* result_filter, bool* can_filter_all);
321
322
    [[nodiscard]] static Status execute_conjuncts_and_filter_block(
323
            const VExprContextSPtrs& ctxs, Block* block, std::vector<uint32_t>& columns_to_filter,
324
            int column_to_keep);
325
326
    static Status execute_conjuncts_and_filter_block(const VExprContextSPtrs& ctxs, Block* block,
327
                                                     std::vector<uint32_t>& columns_to_filter,
328
                                                     int column_to_keep, IColumn::Filter& filter);
329
330
    [[nodiscard]] static Status get_output_block_after_execute_exprs(const VExprContextSPtrs&,
331
                                                                     const Block&, Block*,
332
                                                                     bool do_projection = false);
333
334
7
    int get_last_result_column_id() const {
335
7
        DCHECK(_last_result_column_id != -1);
336
7
        return _last_result_column_id;
337
7
    }
338
339
60
    RuntimeFilterSelectivity& get_runtime_filter_selectivity() {
340
60
        if (!_rf_selectivity) {
341
0
            throw Exception(ErrorCode::INTERNAL_ERROR, "RuntimeFilterSelectivity is null");
342
0
        }
343
60
        return *_rf_selectivity;
344
60
    }
345
346
0
    FunctionContext::FunctionStateScope get_function_state_scope() const {
347
0
        return _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
348
0
    }
349
350
    void clone_fn_contexts(VExprContext* other);
351
352
    VExprContext& operator=(const VExprContext& other) = delete;
353
354
    VExprContext& operator=(VExprContext&& other) = delete;
355
356
140
    [[nodiscard]] static size_t get_memory_usage(const VExprContextSPtrs& contexts) {
357
140
        size_t usage = 0;
358
140
        std::for_each(contexts.cbegin(), contexts.cend(),
359
140
                      [&usage](auto&& context) { usage += context->_memory_usage; });
360
140
        return usage;
361
140
    }
362
363
0
    [[nodiscard]] size_t get_memory_usage() const { return _memory_usage; }
364
365
    void prepare_ann_range_search(const doris::VectorSearchUserParams& params);
366
367
    Status evaluate_ann_range_search(
368
            const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& index_iterators,
369
            const std::vector<std::unique_ptr<segment_v2::ColumnIterator>>& column_iterators,
370
            const std::unordered_map<VExprContext*, std::unordered_map<ColumnId, VExpr*>>&
371
                    common_expr_to_slotref_map,
372
            size_t rows_of_segment, roaring::Roaring& row_bitmap,
373
            segment_v2::AnnIndexStats& ann_index_stats, bool enable_result_cache,
374
            bool* ann_range_search_executed);
375
376
    uint64_t get_digest(uint64_t seed) const;
377
378
private:
379
    // Close method is called in vexpr context dector, not need call expicility
380
    void close();
381
382
    static void _reset_memory_usage(const VExprContextSPtrs& contexts);
383
384
    friend class VExpr;
385
386
    /// The expr tree this context is for.
387
    VExprSPtr _root;
388
389
    /// True if this context came from a Clone() call. Used to manage FunctionStateScope.
390
    bool _is_clone = false;
391
392
    /// Variables keeping track of current state.
393
    bool _prepared = false;
394
    bool _opened = false;
395
396
    /// See set_approx_index_result_consumer. Null by default, so a caller that does not read the
397
    /// approximate map never pays for the index reads behind one.
398
    const VExpr* _approx_index_result_consumer = nullptr;
399
400
    /// FunctionContexts for each registered expression. The FunctionContexts are created
401
    /// and owned by this VExprContext.
402
    std::vector<std::unique_ptr<FunctionContext>> _fn_contexts;
403
404
    int _last_result_column_id = -1;
405
406
    /// The depth of expression-tree.
407
    int _depth_num = 0;
408
409
    std::shared_ptr<IndexExecContext> _index_context;
410
    size_t _memory_usage = 0;
411
412
    segment_v2::AnnRangeSearchRuntime _ann_range_search_runtime;
413
    bool _suitable_for_ann_index = true;
414
415
    std::unique_ptr<LambdaExecutionContext> _lambda_execution_context;
416
417
    std::unique_ptr<RuntimeFilterSelectivity> _rf_selectivity =
418
            std::make_unique<RuntimeFilterSelectivity>();
419
};
420
} // namespace doris