Coverage Report

Created: 2026-07-05 02:38

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