Coverage Report

Created: 2026-08-14 08:30

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