Coverage Report

Created: 2026-08-11 00:26

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