Coverage Report

Created: 2026-10-16 01:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/exprs/vin_predicate.cpp
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
#include "exprs/vin_predicate.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Exprs_types.h>
22
#include <glog/logging.h>
23
24
#include <algorithm>
25
#include <cstddef>
26
#include <ostream>
27
28
#include "common/status.h"
29
#include "core/block/block.h"
30
#include "core/block/column_numbers.h"
31
#include "core/block/column_with_type_and_name.h"
32
#include "core/block/columns_with_type_and_name.h"
33
#include "core/data_type/define_primitive_type.h"
34
#include "exprs/expr_zonemap_filter.h"
35
#include "exprs/function/in.h"
36
#include "exprs/function/simple_function_factory.h"
37
#include "exprs/vexpr_context.h"
38
#include "exprs/vslot_ref.h"
39
#include "runtime/runtime_state.h"
40
41
namespace doris {
42
class RowDescriptor;
43
class RuntimeState;
44
} // namespace doris
45
46
namespace doris {
47
#include "common/compile_check_begin.h"
48
49
namespace {
50
51
52
size_t raw_in_value_size(PrimitiveType primitive_type) {
52
52
    switch (primitive_type) {
53
0
#define RETURN_RAW_IN_SIZE(TYPE) \
54
48
    case TYPE:                   \
55
48
        return sizeof(typename PrimitiveTypeTraits<TYPE>::CppType)
56
0
        RETURN_RAW_IN_SIZE(TYPE_BOOLEAN);
57
0
        RETURN_RAW_IN_SIZE(TYPE_TINYINT);
58
0
        RETURN_RAW_IN_SIZE(TYPE_SMALLINT);
59
0
        RETURN_RAW_IN_SIZE(TYPE_INT);
60
0
        RETURN_RAW_IN_SIZE(TYPE_BIGINT);
61
0
        RETURN_RAW_IN_SIZE(TYPE_LARGEINT);
62
24
        RETURN_RAW_IN_SIZE(TYPE_FLOAT);
63
24
        RETURN_RAW_IN_SIZE(TYPE_DOUBLE);
64
0
        RETURN_RAW_IN_SIZE(TYPE_DATE);
65
0
        RETURN_RAW_IN_SIZE(TYPE_DATETIME);
66
0
        RETURN_RAW_IN_SIZE(TYPE_DATEV2);
67
0
        RETURN_RAW_IN_SIZE(TYPE_DATETIMEV2);
68
0
        RETURN_RAW_IN_SIZE(TYPE_TIMESTAMP_NS);
69
0
        RETURN_RAW_IN_SIZE(TYPE_TIMESTAMPTZ);
70
0
        RETURN_RAW_IN_SIZE(TYPE_TIMEV2);
71
0
        RETURN_RAW_IN_SIZE(TYPE_DECIMAL32);
72
0
        RETURN_RAW_IN_SIZE(TYPE_DECIMAL64);
73
0
        RETURN_RAW_IN_SIZE(TYPE_DECIMALV2);
74
0
        RETURN_RAW_IN_SIZE(TYPE_DECIMAL128I);
75
0
        RETURN_RAW_IN_SIZE(TYPE_DECIMAL256);
76
0
        RETURN_RAW_IN_SIZE(TYPE_IPV4);
77
0
        RETURN_RAW_IN_SIZE(TYPE_IPV6);
78
0
        RETURN_RAW_IN_SIZE(TYPE_UUID);
79
0
#undef RETURN_RAW_IN_SIZE
80
4
    default:
81
4
        return 0;
82
52
    }
83
52
}
84
85
} // namespace
86
87
VInPredicate::VInPredicate(const TExprNode& node)
88
53
        : VExpr(node), _is_not_in(node.in_predicate.is_not_in) {}
89
90
Status VInPredicate::prepare(RuntimeState* state, const RowDescriptor& desc,
91
15
                             VExprContext* context) {
92
15
    RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
93
94
15
    if (_children.empty()) {
95
0
        return Status::InternalError("no Function operator in.");
96
0
    }
97
98
15
    _expr_name =
99
15
            fmt::format("({} {} set)", _children[0]->expr_name(), _is_not_in ? "not_in" : "in");
100
101
15
    ColumnsWithTypeAndName argument_template;
102
15
    argument_template.reserve(get_num_children());
103
45
    for (auto child : _children) {
104
45
        argument_template.emplace_back(nullptr, child->data_type(), child->expr_name());
105
45
    }
106
107
    // construct the proper function_name
108
15
    std::string head(_is_not_in ? "not_" : "");
109
15
    std::string real_function_name = head + std::string(function_name);
110
15
    auto arg_type = remove_nullable(argument_template[0].type);
111
15
    if (is_complex_type(arg_type->get_primitive_type())) {
112
0
        real_function_name = "collection_" + real_function_name;
113
0
    }
114
15
    _function = SimpleFunctionFactory::instance().get_function(real_function_name,
115
15
                                                               argument_template, _data_type, {});
116
15
    if (_function == nullptr) {
117
0
        return Status::NotSupported("Function {} is not implemented", real_function_name);
118
0
    }
119
120
15
    VExpr::register_function_context(state, context);
121
15
    _prepare_finished = true;
122
123
15
    if (state->query_options().__isset.in_list_value_count_threshold) {
124
15
        _in_list_value_count_threshold = state->query_options().in_list_value_count_threshold;
125
15
    }
126
15
    return Status::OK();
127
15
}
128
129
Status VInPredicate::open(RuntimeState* state, VExprContext* context,
130
10
                          FunctionContext::FunctionStateScope scope) {
131
10
    DCHECK(_prepare_finished);
132
28
    for (auto& child : _children) {
133
28
        RETURN_IF_ERROR(child->open(state, context, scope));
134
28
    }
135
10
    RETURN_IF_ERROR(VExpr::init_function_context(state, context, scope, _function));
136
10
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
137
10
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
138
10
    }
139
140
10
    _is_args_all_constant = std::all_of(_children.begin() + 1, _children.end(),
141
18
                                        [](const VExprSPtr& expr) { return expr->is_constant(); });
142
10
    if (scope == FunctionContext::FRAGMENT_LOCAL && _is_args_all_constant &&
143
10
        !_zonemap_materialized) {
144
10
        RETURN_IF_ERROR(_materialize_for_zonemap_filter(context));
145
10
    }
146
10
    _open_finished = true;
147
10
    return Status::OK();
148
10
}
149
150
27
void VInPredicate::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
151
27
    VExpr::close_function_context(context, scope, _function);
