Coverage Report

Created: 2026-11-03 18:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/exprs/vtopn_pred.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 <gen_cpp/types.pb.h>
21
22
#include <utility>
23
24
#include "core/block/column_numbers.h"
25
#include "core/data_type/data_type.h"
26
#include "exec/common/util.hpp"
27
#include "exprs/function/simple_function_factory.h"
28
#include "exprs/vectorized_fn_call.h"
29
#include "exprs/vexpr.h"
30
#include "exprs/vslot_ref.h"
31
#include "runtime/query_context.h"
32
#include "runtime/runtime_predicate.h"
33
#include "runtime/runtime_state.h"
34
35
namespace doris {
36
#include "common/compile_check_begin.h"
37
38
// only used for dynamic topn filter
39
class VTopNPred : public VExpr {
40
    ENABLE_FACTORY_CREATOR(VTopNPred);
41
42
public:
43
    VTopNPred(const TExprNode& node, int source_node_id, VExprContextSPtr target_ctx)
44
130
            : VExpr(node),
45
130
              _source_node_id(source_node_id),
46
130
              _expr_name(fmt::format("VTopNPred(source_node_id={})", _source_node_id)),
47
130
              _target_ctx(std::move(target_ctx)) {}
48
34
    bool is_topn_filter() const override { return true; }
49
50
0
    static Status create_vtopn_pred(const TExpr& target_expr, int source_node_id, VExprSPtr& expr) {
51
0
        VExprContextSPtr target_ctx;
52
0
        RETURN_IF_ERROR(VExpr::create_expr_tree(target_expr, target_ctx));
53
54
0
        TExprNode node;
55
0
        node.__set_node_type(TExprNodeType::FUNCTION_CALL);
56
0
        node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
57
0
        node.__set_is_nullable(target_ctx->root()->is_nullable());
58
0
        expr = VTopNPred::create_shared(node, source_node_id, target_ctx);
59
60
0
        DCHECK(target_ctx->root() != nullptr);
61
0
        expr->add_child(target_ctx->root());
62
63
0
        return Status::OK();
64
0
    }
65
66
0
    int source_node_id() const { return _source_node_id; }
67
262
    bool is_asc() const { return _predicate->is_asc(); }
68
155
    bool nulls_first() const { return _predicate->nulls_first(); }
69
70
    bool can_evaluate_zonemap_filter() const override;
71
    ZoneMapFilterResult evaluate_zonemap_filter(const ZoneMapEvalContext& ctx) const override;
72
73
48
    Status clone_node(VExprSPtr* cloned_expr) const override {
74
48
        DORIS_CHECK(cloned_expr != nullptr);
75
48
        *cloned_expr = VTopNPred::create_shared(clone_texpr_node(), _source_node_id, nullptr);
76
48
        return Status::OK();
77
48
    }
78
79
106
    Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override {
80
106
        _predicate = &state->get_query_ctx()->get_runtime_predicate(_source_node_id);
81
106
        RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
82
83
106
        ColumnsWithTypeAndName argument_template;
84
106
        argument_template.emplace_back(nullptr, _children[0]->data_type(),
85
106
                                       _children[0]->expr_name());
86
106
        argument_template.emplace_back(nullptr, _children[0]->data_type(), "topn value");
87
88
106
        _function = SimpleFunctionFactory::instance().get_function(
89
106
                _predicate->is_asc() ? "le" : "ge", argument_template, _data_type, {},
90
106
                state->be_exec_version());
91
106
        if (!_function) {
92
0
            return Status::InternalError("get function failed");
93
0
        }
94
106
        return Status::OK();
95
106
    }
96
97
    Status execute_column_impl(VExprContext* context, const Block* block, const Selector* selector,
98
47
                               size_t count, ColumnPtr& result_column) const override {
99
47
        if (!_predicate->has_value()) {
100
41
            result_column = create_always_true_column(count, _data_type->is_nullable());
101
41
            return Status::OK();
102
41
        }
103
104
6
        Block temp_block;
105
106
        // slot
107
6
        ColumnPtr slot_column;
108
6
        RETURN_IF_ERROR(_children[0]->execute_column(context, block, selector, count, slot_column));
109
6
        auto slot_type = _children[0]->execute_type(block);
110
6
        temp_block.insert({slot_column, slot_type, _children[0]->expr_name()});
111
6
        int slot_id = 0;
112
113
        // topn value
114
6
        Field field = _predicate->get_value();
115
6
        auto column_ptr = _children[0]->data_type()->create_column_const(1, field);
116
6
        int topn_value_id = VExpr::insert_param(&temp_block,
117
6
                                                {column_ptr, _children[0]->data_type(), _expr_name},
118
6
                                                std::max(count, column_ptr->size()));
119
120
        // if error(slot_id == -1), will return.
121
6
        ColumnNumbers arguments = {static_cast<uint32_t>(slot_id),
122
6
                                   static_cast<uint32_t>(topn_value_id)};
123
124
6
        uint32_t num_columns_without_result = temp_block.columns();
125
        // prepare a column to save result
126
6
        temp_block.insert({nullptr, _data_type, _expr_name});
127
128
6
        RETURN_IF_ERROR(_function->execute(nullptr, temp_block, arguments,
129
6
                                           num_columns_without_result, temp_block.rows()));
130
6
        result_column = std::move(temp_block.get_by_position(num_columns_without_result).column);
131
6
        if (is_nullable() && _predicate->nulls_first()) {
132
            // null values ​​are always not filtered
133
0
            change_null_to_true(result_column);
134
0
        }
135
6
        DCHECK_EQ(result_column->size(), count);
136
6
        return Status::OK();
137
6
    }
138
139
    // Returns true only for a direct slot binding whose logical fixed-width type exactly matches
140
    // `data_type`. Eligibility does not depend on whether the dynamic TopN bound has arrived: a
141
    // reader may cache this answer during initialization and observe the bound in a later batch.
142
    bool can_execute_on_raw_fixed_values(const DataTypePtr& data_type,
143
                                         int column_id) const override;
144
145
    // Compares the contiguous non-NULL physical values with one snapshot of the current TopN bound
146
    // and ANDs the result into `matches`. `value_width` must equal the logical Doris value width.
147
    // When no bound is available yet, this is deliberately an all-pass operation.
148
    Status execute_on_raw_fixed_values(const uint8_t* values, size_t num_values, size_t value_width,
149
                                       const DataTypePtr& data_type, int column_id,
150
                                       uint8_t* matches) const override;
151
152
    // Returns true for a directly bound STRING-like or VARBINARY slot. As with the fixed-width
153
    // capability, a not-yet-published bound does not force the scanner onto a materializing path.
154
    bool can_execute_on_raw_binary_values(const DataTypePtr& data_type,
155
                                          int column_id) const override;
156
157
    // Compares decoder-owned immutable byte slices with the current TopN bound and ANDs each
158
    // decision into `matches`; it never copies the slices into a ColumnString/ColumnVarbinary.
159
    Status execute_on_raw_binary_values(const StringRef* values, size_t num_values,
160
                                        const DataTypePtr& data_type, int column_id,
161
                                        uint8_t* matches) const override;
162
163
205
    bool raw_predicate_result_for_null() const override {
164
        // execute_column() is all-pass until publication; afterwards NULLS FIRST keeps NULL while
165
        // NULLS LAST rejects it. Sample this state per fragment just like the mutable bound.
166
205
        return _predicate != nullptr && (!_predicate->has_value() || _predicate->nulls_first());
167
205
    }
168
169
    // Dictionary capability is restricted to a direct slot and NULLS-LAST semantics. It stays
170
    // enabled before the first bound so row-group setup can cache an all-pass bitmap; the scan
171
    // scheduler retains a per-batch residual and defers dictionary-id filtering while NULL still
172
    // matches, then safely resumes it after bound publication.
173
    bool can_evaluate_dictionary_filter() const override;
174
175
    // Evaluates every non-NULL entry in the bound slot dictionary against one current-bound
176
    // snapshot. kNoMatch proves that no entry can pass; kMayMatch includes both a matching entry and
177
    // a not-yet-published bound; kUnsupported reports an absent or incompatible dictionary slot.
178
    ZoneMapFilterResult evaluate_dictionary_filter(const DictionaryEvalContext& ctx) const override;
179
180
0
    const std::string& expr_name() const override { return _expr_name; }
181
182
    // only used in external table (for min-max filter). get `slot > xxx`, not `function(slot) > xxx`.
183
0
    bool get_binary_expr(VExprSPtr& new_root) const {
184
0
        if (!get_child(0)->is_slot_ref()) {
185
            // top rf maybe is `xxx order by abs(column) limit xxx`.
186
0
            return false;
187
0
        }
188
189
0
        if (!_predicate->has_value()) {
190
0
            return false;
191
0
        }
192
193
0
        auto* slot_ref = assert_cast<VSlotRef*>(get_child(0).get());
194
0
        auto slot_data_type = remove_nullable(slot_ref->data_type());
195
0
        {
196
0
            TFunction fn;
197
0
            TFunctionName fn_name;
198
0
            fn_name.__set_db_name("");
199
0
            fn_name.__set_function_name(_predicate->is_asc() ? "le" : "ge");
200
0
            fn.__set_name(fn_name);
201
0
            fn.__set_binary_type(TFunctionBinaryType::BUILTIN);
202
0
            std::vector<TTypeDesc> arg_types;
203
0
            arg_types.push_back(create_type_desc(slot_data_type->get_primitive_type(),
204
0
                                                 slot_data_type->get_precision(),
205
0
                                                 slot_data_type->get_scale()));
206
207
0
            arg_types.push_back(create_type_desc(slot_data_type->get_primitive_type(),
208
0
                                                 slot_data_type->get_precision(),
209
0
                                                 slot_data_type->get_scale()));
210
0
            fn.__set_arg_types(arg_types);
211
0
            fn.__set_ret_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
212
0
            fn.__set_has_var_args(false);
213
214
0
            TExprNode texpr_node;
215
0
            texpr_node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
216
0
            texpr_node.__set_node_type(TExprNodeType::BINARY_PRED);
217
0
            texpr_node.__set_opcode(_predicate->is_asc() ? TExprOpcode::LE : TExprOpcode::GE);
218
0
            texpr_node.__set_fn(fn);
219
0
            texpr_node.__set_num_children(2);
220
0
            texpr_node.__set_is_nullable(is_nullable());
221
0
            new_root = VectorizedFnCall::create_shared(texpr_node);
222
0
        }
223
224
0
        {
225
            // add slot
226
0
            new_root->add_child(children().at(0));
227
0
        }
228
        // add Literal
229
0
        {
230
0
            Field field = _predicate->get_value();
231
0
            TExprNode node = create_texpr_node_from(field, slot_data_type->get_primitive_type(),
232
0
                                                    slot_data_type->get_precision(),
233
0
                                                    slot_data_type->get_scale());
234
0
            new_root->add_child(VLiteral::create_shared(node));
235
0
        }
236
237
        // Since the normal greater than or less than relationship does not consider the relationship of null values, the generated `col >=/<= xxx OR col is null.`
238
0
        if (_predicate->nulls_first()) {
239
0
            VExprSPtr col_is_null_node;
240
0
            {
241
0
                TFunction fn;
242
0
                TFunctionName fn_name;
243
0
                fn_name.__set_db_name("");
244
0
                fn_name.__set_function_name("is_null_pred");
245
0
                fn.__set_name(fn_name);
246
0
                fn.__set_binary_type(TFunctionBinaryType::BUILTIN);
247
0
                std::vector<TTypeDesc> arg_types;
248
0
                arg_types.push_back(create_type_desc(slot_data_type->get_primitive_type(),
249
0
                                                     slot_data_type->get_precision(),
250
0
                                                     slot_data_type->get_scale()));
251
0
                fn.__set_arg_types(arg_types);
252
0
                fn.__set_ret_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
253
0
                fn.__set_has_var_args(false);
254
255
0
                TExprNode texpr_node;
256
0
                texpr_node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
257
0
                texpr_node.__set_node_type(TExprNodeType::FUNCTION_CALL);
258
0
                texpr_node.__set_fn(fn);
259
0
                texpr_node.__set_num_children(1);
260
0
                col_is_null_node = VectorizedFnCall::create_shared(texpr_node);
261
262
                // add slot.
263
0
                col_is_null_node->add_child(children().at(0));
264
0
            }
265
266
0
            VExprSPtr or_node;
267
0
            {
268
0
                TExprNode texpr_node;
269
0
                texpr_node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
270
0
                texpr_node.__set_node_type(TExprNodeType::COMPOUND_PRED);
271
0
                texpr_node.__set_opcode(TExprOpcode::COMPOUND_OR);
272
0
                texpr_node.__set_num_children(2);
273
0
                or_node = VectorizedFnCall::create_shared(texpr_node);
274
0
            }
275
276
0
            or_node->add_child(col_is_null_node);
277
0
            or_node->add_child(new_root);
278
0
            new_root = or_node;
279
0
        }
280
281
0
        return true;
282
0
    }
283
284
private:
285
    int _source_node_id;
286
    std::string _expr_name;
287
    RuntimePredicate* _predicate = nullptr;
288
    FunctionBasePtr _function;
289
    VExprContextSPtr _target_ctx;
290
};
291
292
#include "common/compile_check_end.h"
293
} // namespace doris