Coverage Report

Created: 2026-11-05 16:36

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
268
size_t raw_in_value_size(PrimitiveType primitive_type) {
52
268
    switch (primitive_type) {
53
0
#define RETURN_RAW_IN_SIZE(TYPE) \
54
264
    case TYPE:                   \
55
264
        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
132
        RETURN_RAW_IN_SIZE(TYPE_FLOAT);
63
132
        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
268
    }
83
268
}
84
85
} // namespace
86
87
VInPredicate::VInPredicate(const TExprNode& node)
88
73
        : VExpr(node), _is_not_in(node.in_predicate.is_not_in) {}
89
90
Status VInPredicate::prepare(RuntimeState* state, const RowDescriptor& desc,
91
35
                             VExprContext* context) {
92
35
    RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
93
94
35
    if (_children.empty()) {
95
0
        return Status::InternalError("no Function operator in.");
96
0
    }
97
98
35
    _expr_name =
99
35
            fmt::format("({} {} set)", _children[0]->expr_name(), _is_not_in ? "not_in" : "in");
100
101
35
    ColumnsWithTypeAndName argument_template;
102
35
    argument_template.reserve(get_num_children());
103
85
    for (auto child : _children) {
104
85
        argument_template.emplace_back(nullptr, child->data_type(), child->expr_name());
105
85
    }
106
107
    // construct the proper function_name
108
35
    std::string head(_is_not_in ? "not_" : "");
109
35
    std::string real_function_name = head + std::string(function_name);
110
35
    auto arg_type = remove_nullable(argument_template[0].type);
111
35
    if (is_complex_type(arg_type->get_primitive_type())) {
112
0
        real_function_name = "collection_" + real_function_name;
113
0
    }
114
35
    _function = SimpleFunctionFactory::instance().get_function(real_function_name,
115
35
                                                               argument_template, _data_type, {});
116
35
    if (_function == nullptr) {
117
0
        return Status::NotSupported("Function {} is not implemented", real_function_name);
118
0
    }
119
120
35
    VExpr::register_function_context(state, context);
121
35
    _prepare_finished = true;
122
123
35
    if (state->query_options().__isset.in_list_value_count_threshold) {
124
35
        _in_list_value_count_threshold = state->query_options().in_list_value_count_threshold;
125
35
    }
126
35
    return Status::OK();
127
35
}
128
129
Status VInPredicate::open(RuntimeState* state, VExprContext* context,
130
30
                          FunctionContext::FunctionStateScope scope) {
131
30
    DCHECK(_prepare_finished);
132
68
    for (auto& child : _children) {
133
68
        RETURN_IF_ERROR(child->open(state, context, scope));
134
68
    }
135
30
    RETURN_IF_ERROR(VExpr::init_function_context(state, context, scope, _function));
136
30
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
137
30
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
138
30
    }
139
140
30
    _is_args_all_constant = std::all_of(_children.begin() + 1, _children.end(),
141
38
                                        [](const VExprSPtr& expr) { return expr->is_constant(); });
142
30
    if (scope == FunctionContext::FRAGMENT_LOCAL && _is_args_all_constant &&
143
30
        !_zonemap_materialized) {
144
30
        RETURN_IF_ERROR(_materialize_for_zonemap_filter(context));
145
30
    }
146
30
    _open_finished = true;
147
30
    return Status::OK();
148
30
}
149
150
67
void VInPredicate::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
151
67
    VExpr::close_function_context(context, scope, _function);
152
67
    VExpr::close(context, scope);