152
27
    VExpr::close(context, scope);
153
27
}
154
155
1
Status VInPredicate::evaluate_inverted_index(VExprContext* context, uint32_t segment_num_rows) {
156
1
    DCHECK_GE(get_num_children(), 2);
157
1
    return _evaluate_inverted_index(context, _function, segment_num_rows);
158
1
}
159
160
12
Status VInPredicate::_materialize_for_zonemap_filter(VExprContext* context) {
161
12
    _seg_filter_values.clear();
162
12
    _seg_filter_contains_null = false;
163
12
    _seg_filter_contains_nan = false;
164
12
    _zonemap_materialized = false;
165
12
    _direct_filter_set.reset();
166
12
    if (_children.size() < 2) {
167
0
        return Status::OK();
168
0
    }
169
170
12
    auto bloom_probe = expr_zonemap::extract_bloom_filter_probe(_children[0]);
171
12
    if (!bloom_probe.has_value()) {
172
0
        return Status::OK();
173
0
    }
174
    // Materialization is shared by all pruning paths. Their capability checks keep ZoneMap,
175
    // dictionary, and raw evaluation direct-slot-only while Bloom may consume a nested leaf.
176
12
    const auto data_type = remove_nullable(bloom_probe->value_type);
177
12
    DORIS_CHECK(data_type != nullptr);
178
    // Binary IN is rejected by the SQL function; do not build storage predicates for its keys.
179
12
    if (is_complex_type(data_type->get_primitive_type()) ||
180
12
        data_type->get_primitive_type() == TYPE_VARBINARY) {
181
2
        return Status::OK();
182
2
    }
183
184
10
    DORIS_CHECK(context != nullptr);
185
10
    auto* fn_ctx = context->fn_context(_fn_context_index);
186
10
    DORIS_CHECK(fn_ctx != nullptr);
187
10
    auto* in_state =
188
10
            reinterpret_cast<InState*>(fn_ctx->get_function_state(FunctionContext::FRAGMENT_LOCAL));
189
10
    DORIS_CHECK(in_state != nullptr);
190
10
    DORIS_CHECK(in_state->use_set);
191
10
    DORIS_CHECK(in_state->hybrid_set != nullptr);
192
10
    _direct_filter_set = in_state->hybrid_set;
193
194
10
    expr_zonemap::InZonemapMaterializedSet materialized;
195
10
    RETURN_IF_ERROR(expr_zonemap::materialize_hybrid_set_for_zonemap_filter(
196
10
            *in_state->hybrid_set, data_type, &materialized));
197
10
    _seg_filter_contains_null = materialized.contains_null;
198
10
    _seg_filter_contains_nan = materialized.contains_nan;
199
10
    _seg_filter_values = std::move(materialized.values);
200
10
    _seg_filter_min = std::move(materialized.min_value);
201
10
    _seg_filter_max = std::move(materialized.max_value);
202
10
    _zonemap_materialized = true;
203
10
    return Status::OK();
204
10
}
205
206
20
ZoneMapFilterResult VInPredicate::evaluate_zonemap_filter(const ZoneMapEvalContext& ctx) const {
207
20
    if (_is_not_in && _seg_filter_contains_null) {
208
1
        return ZoneMapFilterResult::kNoMatch;
209
1
    }
210
19
    return expr_zonemap::eval_in_zonemap(ctx, get_child(0), _is_not_in, _seg_filter_values,
211
19
                                         _seg_filter_contains_nan, _seg_filter_min,
212
19
                                         _seg_filter_max);
213
20
}
214
215
69
bool VInPredicate::can_evaluate_zonemap_filter() const {
216
69
    return _zonemap_materialized && std::dynamic_pointer_cast<VSlotRef>(get_child(0)) != nullptr;
217
69
}
218
219
ZoneMapFilterResult VInPredicate::evaluate_dictionary_filter(
220
2
        const DictionaryEvalContext& ctx) const {
221
2
    return expr_zonemap::eval_in_dictionary(ctx, get_child(0), _is_not_in, _seg_filter_values);
222
2
}
223
224
24
bool VInPredicate::can_evaluate_dictionary_filter() const {
225
24
    return _zonemap_materialized && !_is_not_in &&
226
24
           std::dynamic_pointer_cast<VSlotRef>(get_child(0)) != nullptr;
227
24
}
228
229
4
ZoneMapFilterResult VInPredicate::evaluate_bloom_filter(const BloomFilterEvalContext& ctx) const {
230
4
    return expr_zonemap::eval_in_bloom_filter(ctx, get_child(0), _is_not_in, _seg_filter_values);
231
4
}
232
233
16
bool VInPredicate::can_evaluate_bloom_filter() const {
234
    // A NaN member forces conservative retention regardless of the remaining finite probes.
235
16
    return _zonemap_materialized && !_is_not_in && !_seg_filter_contains_nan &&
236
16
           expr_zonemap::extract_bloom_filter_probe(get_child(0)).has_value();
237
16
}
238
239
bool VInPredicate::can_execute_on_raw_fixed_values(const DataTypePtr& data_type,
240
45
                                                   int column_id) const {
241
45
    if (!_zonemap_materialized || _direct_filter_set == nullptr || data_type == nullptr ||
242
45
        !_is_args_all_constant) {
243
0
        return false;
244
0
    }
245
45
    const auto slot = std::dynamic_pointer_cast<VSlotRef>(get_child(0));
246
45
    if (slot == nullptr || slot->column_id() != column_id || slot->data_type() == nullptr) {
247
1
        return false;
248
1
    }
249
44
    const auto raw_type = remove_nullable(data_type);
250
44
    return remove_nullable(slot->data_type())->equals(*raw_type) &&
251
44
           raw_in_value_size(raw_type->get_primitive_type()) != 0;
252
45
}
253
254
Status VInPredicate::execute_on_raw_fixed_values(const uint8_t* values, size_t num_values,
255
                                                 size_t value_width, const DataTypePtr& data_type,
256
8
                                                 int column_id, uint8_t* matches) const {
257
8
    if (!can_execute_on_raw_fixed_values(data_type, column_id)) {
258
0
        return Status::NotSupported("IN predicate cannot evaluate raw fixed-width values");
259
0
    }
260
8
    DORIS_CHECK(values != nullptr || num_values == 0);
261
8
    DORIS_CHECK(matches != nullptr || num_values == 0);
262
8
    const size_t expected_width =
263
8
            raw_in_value_size(remove_nullable(data_type)->get_primitive_type());
264
8
    if (value_width != expected_width) {
265
0
        return Status::Corruption("Raw IN width {} does not match expected {}", value_width,
266
0
                                  expected_width);
267
0
    }
268
    // NOT IN with a NULL literal is UNKNOWN for every non-null physical value. Definition levels
269
    // handle input NULLs, while this guard preserves the remaining three-valued SQL invariant.
270
8
    if (_is_not_in && _seg_filter_contains_null) {
271
0
        std::fill(matches, matches + num_values, uint8_t {0});
272
8
    } else if (_is_not_in) {
273
4
        _direct_filter_set->find_batch_raw_fixed_negative(values, num_values, value_width, matches);
274
4
    } else {
275
4
        _direct_filter_set->find_batch_raw_fixed(values, num_values, value_width, matches);
276
4
    }
277
8
    return Status::OK();
278
8
}
279
280
bool VInPredicate::can_execute_on_raw_binary_values(const DataTypePtr& data_type,
281
18
                                                    int column_id) const {
282
18
    if (!_zonemap_materialized || _direct_filter_set == nullptr || data_type == nullptr ||
283
18
        !_is_args_all_constant ||
284
18
        !is_string_type(remove_nullable(data_type)->get_primitive_type())) {
285
8
        return false;
286
8
    }
287
10
    const auto slot = std::dynamic_pointer_cast<VSlotRef>(get_child(0));
288
10
    return slot != nullptr && slot->column_id() == column_id && slot->data_type() != nullptr &&
289
10
           is_string_type(remove_nullable(slot->data_type())->get_primitive_type());
290
18
}
291
292
Status VInPredicate::execute_on_raw_binary_values(const StringRef* values, size_t num_values,
293
                                                  const DataTypePtr& data_type, int column_id,
294
2
                                                  uint8_t* matches) const {
295
2
    if (!can_execute_on_raw_binary_values(data_type, column_id)) {
296
0
        return Status::NotSupported("IN predicate cannot evaluate raw binary values");
297
0
    }
298
2
    DORIS_CHECK(values != nullptr || num_values == 0);
299
2
    DORIS_CHECK(matches != nullptr || num_values == 0);
300
2
    if (_is_not_in && _seg_filter_contains_null) {
301
0
        std::fill(matches, matches + num_values, uint8_t {0});
302
2
    } else if (_is_not_in) {
303
1
        _direct_filter_set->find_batch_raw_binary_negative(values, num_values, matches);
304
1
    } else {
305
        // Decoder-owned slices remain valid for the whole batch, so regular SQL IN/NOT IN can
306
        // probe the prepared hash set without constructing and then compacting a ColumnString.
307
1
        _direct_filter_set->find_batch_raw_binary(values, num_values, matches);
308
1
    }
309
2
    return Status::OK();
310
2
}
311
312
Status VInPredicate::execute_column(VExprContext* context, const Block* block, Selector* selector,
313
0
                                    size_t count, ColumnPtr& result_column) const {
314
0
    if (is_const_and_have_executed()) { // const have execute in open function
315
0
        result_column = get_result_from_const(count);
316
0
        return Status::OK();
317
0
    }
318
0
    if (fast_execute(context, selector, count, result_column)) {
319
0
        return Status::OK();
320
0
    }
321
0
    DCHECK(_open_finished || block == nullptr);
322
323
    // This is an optimization. For expressions like colA IN (1, 2, 3, 4),
324
    // where all values inside the IN clause are constants,
325
    // a hash set is created during open, and it will not be accessed again during execute
326
    //  Here, _children[0] is colA
327
0
    const size_t args_size = _is_args_all_constant ? 1 : _children.size();
328
329
0
    ColumnNumbers arguments;
330
0
    arguments.reserve(args_size);
331
0
    Block temp_block;
332
0
    for (int i = 0; i < args_size; ++i) {
333
0
        ColumnPtr column;
334
0
        RETURN_IF_ERROR(_children[i]->execute_column(context, block, selector, count, column));
335
0
        arguments.push_back(i);
336
0
        temp_block.insert({column, _children[i]->execute_type(block), _children[i]->expr_name()});
337
0
    }
338
339
0
    int num_columns_without_result = temp_block.columns();
340
0
    temp_block.insert({nullptr, _data_type, _expr_name});
341
342
0
    RETURN_IF_ERROR(_function->execute(context->fn_context(_fn_context_index), temp_block,
343
0
                                       arguments, num_columns_without_result, temp_block.rows()));
344
0
    result_column = temp_block.get_by_position(num_columns_without_result).column;
345
0
    DCHECK_EQ(result_column->size(), count);
346
0
    return Status::OK();
347
0
}
348
349
0
size_t VInPredicate::estimate_memory(const size_t rows) {
350
0
    if (is_const_and_have_executed()) {
351
0
        return 0;
352
0
    }
353
354
0
    size_t estimate_size = 0;
355
356
0
    for (int i = 0; i < _children.size(); ++i) {
357
0
        estimate_size += _children[i]->estimate_memory(rows);
358
0
    }
359
360
0
    if (_data_type->is_nullable()) {
361
0
        estimate_size += rows * sizeof(uint8_t);
362
0
    }
363
364
0
    estimate_size += rows * sizeof(uint8_t);
365
366
0
    return estimate_size;
367
0
}
368
369
10
const std::string& VInPredicate::expr_name() const {
370
10
    return _expr_name;
371
10
}
372
373
5
std::string VInPredicate::debug_string() const {
374
5
    std::stringstream out;
375
5
    out << "InPredicate(" << children()[0]->debug_string() << " " << _is_not_in << ",[";
376
5
    int num_children = get_num_children();
377
378
17
    for (int i = 1; i < num_children; ++i) {
379
12
        out << (i == 1 ? "" : " ") << children()[i]->debug_string();
380
12
    }
381
382
5
    out << "])";
383
5
    return out.str();
384
5
}
385
386
#include "common/compile_check_end.h"
387
} // namespace doris