Coverage Report

Created: 2026-08-05 13:32

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