153
67
}
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
32
Status VInPredicate::_materialize_for_zonemap_filter(VExprContext* context) {
161
32
    _seg_filter_values.clear();
162
32
    _seg_filter_contains_null = false;
163
32
    _seg_filter_contains_nan = false;
164
32
    _zonemap_materialized = false;
165
32
    _direct_filter_set.reset();
166
32
    if (_children.size() < 2) {
167
0
        return Status::OK();
168
0
    }
169
170
32
    auto bloom_probe = expr_zonemap::extract_bloom_filter_probe(_children[0]);
171
32
    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
32
    const auto data_type = remove_nullable(bloom_probe->value_type);
177
32
    DORIS_CHECK(data_type != nullptr);
178
    // Binary IN is rejected by the SQL function; do not build storage predicates for its keys.
179
32
    if (is_complex_type(data_type->get_primitive_type()) ||
180
32
        data_type->get_primitive_type() == TYPE_VARBINARY) {
181
2
        return Status::OK();
182
2
    }
183
184
30
    DORIS_CHECK(context != nullptr);
185
30
    auto* fn_ctx = context->fn_context(_fn_context_index);
186
30
    DORIS_CHECK(fn_ctx != nullptr);
187
30
    auto* in_state =
188
30
            reinterpret_cast<InState*>(fn_ctx->get_function_state(FunctionContext::FRAGMENT_LOCAL));
189
30
    DORIS_CHECK(in_state != nullptr);
190
30
    DORIS_CHECK(in_state->use_set);
191
30
    DORIS_CHECK(in_state->hybrid_set != nullptr);
192
30
    _direct_filter_set = in_state->hybrid_set;
193
194
30
    expr_zonemap::InZonemapMaterializedSet materialized;
195
30
    RETURN_IF_ERROR(expr_zonemap::materialize_hybrid_set_for_zonemap_filter(
196
30
            *in_state->hybrid_set, data_type, &materialized));
197
30
    _seg_filter_contains_null = materialized.contains_null;
198
30
    _seg_filter_contains_nan = materialized.contains_nan;
199
30
    _seg_filter_values = std::move(materialized.values);
200
30
    _seg_filter_min = std::move(materialized.min_value);
201
30
    _seg_filter_max = std::move(materialized.max_value);
202
30
    _zonemap_materialized = true;
203
30
    return Status::OK();
204
30
}
205
206
96
ZoneMapFilterResult VInPredicate::evaluate_zonemap_filter(const ZoneMapEvalContext& ctx) const {
207
96
    if (_is_not_in && _seg_filter_contains_null) {
208
1
        return ZoneMapFilterResult::kNoMatch;
209
1
    }
210
95
    return expr_zonemap::eval_in_zonemap(ctx, get_child(0), _is_not_in, _seg_filter_values,
211
95
                                         _seg_filter_contains_nan, _seg_filter_min,
212
95
                                         _seg_filter_max);
213
96
}
214
215
333
bool VInPredicate::can_evaluate_zonemap_filter() const {
216
333
    return _zonemap_materialized && std::dynamic_pointer_cast<VSlotRef>(get_child(0)) != nullptr;
217
333
}
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
96
bool VInPredicate::can_evaluate_dictionary_filter() const {
225
96
    return _zonemap_materialized && !_is_not_in &&
226
96
           std::dynamic_pointer_cast<VSlotRef>(get_child(0)) != nullptr;
227
96
}
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
52
bool VInPredicate::can_evaluate_bloom_filter() const {
234
    // A NaN member forces conservative retention regardless of the remaining finite probes.
235
52
    return _zonemap_materialized && !_is_not_in && !_seg_filter_contains_nan &&
236
52
           expr_zonemap::extract_bloom_filter_probe(get_child(0)).has_value();
237
52
}
238
239
bool VInPredicate::can_execute_on_raw_fixed_values(const DataTypePtr& data_type,
240
225
                                                   int column_id) const {
241
225
    if (!_zonemap_materialized || _direct_filter_set == nullptr || data_type == nullptr ||
242
225
        !_is_args_all_constant) {
243
0
        return false;
244
0
    }
245
225
    const auto slot = std::dynamic_pointer_cast<VSlotRef>(get_child(0));
246
225
    if (slot == nullptr || slot->column_id() != column_id || slot->data_type() == nullptr) {
247
1
        return false;
248
1
    }
249
224
    const auto raw_type = remove_nullable(data_type);
250
224
    return remove_nullable(slot->data_type())->equals(*raw_type) &&
251
224
           raw_in_value_size(raw_type->get_primitive_type()) != 0;
252
225
}
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
44
                                                 int column_id, uint8_t* matches) const {
257
44
    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
44
    DORIS_CHECK(values != nullptr || num_values == 0);
261
44
    DORIS_CHECK(matches != nullptr || num_values == 0);
262
44
    const size_t expected_width =
263
44
            raw_in_value_size(remove_nullable(data_type)->get_primitive_type());
264
44
    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
44
    if (_is_not_in && _seg_filter_contains_null) {
271
0
        std::fill(matches, matches + num_values, uint8_t {0});
272
44
    } else if (_is_not_in) {
273
40
        _direct_filter_set->find_batch_raw_fixed_negative(values, num_values, value_width, matches);
274
40
    } else {
275
4
        _direct_filter_set->find_batch_raw_fixed(values, num_values, value_width, matches);
276
4
    }
277
44
    return Status::OK();
278
44
}
279
280
bool VInPredicate::can_execute_on_raw_binary_values(const DataTypePtr& data_type,
281
54
                                                    int column_id) const {
282
54
    if (!_zonemap_materialized || _direct_filter_set == nullptr || data_type == nullptr ||
283
54
        !_is_args_all_constant ||
284
54
        !is_string_type(remove_nullable(data_type)->get_primitive_type())) {
285
44
        return false;
286
44
    }
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
54
}
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_impl(VExprContext* context, const Block* block,
313
                                         const Selector* selector, size_t count,
314
0
                                         ColumnPtr& result_column) const {
315
0
    if (is_const_and_have_executed()) { // const have execute in open function
316
0
        result_column = get_result_from_const(count);
317
0
        return Status::OK();
318
0
    }
319
0
    if (fast_execute(context, selector, count, result_column)) {
320
0
        return Status::OK();
321
0
    }
322
0
    DCHECK(_open_finished || block == nullptr);
323
324
    // This is an optimization. For expressions like colA IN (1, 2, 3, 4),
325
    // where all values inside the IN clause are constants,
326
    // a hash set is created during open, and it will not be accessed again during execute
327
    //  Here, _children[0] is colA
328
0
    const size_t args_size = _is_args_all_constant ? 1 : _children.size();
329
330
0
    ColumnNumbers arguments;
331
0
    arguments.reserve(args_size);
332
0
    Block temp_block;
333
0
    for (int i = 0; i < args_size; ++i) {
334
0
        ColumnPtr column;
335
0
        RETURN_IF_ERROR(_children[i]->execute_column(context, block, selector, count, column));
336
0
        arguments.push_back(i);
337
0
        temp_block.insert({column, _children[i]->execute_type(block), _children[i]->expr_name()});
338
0
    }
339
340
0
    int num_columns_without_result = temp_block.columns();
341
0
    temp_block.insert({nullptr, _data_type, _expr_name});
342
343
0
    RETURN_IF_ERROR(_function->execute(context->fn_context(_fn_context_index), temp_block,
344
0
                                       arguments, num_columns_without_result, temp_block.rows()));
345
0
    result_column = temp_block.get_by_position(num_columns_without_result).column;
346
0
    DCHECK_EQ(result_column->size(), count);
347
0
    return Status::OK();
348
0
}
349
350
0
size_t VInPredicate::estimate_memory(const size_t rows) {
351
0
    if (is_const_and_have_executed()) {
352
0
        return 0;
353
0
    }
354
355
0
    size_t estimate_size = 0;
356
357
0
    for (int i = 0; i < _children.size(); ++i) {
358
0
        estimate_size += _children[i]->estimate_memory(rows);
359
0
    }
360
361
0
    if (_data_type->is_nullable()) {
362
0
        estimate_size += rows * sizeof(uint8_t);
363
0
    }
364
365
0
    estimate_size += rows * sizeof(uint8_t);
366
367
0
    return estimate_size;
368
0
}
369
370
46
const std::string& VInPredicate::expr_name() const {
371
46
    return _expr_name;
372
46
}
373
374
5
std::string VInPredicate::debug_string() const {
375
5
    std::stringstream out;
376
5
    out << "InPredicate(" << children()[0]->debug_string() << " " << _is_not_in << ",[";
377
5
    int num_children = get_num_children();
378
379
17
    for (int i = 1; i < num_children; ++i) {
380
12
        out << (i == 1 ? "" : " ") << children()[i]->debug_string();
381
12
    }
382
383
5
    out << "])";
384
5
    return out.str();
385
5
}
386
387
#include "common/compile_check_end.h"
388
} // namespace doris