Coverage Report

Created: 2026-04-20 20:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/file_scanner.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 "exec/scan/file_scanner.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Exprs_types.h>
22
#include <gen_cpp/Metrics_types.h>
23
#include <gen_cpp/Opcodes_types.h>
24
#include <gen_cpp/PaloInternalService_types.h>
25
#include <gen_cpp/PlanNodes_types.h>
26
#include <glog/logging.h>
27
28
#include <algorithm>
29
#include <boost/iterator/iterator_facade.hpp>
30
#include <map>
31
#include <ranges>
32
#include <tuple>
33
#include <unordered_map>
34
#include <utility>
35
36
#include "common/compiler_util.h" // IWYU pragma: keep
37
#include "common/config.h"
38
#include "common/consts.h"
39
#include "common/logging.h"
40
#include "common/status.h"
41
#include "core/block/column_with_type_and_name.h"
42
#include "core/block/columns_with_type_and_name.h"
43
#include "core/column/column.h"
44
#include "core/column/column_nullable.h"
45
#include "core/column/column_vector.h"
46
#include "core/data_type/data_type.h"
47
#include "core/data_type/data_type_nullable.h"
48
#include "core/data_type/data_type_string.h"
49
#include "core/string_ref.h"
50
#include "exec/common/stringop_substring.h"
51
#include "exec/rowid_fetcher.h"
52
#include "exec/scan/scan_node.h"
53
#include "exprs/aggregate/aggregate_function.h"
54
#include "exprs/function/function.h"
55
#include "exprs/function/simple_function_factory.h"
56
#include "exprs/vexpr.h"
57
#include "exprs/vexpr_context.h"
58
#include "exprs/vexpr_fwd.h"
59
#include "exprs/vslot_ref.h"
60
#include "format/arrow/arrow_stream_reader.h"
61
#include "format/count_reader.h"
62
#include "format/csv/csv_reader.h"
63
#include "format/json/new_json_reader.h"
64
#include "format/native/native_reader.h"
65
#include "format/orc/vorc_reader.h"
66
#include "format/parquet/vparquet_reader.h"
67
#include "format/table/hive_reader.h"
68
#include "format/table/hudi_jni_reader.h"
69
#include "format/table/hudi_reader.h"
70
#include "format/table/iceberg_reader.h"
71
#include "format/table/iceberg_sys_table_jni_reader.h"
72
#include "format/table/jdbc_jni_reader.h"
73
#include "format/table/max_compute_jni_reader.h"
74
#include "format/table/paimon_cpp_reader.h"
75
#include "format/table/paimon_jni_reader.h"
76
#include "format/table/paimon_predicate_converter.h"
77
#include "format/table/paimon_reader.h"
78
#include "format/table/remote_doris_reader.h"
79
#include "format/table/transactional_hive_reader.h"
80
#include "format/table/trino_connector_jni_reader.h"
81
#include "format/text/text_reader.h"
82
#include "io/cache/block_file_cache_profile.h"
83
#include "load/group_commit/wal/wal_reader.h"
84
#include "runtime/descriptors.h"
85
#include "runtime/runtime_profile.h"
86
#include "runtime/runtime_state.h"
87
88
namespace cctz {
89
class time_zone;
90
} // namespace cctz
91
namespace doris {
92
class ShardedKVCache;
93
} // namespace doris
94
95
namespace doris {
96
using namespace ErrorCode;
97
98
const std::string FileScanner::FileReadBytesProfile = "FileReadBytes";
99
const std::string FileScanner::FileReadTimeProfile = "FileReadTime";
100
101
FileScanner::FileScanner(RuntimeState* state, FileScanLocalState* local_state, int64_t limit,
102
                         std::shared_ptr<SplitSourceConnector> split_source,
103
                         RuntimeProfile* profile, ShardedKVCache* kv_cache,
104
                         const std::unordered_map<std::string, int>* colname_to_slot_id)
105
2
        : Scanner(state, local_state, limit, profile),
106
2
          _split_source(split_source),
107
2
          _cur_reader(nullptr),
108
2
          _cur_reader_eof(false),
109
2
          _kv_cache(kv_cache),
110
2
          _strict_mode(false),
111
2
          _col_name_to_slot_id(colname_to_slot_id) {
112
2
    if (state->get_query_ctx() != nullptr &&
113
2
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
114
0
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
115
2
    } else {
116
        // old fe thrift protocol
117
2
        _params = _split_source->get_params();
118
2
    }
119
2
    if (_params->__isset.strict_mode) {
120
0
        _strict_mode = _params->strict_mode;
121
0
    }
122
123
    // For load scanner, there are input and output tuple.
124
    // For query scanner, there is only output tuple
125
2
    _input_tuple_desc = state->desc_tbl().get_tuple_descriptor(_params->src_tuple_id);
126
2
    _real_tuple_desc = _input_tuple_desc == nullptr ? _output_tuple_desc : _input_tuple_desc;
127
2
    _is_load = (_input_tuple_desc != nullptr);
128
2
    _configure_file_scan_handlers();
129
2
}
130
131
18
void FileScanner::_configure_file_scan_handlers() {
132
18
    if (_is_load) {
133
2
        _init_src_block_handler = &FileScanner::_init_src_block_for_load;
134
2
        _process_src_block_after_read_handler =
135
2
                &FileScanner::_process_src_block_after_read_for_load;
136
2
        _should_push_down_predicates_handler = &FileScanner::_should_push_down_predicates_for_load;
137
2
        _should_enable_condition_cache_handler =
138
2
                &FileScanner::_should_enable_condition_cache_for_load;
139
16
    } else {
140
16
        _init_src_block_handler = &FileScanner::_init_src_block_for_query;
141
16
        _process_src_block_after_read_handler =
142
16
                &FileScanner::_process_src_block_after_read_for_query;
143
16
        _should_push_down_predicates_handler = &FileScanner::_should_push_down_predicates_for_query;
144
16
        _should_enable_condition_cache_handler =
145
16
                &FileScanner::_should_enable_condition_cache_for_query;
146
16
    }
147
18
}
148
149
2
Status FileScanner::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
150
2
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
151
2
    _get_block_timer =
152
2
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerGetBlockTime", 1);
153
2
    _cast_to_input_block_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
154
2
                                                      "FileScannerCastInputBlockTime", 1);
155
2
    _fill_missing_columns_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
156
2
                                                       "FileScannerFillMissingColumnTime", 1);
157
2
    _pre_filter_timer =
158
2
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerPreFilterTimer", 1);
159
2
    _convert_to_output_block_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
160
2
                                                          "FileScannerConvertOuputBlockTime", 1);
161
2
    _runtime_filter_partition_prune_timer = ADD_TIMER_WITH_LEVEL(
162
2
            _local_state->scanner_profile(), "FileScannerRuntimeFilterPartitionPruningTime", 1);
163
2
    _empty_file_counter =
164
2
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "EmptyFileNum", TUnit::UNIT, 1);
165
2
    _not_found_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
166
2
                                                     "NotFoundFileNum", TUnit::UNIT, 1);
167
2
    _fully_skipped_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
168
2
                                                         "FullySkippedFileNum", TUnit::UNIT, 1);
169
2
    _file_counter =
170
2
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "FileNumber", TUnit::UNIT, 1);
171
172
2
    _file_read_bytes_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
173
2
                                                      FileReadBytesProfile, TUnit::BYTES, 1);
174
2
    _file_read_calls_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
175
2
                                                      "FileReadCalls", TUnit::UNIT, 1);
176
2
    _file_read_time_counter =
177
2
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), FileReadTimeProfile, 1);
178
179
2
    _runtime_filter_partition_pruned_range_counter =
180
2
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
181
2
                                   "RuntimeFilterPartitionPrunedRangeNum", TUnit::UNIT, 1);
182
183
2
    _file_cache_statistics.reset(new io::FileCacheStatistics());
184
2
    _file_reader_stats.reset(new io::FileReaderStats());
185
186
2
    RETURN_IF_ERROR(_init_io_ctx());
187
2
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
188
2
    _io_ctx->file_reader_stats = _file_reader_stats.get();
189
2
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
190
191
2
    if (_is_load) {
192
0
        _src_row_desc.reset(new RowDescriptor(_state->desc_tbl(),
193
0
                                              std::vector<TupleId>({_input_tuple_desc->id()})));
194
        // prepare pre filters
195
0
        if (_params->__isset.pre_filter_exprs_list) {
196
0
            RETURN_IF_ERROR(doris::VExpr::create_expr_trees(_params->pre_filter_exprs_list,
197
0
                                                            _pre_conjunct_ctxs));
198
0
        } else if (_params->__isset.pre_filter_exprs) {
199
0
            VExprContextSPtr context;
200
0
            RETURN_IF_ERROR(doris::VExpr::create_expr_tree(_params->pre_filter_exprs, context));
201
0
            _pre_conjunct_ctxs.emplace_back(context);
202
0
        }
203
204
0
        for (auto& conjunct : _pre_conjunct_ctxs) {
205
0
            RETURN_IF_ERROR(conjunct->prepare(_state, *_src_row_desc));
206
0
            RETURN_IF_ERROR(conjunct->open(_state));
207
0
        }
208
209
0
        _dest_row_desc.reset(new RowDescriptor(_state->desc_tbl(),
210
0
                                               std::vector<TupleId>({_output_tuple_desc->id()})));
211
0
    }
212
213
2
    _default_val_row_desc.reset(
214
2
            new RowDescriptor(_state->desc_tbl(), std::vector<TupleId>({_real_tuple_desc->id()})));
215
216
2
    return Status::OK();
217
2
}
218
219
// check if the expr is a partition pruning expr
220
0
bool FileScanner::_check_partition_prune_expr(const VExprSPtr& expr) {
221
0
    if (expr->is_slot_ref()) {
222
0
        auto* slot_ref = static_cast<VSlotRef*>(expr.get());
223
0
        return _partition_slot_index_map.find(slot_ref->slot_id()) !=
224
0
               _partition_slot_index_map.end();
225
0
    }
226
0
    if (expr->is_literal()) {
227
0
        return true;
228
0
    }
229
0
    return std::ranges::all_of(expr->children(), [this](const auto& child) {
230
0
        return _check_partition_prune_expr(child);
231
0
    });
232
0
}
233
234
0
void FileScanner::_init_runtime_filter_partition_prune_ctxs() {
235
0
    _runtime_filter_partition_prune_ctxs.clear();
236
0
    for (auto& conjunct : _conjuncts) {
237
0
        auto impl = conjunct->root()->get_impl();
238
        // If impl is not null, which means this a conjuncts from runtime filter.
239
0
        auto expr = impl ? impl : conjunct->root();
240
0
        if (_check_partition_prune_expr(expr)) {
241
0
            _runtime_filter_partition_prune_ctxs.emplace_back(conjunct);
242
0
        }
243
0
    }
244
0
}
245
246
0
void FileScanner::_init_runtime_filter_partition_prune_block() {
247
    // init block with empty column
248
0
    for (auto const* slot_desc : _real_tuple_desc->slots()) {
249
0
        _runtime_filter_partition_prune_block.insert(
250
0
                ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
251
0
                                      slot_desc->get_data_type_ptr(), slot_desc->col_name()));
252
0
    }
253
0
}
254
255
0
Status FileScanner::_process_runtime_filters_partition_prune(bool& can_filter_all) {
256
0
    SCOPED_TIMER(_runtime_filter_partition_prune_timer);
257
0
    if (_runtime_filter_partition_prune_ctxs.empty() || _partition_col_descs.empty()) {
258
0
        return Status::OK();
259
0
    }
260
0
    size_t partition_value_column_size = 1;
261
262
    // 1. Get partition key values to string columns.
263
0
    std::unordered_map<SlotId, MutableColumnPtr> partition_slot_id_to_column;
264
0
    for (auto const& partition_col_desc : _partition_col_descs) {
265
0
        const auto& [partition_value, partition_slot_desc] = partition_col_desc.second;
266
0
        auto data_type = partition_slot_desc->get_data_type_ptr();
267
0
        auto test_serde = data_type->get_serde();
268
0
        auto partition_value_column = data_type->create_column();
269
0
        auto* col_ptr = static_cast<IColumn*>(partition_value_column.get());
270
0
        Slice slice(partition_value.data(), partition_value.size());
271
0
        uint64_t num_deserialized = 0;
272
0
        DataTypeSerDe::FormatOptions options {};
273
0
        if (_partition_value_is_null.contains(partition_slot_desc->col_name())) {
274
            // for iceberg/paimon table
275
            // NOTICE: column is always be nullable for iceberg/paimon table now
276
0
            DCHECK(data_type->is_nullable());
277
0
            test_serde = test_serde->get_nested_serdes()[0];
278
0
            auto* null_column = assert_cast<ColumnNullable*>(col_ptr);
279
0
            if (_partition_value_is_null[partition_slot_desc->col_name()]) {
280
0
                null_column->insert_many_defaults(partition_value_column_size);
281
0
            } else {
282
                // If the partition value is not null, we set null map to 0 and deserialize it normally.
283
0
                null_column->get_null_map_column().insert_many_vals(0, partition_value_column_size);
284
0
                RETURN_IF_ERROR(test_serde->deserialize_column_from_fixed_json(
285
0
                        null_column->get_nested_column(), slice, partition_value_column_size,
286
0
                        &num_deserialized, options));
287
0
            }
288
0
        } else {
289
            // for hive/hudi table, the null value is set as "\\N"
290
            // TODO: this will be unified as iceberg/paimon table in the future
291
0
            RETURN_IF_ERROR(test_serde->deserialize_column_from_fixed_json(
292
0
                    *col_ptr, slice, partition_value_column_size, &num_deserialized, options));
293
0
        }
294
295
0
        partition_slot_id_to_column[partition_slot_desc->id()] = std::move(partition_value_column);
296
0
    }
297
298
    // 2. Fill _runtime_filter_partition_prune_block from the partition column, then execute conjuncts and filter block.
299
    // 2.1 Fill _runtime_filter_partition_prune_block from the partition column to match the conjuncts executing.
300
0
    size_t index = 0;
301
0
    bool first_column_filled = false;
302
0
    for (auto const* slot_desc : _real_tuple_desc->slots()) {
303
0
        if (partition_slot_id_to_column.find(slot_desc->id()) !=
304
0
            partition_slot_id_to_column.end()) {
305
0
            auto data_type = slot_desc->get_data_type_ptr();
306
0
            auto partition_value_column = std::move(partition_slot_id_to_column[slot_desc->id()]);
307
0
            if (data_type->is_nullable()) {
308
0
                _runtime_filter_partition_prune_block.insert(
309
0
                        index, ColumnWithTypeAndName(
310
0
                                       ColumnNullable::create(
311
0
                                               std::move(partition_value_column),
312
0
                                               ColumnUInt8::create(partition_value_column_size, 0)),
313
0
                                       data_type, slot_desc->col_name()));
314
0
            } else {
315
0
                _runtime_filter_partition_prune_block.insert(
316
0
                        index, ColumnWithTypeAndName(std::move(partition_value_column), data_type,
317
0
                                                     slot_desc->col_name()));
318
0
            }
319
0
            if (index == 0) {
320
0
                first_column_filled = true;
321
0
            }
322
0
        }
323
0
        index++;
324
0
    }
325
326
    // 2.2 Execute conjuncts.
327
0
    if (!first_column_filled) {
328
        // VExprContext.execute has an optimization, the filtering is executed when block->rows() > 0
329
        // The following process may be tricky and time-consuming, but we have no other way.
330
0
        _runtime_filter_partition_prune_block.get_by_position(0).column->assume_mutable()->resize(
331
0
                partition_value_column_size);
332
0
    }
333
0
    IColumn::Filter result_filter(_runtime_filter_partition_prune_block.rows(), 1);
334
0
    RETURN_IF_ERROR(VExprContext::execute_conjuncts(_runtime_filter_partition_prune_ctxs, nullptr,
335
0
                                                    &_runtime_filter_partition_prune_block,
336
0
                                                    &result_filter, &can_filter_all));
337
0
    return Status::OK();
338
0
}
339
340
1
Status FileScanner::_process_conjuncts() {
341
1
    _slot_id_to_filter_conjuncts.clear();
342
1
    _not_single_slot_filter_conjuncts.clear();
343
1
    for (auto& conjunct : _push_down_conjuncts) {
344
1
        auto impl = conjunct->root()->get_impl();
345
        // If impl is not null, which means this a conjuncts from runtime filter.
346
1
        auto cur_expr = impl ? impl : conjunct->root();
347
348
1
        std::vector<int> slot_ids;
349
1
        _get_slot_ids(cur_expr.get(), &slot_ids);
350
1
        if (slot_ids.empty()) {
351
1
            _not_single_slot_filter_conjuncts.emplace_back(conjunct);
352
1
            continue;
353
1
        }
354
0
        bool single_slot = true;
355
0
        for (int i = 1; i < slot_ids.size(); i++) {
356
0
            if (slot_ids[i] != slot_ids[0]) {
357
0
                single_slot = false;
358
0
                break;
359
0
            }
360
0
        }
361
0
        if (single_slot) {
362
0
            SlotId slot_id = slot_ids[0];
363
0
            _slot_id_to_filter_conjuncts[slot_id].emplace_back(conjunct);
364
0
        } else {
365
0
            _not_single_slot_filter_conjuncts.emplace_back(conjunct);
366
0
        }
367
0
    }
368
1
    return Status::OK();
369
1
}
370
371
1
Status FileScanner::_process_late_arrival_conjuncts() {
372
1
    if (_push_down_conjuncts.size() < _conjuncts.size()) {
373
1
        _push_down_conjuncts = _conjuncts;
374
        // Do not clear _conjuncts here!
375
        // We must keep it for fallback filtering, especially when mixing
376
        // Native readers (which use _push_down_conjuncts) and JNI readers (which rely on _conjuncts).
377
        // _conjuncts.clear();
378
1
        RETURN_IF_ERROR(_process_conjuncts());
379
1
    }
380
1
    if (_applied_rf_num == _total_rf_num) {
381
1
        _local_state->scanner_profile()->add_info_string("ApplyAllRuntimeFilters", "True");
382
1
    }
383
1
    return Status::OK();
384
1
}
385
386
1
void FileScanner::_get_slot_ids(VExpr* expr, std::vector<int>* slot_ids) {
387
1
    for (auto& child_expr : expr->children()) {
388
0
        if (child_expr->is_slot_ref()) {
389
0
            VSlotRef* slot_ref = reinterpret_cast<VSlotRef*>(child_expr.get());
390
0
            SlotDescriptor* slot_desc = _state->desc_tbl().get_slot_descriptor(slot_ref->slot_id());
391
0
            slot_desc->set_is_predicate(true);
392
0
            slot_ids->emplace_back(slot_ref->slot_id());
393
0
        } else {
394
0
            _get_slot_ids(child_expr.get(), slot_ids);
395
0
        }
396
0
    }
397
1
}
398
399
0
Status FileScanner::_open_impl(RuntimeState* state) {
400
0
    RETURN_IF_CANCELLED(state);
401
0
    RETURN_IF_ERROR(Scanner::_open_impl(state));
402
0
    if (_local_state) {
403
0
        _condition_cache_digest = _local_state->get_condition_cache_digest();
404
0
    }
405
0
    RETURN_IF_ERROR(_split_source->get_next(&_first_scan_range, &_current_range));
406
0
    if (_first_scan_range) {
407
0
        RETURN_IF_ERROR(_init_expr_ctxes());
408
0
        if (_state->query_options().enable_runtime_filter_partition_prune &&
409
0
            !_partition_slot_index_map.empty()) {
410
0
            _init_runtime_filter_partition_prune_ctxs();
411
0
            _init_runtime_filter_partition_prune_block();
412
0
        }
413
0
    } else {
414
        // there's no scan range in split source. stop scanner directly.
415
0
        _scanner_eof = true;
416
0
    }
417
418
0
    return Status::OK();
419
0
}
420
421
37
Status FileScanner::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
422
37
    Status st = _get_block_wrapped(state, block, eof);
423
424
37
    if (!st.ok()) {
425
        // add cur path in error msg for easy debugging
426
1
        return std::move(st.append(". cur path: " + get_current_scan_range_name()));
427
1
    }
428
36
    return st;
429
37
}
430
431
// For query:
432
//                              [exist cols]  [non-exist cols]  [col from path]  input  output
433
//                              A     B    C  D                 E
434
// _init_src_block              x     x    x  x                 x                -      x
435
// get_next_block               x     x    x  -                 -                -      x
436
// _cast_to_input_block         -     -    -  -                 -                -      -
437
// _fill_columns_from_path      -     -    -  -                 x                -      x
438
// _fill_missing_columns        -     -    -  x                 -                -      x
439
// _convert_to_output_block     -     -    -  -                 -                -      -
440
//
441
// For load:
442
//                              [exist cols]  [non-exist cols]  [col from path]  input  output
443
//                              A     B    C  D                 E
444
// _init_src_block              x     x    x  x                 x                x      -
445
// get_next_block               x     x    x  -                 -                x      -
446
// _cast_to_input_block         x     x    x  -                 -                x      -
447
// _fill_columns_from_path      -     -    -  -                 x                x      -
448
// _fill_missing_columns        -     -    -  x                 -                x      -
449
// _convert_to_output_block     -     -    -  -                 -                -      x
450
37
Status FileScanner::_get_block_wrapped(RuntimeState* state, Block* block, bool* eof) {
451
37
    do {
452
37
        RETURN_IF_CANCELLED(state);
453
37
        if (_cur_reader == nullptr || _cur_reader_eof) {
454
1
            _finalize_reader_condition_cache();
455
            // The file may not exist because the file list is got from meta cache,
456
            // And the file may already be removed from storage.
457
            // Just ignore not found files.
458
1
            Status st = _get_next_reader();
459
1
            if (st.is<ErrorCode::NOT_FOUND>() && config::ignore_not_found_file_in_external_table) {
460
0
                _cur_reader_eof = true;
461
0
                COUNTER_UPDATE(_not_found_file_counter, 1);
462
0
                continue;
463
1
            } else if (st.is<ErrorCode::END_OF_FILE>()) {
464
0
                _cur_reader_eof = true;
465
0
                COUNTER_UPDATE(_fully_skipped_file_counter, 1);
466
0
                continue;
467
1
            } else if (!st) {
468
1
                return st;
469
1
            }
470
0
            _init_reader_condition_cache();
471
0
        }
472
473
36
        if (_scanner_eof) {
474
0
            *eof = true;
475
0
            return Status::OK();
476
0
        }
477
478
        // Init src block for load job based on the data file schema (e.g. parquet)
479
        // For query job, simply set _src_block_ptr to block.
480
36
        size_t read_rows = 0;
481
36
        RETURN_IF_ERROR(_init_src_block(block));
482
36
        {
483
36
            SCOPED_TIMER(_get_block_timer);
484
485
            // Read next block.
486
            // Some of column in block may not be filled (column not exist in file)
487
36
            RETURN_IF_ERROR(
488
36
                    _cur_reader->get_next_block(_src_block_ptr, &read_rows, &_cur_reader_eof));
489
36
        }
490
        // use read_rows instead of _src_block_ptr->rows(), because the first column of _src_block_ptr
491
        // may not be filled after calling `get_next_block()`, so _src_block_ptr->rows() may return wrong result.
492
36
        if (read_rows > 0) {
493
25
            if ((!_cur_reader->count_read_rows()) && _io_ctx) {
494
0
                _io_ctx->file_reader_stats->read_rows += read_rows;
495
0
            }
496
            // If the push_down_agg_type is COUNT, no need to do the rest,
497
            // because we only save a number in block.
498
25
            if (_get_push_down_agg_type() != TPushAggOp::type::COUNT) {
499
25
                RETURN_IF_ERROR(_process_src_block_after_read(block));
500
25
            }
501
25
        }
502
36
        break;
503
36
    } while (true);
504
505
    // Update filtered rows and unselected rows for load, reset counter.
506
    // {
507
    //     state->update_num_rows_load_filtered(_counter.num_rows_filtered);
508
    //     state->update_num_rows_load_unselected(_counter.num_rows_unselected);
509
    //     _reset_counter();
510
    // }
511
36
    return Status::OK();
512
37
}
513
514
/**
515
 * Check whether there are complex types in parquet/orc reader in broker/stream load.
516
 * Broker/stream load will cast any type as string type, and complex types will be casted wrong.
517
 * This is a temporary method, and will be replaced by tvf.
518
 */
519
0
Status FileScanner::_check_output_block_types() {
520
    // Only called from _init_src_block_for_load, so _is_load is always true.
521
0
    TFileFormatType::type format_type = _params->format_type;
522
0
    if (format_type == TFileFormatType::FORMAT_PARQUET ||
523
0
        format_type == TFileFormatType::FORMAT_ORC) {
524
0
        for (auto slot : _output_tuple_desc->slots()) {
525
0
            if (is_complex_type(slot->type()->get_primitive_type())) {
526
0
                return Status::InternalError(
527
0
                        "Parquet/orc doesn't support complex types in broker/stream load, "
528
0
                        "please use tvf(table value function) to insert complex types.");
529
0
            }
530
0
        }
531
0
    }
532
0
    return Status::OK();
533
0
}
534
535
36
Status FileScanner::_init_src_block(Block* block) {
536
36
    DCHECK(_init_src_block_handler != nullptr);
537
36
    return (this->*_init_src_block_handler)(block);
538
36
}
539
540
36
Status FileScanner::_init_src_block_for_query(Block* block) {
541
36
    _src_block_ptr = block;
542
543
    // Build name to index map only once on first call.
544
36
    if (_src_block_name_to_idx.empty()) {
545
16
        _src_block_name_to_idx = block->get_name_to_pos_map();
546
16
    }
547
36
    return Status::OK();
548
36
}
549
550
0
Status FileScanner::_init_src_block_for_load(Block* block) {
551
0
    static_cast<void>(block);
552
0
    RETURN_IF_ERROR(_check_output_block_types());
553
554
    // if (_src_block_init) {
555
    //     _src_block.clear_column_data();
556
    //     _src_block_ptr = &_src_block;
557
    //     return Status::OK();
558
    // }
559
560
0
    _src_block.clear();
561
0
    uint32_t idx = 0;
562
    // slots in _input_tuple_desc contains all slots describe in load statement, eg:
563
    // -H "columns: k1, k2, tmp1, k3 = tmp1 + 1"
564
    // _input_tuple_desc will contains: k1, k2, tmp1
565
    // and some of them are from file, such as k1 and k2, and some of them may not exist in file, such as tmp1
566
    // _input_tuple_desc also contains columns from path
567
0
    for (auto& slot : _input_tuple_desc->slots()) {
568
0
        DataTypePtr data_type;
569
0
        auto it = _slot_lower_name_to_col_type.find(slot->col_name());
570
0
        if (slot->is_skip_bitmap_col()) {
571
0
            _skip_bitmap_col_idx = idx;
572
0
        }
573
0
        if (_params->__isset.sequence_map_col) {
574
0
            if (_params->sequence_map_col == slot->col_name()) {
575
0
                _sequence_map_col_uid = slot->col_unique_id();
576
0
            }
577
0
        }
578
0
        data_type =
579
0
                it == _slot_lower_name_to_col_type.end() ? slot->type() : make_nullable(it->second);
580
0
        MutableColumnPtr data_column = data_type->create_column();
581
0
        _src_block.insert(
582
0
                ColumnWithTypeAndName(std::move(data_column), data_type, slot->col_name()));
583
0
        _src_block_name_to_idx.emplace(slot->col_name(), idx++);
584
0
    }
585
0
    if (_params->__isset.sequence_map_col) {
586
0
        for (const auto& slot : _output_tuple_desc->slots()) {
587
            // When the target table has seqeunce map column, _input_tuple_desc will not contains __DORIS_SEQUENCE_COL__,
588
            // so we should get its column unique id from _output_tuple_desc
589
0
            if (slot->is_sequence_col()) {
590
0
                _sequence_col_uid = slot->col_unique_id();
591
0
            }
592
0
        }
593
0
    }
594
0
    _src_block_ptr = &_src_block;
595
0
    _src_block_init = true;
596
0
    return Status::OK();
597
0
}
598
599
0
Status FileScanner::_cast_to_input_block(Block* block) {
600
    // Only called from _process_src_block_after_read_for_load, so _is_load is always true.
601
0
    SCOPED_TIMER(_cast_to_input_block_timer);
602
    // cast primitive type(PT0) to primitive type(PT1)
603
0
    uint32_t idx = 0;
604
0
    for (auto& slot_desc : _input_tuple_desc->slots()) {
605
0
        if (_slot_lower_name_to_col_type.find(slot_desc->col_name()) ==
606
0
            _slot_lower_name_to_col_type.end()) {
607
            // skip columns which does not exist in file
608
0
            continue;
609
0
        }
610
0
        auto& arg = _src_block_ptr->get_by_position(_src_block_name_to_idx[slot_desc->col_name()]);
611
0
        auto return_type = slot_desc->get_data_type_ptr();
612
        // remove nullable here, let the get_function decide whether nullable
613
0
        auto data_type = get_data_type_with_default_argument(remove_nullable(return_type));
614
0
        ColumnsWithTypeAndName arguments {
615
0
                arg, {data_type->create_column(), data_type, slot_desc->col_name()}};
616
0
        auto func_cast =
617
0
                SimpleFunctionFactory::instance().get_function("CAST", arguments, return_type, {});
618
0
        if (!func_cast) {
619
0
            return Status::InternalError("Function CAST[arg={}, col name={}, return={}] not found!",
620
0
                                         arg.type->get_name(), slot_desc->col_name(),
621
0
                                         return_type->get_name());
622
0
        }
623
0
        idx = _src_block_name_to_idx[slot_desc->col_name()];
624
0
        DCHECK(_state != nullptr);
625
0
        auto ctx = FunctionContext::create_context(_state, {}, {});
626
0
        RETURN_IF_ERROR(
627
0
                func_cast->execute(ctx.get(), *_src_block_ptr, {idx}, idx, arg.column->size()));
628
0
        _src_block_ptr->get_by_position(idx).type = std::move(return_type);
629
0
    }
630
0
    return Status::OK();
631
0
}
632
633
0
Status FileScanner::_pre_filter_src_block() {
634
    // Only called from _process_src_block_after_read_for_load, so _is_load is always true.
635
0
    if (!_pre_conjunct_ctxs.empty()) {
636
0
        SCOPED_TIMER(_pre_filter_timer);
637
0
        auto origin_column_num = _src_block_ptr->columns();
638
0
        auto old_rows = _src_block_ptr->rows();
639
0
        RETURN_IF_ERROR(
640
0
                VExprContext::filter_block(_pre_conjunct_ctxs, _src_block_ptr, origin_column_num));
641
0
        _counter.num_rows_unselected += old_rows - _src_block_ptr->rows();
642
0
    }
643
0
    return Status::OK();
644
0
}
645
646
0
Status FileScanner::_convert_to_output_block(Block* block) {
647
    // Only called from _process_src_block_after_read_for_load, so _is_load is always true.
648
0
    SCOPED_TIMER(_convert_to_output_block_timer);
649
    // The block is passed from scanner context's free blocks,
650
    // which is initialized by output columns
651
    // so no need to clear it
652
    // block->clear();
653
654
0
    int ctx_idx = 0;
655
0
    size_t rows = _src_block_ptr->rows();
656
0
    auto filter_column = ColumnUInt8::create(rows, 1);
657
0
    auto& filter_map = filter_column->get_data();
658
659
    // After convert, the column_ptr should be copied into output block.
660
    // Can not use block->insert() because it may cause use_count() non-zero bug
661
0
    MutableBlock mutable_output_block =
662
0
            VectorizedUtils::build_mutable_mem_reuse_block(block, *_dest_row_desc);
663
0
    auto& mutable_output_columns = mutable_output_block.mutable_columns();
664
665
0
    std::vector<BitmapValue>* skip_bitmaps {nullptr};
666
0
    if (_should_process_skip_bitmap_col()) {
667
0
        auto* skip_bitmap_nullable_col_ptr =
668
0
                assert_cast<ColumnNullable*>(_src_block_ptr->get_by_position(_skip_bitmap_col_idx)
669
0
                                                     .column->assume_mutable()
670
0
                                                     .get());
671
0
        skip_bitmaps = &(assert_cast<ColumnBitmap*>(
672
0
                                 skip_bitmap_nullable_col_ptr->get_nested_column_ptr().get())
673
0
                                 ->get_data());
674
        // NOTE:
675
        // - If the table has sequence type column, __DORIS_SEQUENCE_COL__ will be put in _input_tuple_desc, so whether
676
        //   __DORIS_SEQUENCE_COL__ will be marked in skip bitmap depends on whether it's specified in that row
677
        // - If the table has sequence map column, __DORIS_SEQUENCE_COL__ will not be put in _input_tuple_desc,
678
        //   so __DORIS_SEQUENCE_COL__ will be ommited if it't specified in a row and will not be marked in skip bitmap.
679
        //   So we should mark __DORIS_SEQUENCE_COL__ in skip bitmap here if the corresponding sequence map column us marked
680
0
        if (_sequence_map_col_uid != -1) {
681
0
            for (int j = 0; j < rows; ++j) {
682
0
                if ((*skip_bitmaps)[j].contains(_sequence_map_col_uid)) {
683
0
                    (*skip_bitmaps)[j].add(_sequence_col_uid);
684
0
                }
685
0
            }
686
0
        }
687
0
    }
688
689
    // for (auto slot_desc : _output_tuple_desc->slots()) {
690
0
    for (int j = 0; j < mutable_output_columns.size(); ++j) {
691
0
        auto* slot_desc = _output_tuple_desc->slots()[j];
692
0
        int dest_index = ctx_idx;
693
0
        ColumnPtr column_ptr;
694
695
0
        auto& ctx = _dest_vexpr_ctx[dest_index];
696
        // PT1 => dest primitive type
697
0
        RETURN_IF_ERROR(ctx->execute(_src_block_ptr, column_ptr));
698
        // column_ptr maybe a ColumnConst, convert it to a normal column
699
0
        column_ptr = column_ptr->convert_to_full_column_if_const();
700
0
        DCHECK(column_ptr);
701
702
        // because of src_slot_desc is always be nullable, so the column_ptr after do dest_expr
703
        // is likely to be nullable
704
0
        if (LIKELY(column_ptr->is_nullable())) {
705
0
            const auto* nullable_column = reinterpret_cast<const ColumnNullable*>(column_ptr.get());
706
0
            for (int i = 0; i < rows; ++i) {
707
0
                if (filter_map[i] && nullable_column->is_null_at(i)) {
708
                    // skip checks for non-mentioned columns in flexible partial update
709
0
                    if (skip_bitmaps == nullptr ||
710
0
                        !skip_bitmaps->at(i).contains(slot_desc->col_unique_id())) {
711
                        // clang-format off
712
0
                        if (_strict_mode && (_src_slot_descs_order_by_dest[dest_index]) &&
713
0
                            !_src_block_ptr->get_by_position(_dest_slot_to_src_slot_index[dest_index]).column->is_null_at(i)) {
714
0
                            filter_map[i] = false;
715
0
                            RETURN_IF_ERROR(_state->append_error_msg_to_file(
716
0
                                [&]() -> std::string {
717
0
                                    return _src_block_ptr->dump_one_line(i, _num_of_columns_from_file);
718
0
                                },
719
0
                                [&]() -> std::string {
720
0
                                    auto raw_value =
721
0
                                            _src_block_ptr->get_by_position(_dest_slot_to_src_slot_index[dest_index]).column->get_data_at(i);
722
0
                                    std::string raw_string = raw_value.to_string();
723
0
                                    fmt::memory_buffer error_msg;
724
0
                                    fmt::format_to(error_msg,"column({}) value is incorrect while strict mode is {}, src value is {}",
725
0
                                            slot_desc->col_name(), _strict_mode, raw_string);
726
0
                                    return fmt::to_string(error_msg);
727
0
                                }));
728
0
                        } else if (!slot_desc->is_nullable()) {
729
0
                            filter_map[i] = false;
730
0
                            RETURN_IF_ERROR(_state->append_error_msg_to_file(
731
0
                                [&]() -> std::string {
732
0
                                    return _src_block_ptr->dump_one_line(i, _num_of_columns_from_file);
733
0
                                },
734
0
                                [&]() -> std::string {
735
0
                                    fmt::memory_buffer error_msg;
736
0
                                    fmt::format_to(error_msg, "column({}) values is null while columns is not nullable", slot_desc->col_name());
737
0
                                    return fmt::to_string(error_msg);
738
0
                                }));
739
0
                        }
740
                        // clang-format on
741
0
                    }
742
0
                }
743
0
            }
744
0
            if (!slot_desc->is_nullable()) {
745
0
                column_ptr = remove_nullable(column_ptr);
746
0
            }
747
0
        } else if (slot_desc->is_nullable()) {
748
0
            column_ptr = make_nullable(column_ptr);
749
0
        }
750
0
        mutable_output_columns[j]->insert_range_from(*column_ptr, 0, rows);
751
0
        ctx_idx++;
752
0
    }
753
754
    // after do the dest block insert operation, clear _src_block to remove the reference of origin column
755
0
    _src_block_ptr->clear();
756
757
0
    size_t dest_size = block->columns();
758
    // do filter
759
0
    block->insert(ColumnWithTypeAndName(std::move(filter_column), std::make_shared<DataTypeUInt8>(),
760
0
                                        "filter column"));
761
0
    RETURN_IF_ERROR(Block::filter_block(block, dest_size, dest_size));
762
763
0
    _counter.num_rows_filtered += rows - block->rows();
764
0
    return Status::OK();
765
0
}
766
767
25
Status FileScanner::_process_src_block_after_read(Block* block) {
768
25
    DCHECK(_process_src_block_after_read_handler != nullptr);
769
25
    return (this->*_process_src_block_after_read_handler)(block);
770
25
}
771
772
25
Status FileScanner::_process_src_block_after_read_for_query(Block* block) {
773
    // Truncate CHAR/VARCHAR columns when target size is smaller than file schema.
774
    // This is needed for external table queries with truncate_char_or_varchar_columns=true.
775
25
    RETURN_IF_ERROR(_truncate_char_or_varchar_columns(block));
776
25
    return Status::OK();
777
25
}
778
779
0
Status FileScanner::_process_src_block_after_read_for_load(Block* block) {
780
    // Convert the src block columns type in-place.
781
0
    RETURN_IF_ERROR(_cast_to_input_block(block));
782
    // All readers fill partition and missing columns inside get_next_block:
783
    //   ORC/Parquet: in _do_get_next_block via on_fill_partition_columns/on_fill_missing_columns
784
    //   CSV/JSON/others: in on_after_read_block via fill_remaining_columns
785
    // Assert all columns have consistent row counts.
786
0
    if (_src_block_ptr->columns() > 0) {
787
0
        size_t rows = _src_block_ptr->get_by_position(0).column->size();
788
0
        for (size_t i = 1; i < _src_block_ptr->columns(); ++i) {
789
0
            DCHECK_EQ(_src_block_ptr->get_by_position(i).column->size(), rows)
790
0
                    << "Column " << _src_block_ptr->get_by_position(i).name << " has "
791
0
                    << _src_block_ptr->get_by_position(i).column->size() << " rows, expected "
792
0
                    << rows;
793
0
        }
794
0
    }
795
    // Apply _pre_conjunct_ctxs to filter src block.
796
0
    RETURN_IF_ERROR(_pre_filter_src_block());
797
798
    // Convert src block to output block (dest block), then apply filters.
799
0
    RETURN_IF_ERROR(_convert_to_output_block(block));
800
    // Truncate CHAR/VARCHAR columns when target size is smaller than file schema.
801
0
    RETURN_IF_ERROR(_truncate_char_or_varchar_columns(block));
802
0
    return Status::OK();
803
0
}
804
805
25
Status FileScanner::_truncate_char_or_varchar_columns(Block* block) {
806
    // Truncate char columns or varchar columns if size is smaller than file columns
807
    // or not found in the file column schema.
808
25
    if (!_state->query_options().truncate_char_or_varchar_columns) {
809
25
        return Status::OK();
810
25
    }
811
0
    int idx = 0;
812
0
    for (auto* slot_desc : _real_tuple_desc->slots()) {
813
0
        const auto& type = slot_desc->type();
814
0
        if (type->get_primitive_type() != TYPE_VARCHAR && type->get_primitive_type() != TYPE_CHAR) {
815
0
            ++idx;
816
0
            continue;
817
0
        }
818
0
        auto iter = _source_file_col_name_types.find(slot_desc->col_name());
819
0
        if (iter != _source_file_col_name_types.end()) {
820
0
            const auto file_type_desc = _source_file_col_name_types[slot_desc->col_name()];
821
0
            int l = -1;
822
0
            if (auto* ftype = check_and_get_data_type<DataTypeString>(
823
0
                        remove_nullable(file_type_desc).get())) {
824
0
                l = ftype->len();
825
0
            }
826
0
            if ((assert_cast<const DataTypeString*>(remove_nullable(type).get())->len() > 0) &&
827
0
                (assert_cast<const DataTypeString*>(remove_nullable(type).get())->len() < l ||
828
0
                 l < 0)) {
829
0
                _truncate_char_or_varchar_column(
830
0
                        block, idx,
831
0
                        assert_cast<const DataTypeString*>(remove_nullable(type).get())->len());
832
0
            }
833
0
        } else {
834
0
            _truncate_char_or_varchar_column(
835
0
                    block, idx,
836
0
                    assert_cast<const DataTypeString*>(remove_nullable(type).get())->len());
837
0
        }
838
0
        ++idx;
839
0
    }
840
0
    return Status::OK();
841
25
}
842
843
// VARCHAR substring(VARCHAR str, INT pos[, INT len])
844
0
void FileScanner::_truncate_char_or_varchar_column(Block* block, int idx, int len) {
845
0
    auto int_type = std::make_shared<DataTypeInt32>();
846
0
    uint32_t num_columns_without_result = block->columns();
847
0
    const ColumnNullable* col_nullable =
848
0
            assert_cast<const ColumnNullable*>(block->get_by_position(idx).column.get());
849
0
    const ColumnPtr& string_column_ptr = col_nullable->get_nested_column_ptr();
850
0
    ColumnPtr null_map_column_ptr = col_nullable->get_null_map_column_ptr();
851
0
    block->replace_by_position(idx, std::move(string_column_ptr));
852
0
    block->insert({int_type->create_column_const(block->rows(), to_field<TYPE_INT>(1)), int_type,
853
0
                   "const 1"}); // pos is 1
854
0
    block->insert({int_type->create_column_const(block->rows(), to_field<TYPE_INT>(len)), int_type,
855
0
                   fmt::format("const {}", len)});                          // len
856
0
    block->insert({nullptr, std::make_shared<DataTypeString>(), "result"}); // result column
857
0
    ColumnNumbers temp_arguments(3);
858
0
    temp_arguments[0] = idx;                            // str column
859
0
    temp_arguments[1] = num_columns_without_result;     // pos
860
0
    temp_arguments[2] = num_columns_without_result + 1; // len
861
0
    uint32_t result_column_id = num_columns_without_result + 2;
862
863
0
    SubstringUtil::substring_execute(*block, temp_arguments, result_column_id, block->rows());
864
0
    auto res = ColumnNullable::create(block->get_by_position(result_column_id).column,
865
0
                                      null_map_column_ptr);
866
0
    block->replace_by_position(idx, std::move(res));
867
0
    Block::erase_useless_column(block, num_columns_without_result);
868
0
}
869
870
0
std::shared_ptr<segment_v2::RowIdColumnIteratorV2> FileScanner::_create_row_id_column_iterator() {
871
0
    auto& id_file_map = _state->get_id_file_map();
872
0
    auto file_id = id_file_map->get_file_mapping_id(
873
0
            std::make_shared<FileMapping>(((FileScanLocalState*)_local_state)->parent_id(),
874
0
                                          _current_range, _should_enable_file_meta_cache()));
875
0
    return std::make_shared<RowIdColumnIteratorV2>(IdManager::ID_VERSION,
876
0
                                                   BackendOptions::get_backend_id(), file_id);
877
0
}
878
879
26
void FileScanner::_fill_base_init_context(ReaderInitContext* ctx) {
880
26
    ctx->column_descs = &_column_descs;
881
26
    ctx->col_name_to_block_idx = &_src_block_name_to_idx;
882
26
    ctx->state = _state;
883
26
    ctx->tuple_descriptor = _real_tuple_desc;
884
26
    ctx->row_descriptor = _default_val_row_desc.get();
885
26
    ctx->params = _params;
886
26
    ctx->range = &_current_range;
887
26
    ctx->table_info_node = TableSchemaChangeHelper::ConstNode::get_instance();
888
26
    ctx->push_down_agg_type = _get_push_down_agg_type();
889
26
}
890
891
1
Status FileScanner::_get_next_reader() {
892
1
    while (true) {
893
1
        if (_cur_reader) {
894
0
            _cur_reader->collect_profile_before_close();
895
0
            RETURN_IF_ERROR(_cur_reader->close());
896
0
            _state->update_num_finished_scan_range(1);
897
0
        }
898
1
        _cur_reader.reset(nullptr);
899
1
        _src_block_init = false;
900
1
        bool has_next = _first_scan_range;
901
1
        if (!_first_scan_range) {
902
1
            RETURN_IF_ERROR(_split_source->get_next(&has_next, &_current_range));
903
1
        }
904
1
        _first_scan_range = false;
905
1
        if (!has_next || _should_stop) {
906
0
            _scanner_eof = true;
907
0
            return Status::OK();
908
0
        }
909
910
1
        const TFileRangeDesc& range = _current_range;
911
1
        _current_range_path = range.path;
912
913
1
        if (!_partition_slot_index_map.empty()) {
914
            // we need get partition columns first for runtime filter partition pruning
915
0
            RETURN_IF_ERROR(_generate_partition_columns());
916
917
0
            if (_state->query_options().enable_runtime_filter_partition_prune) {
918
                // if enable_runtime_filter_partition_prune is true, we need to check whether this range can be filtered out
919
                // by runtime filter partition prune
920
0
                if (_push_down_conjuncts.size() < _conjuncts.size()) {
921
                    // there are new runtime filters, need to re-init runtime filter partition pruning ctxs
922
0
                    _init_runtime_filter_partition_prune_ctxs();
923
0
                }
924
925
0
                bool can_filter_all = false;
926
0
                RETURN_IF_ERROR(_process_runtime_filters_partition_prune(can_filter_all));
927
0
                if (can_filter_all) {
928
                    // this range can be filtered out by runtime filter partition pruning
929
                    // so we need to skip this range
930
0
                    COUNTER_UPDATE(_runtime_filter_partition_pruned_range_counter, 1);
931
0
                    continue;
932
0
                }
933
0
            }
934
0
        }
935
936
        // create reader for specific format
937
1
        Status init_status = Status::OK();
938
1
        TFileFormatType::type format_type = _get_current_format_type();
939
        // for compatibility, this logic is deprecated in 3.1
940
1
        if (format_type == TFileFormatType::FORMAT_JNI && range.__isset.table_format_params) {
941
0
            if (range.table_format_params.table_format_type == "paimon" &&
942
0
                !range.table_format_params.paimon_params.__isset.paimon_split) {
943
                // use native reader
944
0
                auto format = range.table_format_params.paimon_params.file_format;
945
0
                if (format == "orc") {
946
0
                    format_type = TFileFormatType::FORMAT_ORC;
947
0
                } else if (format == "parquet") {
948
0
                    format_type = TFileFormatType::FORMAT_PARQUET;
949
0
                } else {
950
0
                    return Status::InternalError("Not supported paimon file format: {}", format);
951
0
                }
952
0
            }
953
0
        }
954
955
1
        bool push_down_predicates = _should_push_down_predicates(format_type);
956
1
        bool need_to_get_parsed_schema = false;
957
1
        switch (format_type) {
958
1
        case TFileFormatType::FORMAT_JNI: {
959
1
            ReaderInitContext jni_ctx;
960
1
            _fill_base_init_context(&jni_ctx);
961
962
1
            if (range.__isset.table_format_params &&
963
1
                range.table_format_params.table_format_type == "max_compute") {
964
0
                const auto* mc_desc = static_cast<const MaxComputeTableDescriptor*>(
965
0
                        _real_tuple_desc->table_desc());
966
0
                if (!mc_desc->init_status()) {
967
0
                    return mc_desc->init_status();
968
0
                }
969
0
                std::unique_ptr<MaxComputeJniReader> mc_reader = MaxComputeJniReader::create_unique(
970
0
                        mc_desc, range.table_format_params.max_compute_params, _file_slot_descs,
971
0
                        range, _state, _profile);
972
0
                init_status = static_cast<GenericReader*>(mc_reader.get())->init_reader(&jni_ctx);
973
0
                _cur_reader = std::move(mc_reader);
974
1
            } else if (range.__isset.table_format_params &&
975
1
                       range.table_format_params.table_format_type == "paimon") {
976
0
                if (_state->query_options().__isset.enable_paimon_cpp_reader &&
977
0
                    _state->query_options().enable_paimon_cpp_reader) {
978
0
                    auto cpp_reader = PaimonCppReader::create_unique(_file_slot_descs, _state,
979
0
                                                                     _profile, range, _params);
980
0
                    if (!_is_load && !_push_down_conjuncts.empty()) {
981
0
                        PaimonPredicateConverter predicate_converter(_file_slot_descs, _state);
982
0
                        auto predicate = predicate_converter.build(_push_down_conjuncts);
983
0
                        if (predicate) {
984
0
                            cpp_reader->set_predicate(std::move(predicate));
985
0
                        }
986
0
                    }
987
0
                    init_status =
988
0
                            static_cast<GenericReader*>(cpp_reader.get())->init_reader(&jni_ctx);
989
0
                    _cur_reader = std::move(cpp_reader);
990
0
                } else {
991
0
                    auto paimon_reader = PaimonJniReader::create_unique(_file_slot_descs, _state,
992
0
                                                                        _profile, range, _params);
993
0
                    init_status =
994
0
                            static_cast<GenericReader*>(paimon_reader.get())->init_reader(&jni_ctx);
995
0
                    _cur_reader = std::move(paimon_reader);
996
0
                }
997
1
            } else if (range.__isset.table_format_params &&
998
1
                       range.table_format_params.table_format_type == "hudi") {
999
0
                auto hudi_reader = HudiJniReader::create_unique(
1000
0
                        *_params, range.table_format_params.hudi_params, _file_slot_descs, _state,
1001
0
                        _profile);
1002
0
                init_status = static_cast<GenericReader*>(hudi_reader.get())->init_reader(&jni_ctx);
1003
0
                _cur_reader = std::move(hudi_reader);
1004
1
            } else if (range.__isset.table_format_params &&
1005
1
                       range.table_format_params.table_format_type == "trino_connector") {
1006
0
                auto trino_reader = TrinoConnectorJniReader::create_unique(_file_slot_descs, _state,
1007
0
                                                                           _profile, range);
1008
0
                init_status =
1009
0
                        static_cast<GenericReader*>(trino_reader.get())->init_reader(&jni_ctx);
1010
0
                _cur_reader = std::move(trino_reader);
1011
1
            } else if (range.__isset.table_format_params &&
1012
1
                       range.table_format_params.table_format_type == "jdbc") {
1013
                // Extract jdbc params from table_format_params
1014
0
                std::map<std::string, std::string> jdbc_params(
1015
0
                        range.table_format_params.jdbc_params.begin(),
1016
0
                        range.table_format_params.jdbc_params.end());
1017
0
                auto jdbc_reader = JdbcJniReader::create_unique(_file_slot_descs, _state, _profile,
1018
0
                                                                jdbc_params);
1019
0
                init_status = static_cast<GenericReader*>(jdbc_reader.get())->init_reader(&jni_ctx);
1020
0
                _cur_reader = std::move(jdbc_reader);
1021
1
            } else if (range.__isset.table_format_params &&
1022
1
                       range.table_format_params.table_format_type == "iceberg") {
1023
0
                auto iceberg_sys_reader = IcebergSysTableJniReader::create_unique(
1024
0
                        _file_slot_descs, _state, _profile, range, _params);
1025
0
                init_status = static_cast<GenericReader*>(iceberg_sys_reader.get())
1026
0
                                      ->init_reader(&jni_ctx);
1027
0
                _cur_reader = std::move(iceberg_sys_reader);
1028
0
            }
1029
            // Set col_name_to_block_idx for JNI readers to avoid repeated map creation
1030
1
            if (_cur_reader) {
1031
0
                if (auto* jni_reader = dynamic_cast<JniReader*>(_cur_reader.get())) {
1032
0
                    jni_reader->set_col_name_to_block_idx(&_src_block_name_to_idx);
1033
0
                }
1034
0
            }
1035
1
            break;
1036
1
        }
1037
0
        case TFileFormatType::FORMAT_PARQUET: {
1038
0
            auto file_meta_cache_ptr = _should_enable_file_meta_cache()
1039
0
                                               ? ExecEnv::GetInstance()->file_meta_cache()
1040
0
                                               : nullptr;
1041
0
            if (push_down_predicates) {
1042
0
                RETURN_IF_ERROR(_process_late_arrival_conjuncts());
1043
0
            }
1044
0
            RETURN_IF_ERROR(_init_parquet_reader(file_meta_cache_ptr));
1045
1046
0
            need_to_get_parsed_schema = true;
1047
0
            break;
1048
0
        }
1049
0
        case TFileFormatType::FORMAT_ORC: {
1050
0
            auto file_meta_cache_ptr = _should_enable_file_meta_cache()
1051
0
                                               ? ExecEnv::GetInstance()->file_meta_cache()
1052
0
                                               : nullptr;
1053
0
            if (push_down_predicates) {
1054
0
                RETURN_IF_ERROR(_process_late_arrival_conjuncts());
1055
0
            }
1056
0
            RETURN_IF_ERROR(_init_orc_reader(file_meta_cache_ptr));
1057
1058
0
            need_to_get_parsed_schema = true;
1059
0
            break;
1060
0
        }
1061
0
        case TFileFormatType::FORMAT_CSV_PLAIN:
1062
0
        case TFileFormatType::FORMAT_CSV_GZ:
1063
0
        case TFileFormatType::FORMAT_CSV_BZ2:
1064
0
        case TFileFormatType::FORMAT_CSV_LZ4FRAME:
1065
0
        case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
1066
0
        case TFileFormatType::FORMAT_CSV_LZOP:
1067
0
        case TFileFormatType::FORMAT_CSV_DEFLATE:
1068
0
        case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
1069
0
        case TFileFormatType::FORMAT_PROTO: {
1070
0
            auto reader = CsvReader::create_unique(_state, _profile, &_counter, *_params, range,
1071
0
                                                   _file_slot_descs, _io_ctx.get());
1072
0
            CsvInitContext csv_ctx;
1073
0
            _fill_base_init_context(&csv_ctx);
1074
0
            csv_ctx.is_load = _is_load;
1075
0
            init_status = static_cast<GenericReader*>(reader.get())->init_reader(&csv_ctx);
1076
0
            _cur_reader = std::move(reader);
1077
0
            break;
1078
0
        }
1079
0
        case TFileFormatType::FORMAT_TEXT: {
1080
0
            auto reader = TextReader::create_unique(_state, _profile, &_counter, *_params, range,
1081
0
                                                    _file_slot_descs, _io_ctx.get());
1082
0
            CsvInitContext text_ctx;
1083
0
            _fill_base_init_context(&text_ctx);
1084
0
            text_ctx.is_load = _is_load;
1085
0
            init_status = static_cast<GenericReader*>(reader.get())->init_reader(&text_ctx);
1086
0
            _cur_reader = std::move(reader);
1087
0
            break;
1088
0
        }
1089
0
        case TFileFormatType::FORMAT_JSON: {
1090
0
            _cur_reader =
1091
0
                    NewJsonReader::create_unique(_state, _profile, &_counter, *_params, range,
1092
0
                                                 _file_slot_descs, &_scanner_eof, _io_ctx.get());
1093
0
            JsonInitContext json_ctx;
1094
0
            _fill_base_init_context(&json_ctx);
1095
0
            json_ctx.col_default_value_ctx = &_col_default_value_ctx;
1096
0
            json_ctx.is_load = _is_load;
1097
0
            init_status = _cur_reader->init_reader(&json_ctx);
1098
0
            break;
1099
0
        }
1100
1101
0
        case TFileFormatType::FORMAT_WAL: {
1102
0
            _cur_reader = WalReader::create_unique(_state);
1103
0
            WalInitContext wal_ctx;
1104
0
            _fill_base_init_context(&wal_ctx);
1105
0
            wal_ctx.output_tuple_descriptor = _output_tuple_desc;
1106
0
            init_status = _cur_reader->init_reader(&wal_ctx);
1107
0
            break;
1108
0
        }
1109
0
        case TFileFormatType::FORMAT_NATIVE: {
1110
0
            auto reader =
1111
0
                    NativeReader::create_unique(_profile, *_params, range, _io_ctx.get(), _state);
1112
0
            ReaderInitContext native_ctx;
1113
0
            _fill_base_init_context(&native_ctx);
1114
0
            init_status = static_cast<GenericReader*>(reader.get())->init_reader(&native_ctx);
1115
0
            _cur_reader = std::move(reader);
1116
0
            need_to_get_parsed_schema = false;
1117
0
            break;
1118
0
        }
1119
0
        case TFileFormatType::FORMAT_ARROW: {
1120
0
            ReaderInitContext arrow_ctx;
1121
0
            _fill_base_init_context(&arrow_ctx);
1122
1123
0
            if (range.__isset.table_format_params &&
1124
0
                range.table_format_params.table_format_type == "remote_doris") {
1125
0
                auto doris_reader =
1126
0
                        RemoteDorisReader::create_unique(_file_slot_descs, _state, _profile, range);
1127
0
                init_status =
1128
0
                        static_cast<GenericReader*>(doris_reader.get())->init_reader(&arrow_ctx);
1129
0
                if (doris_reader) {
1130
0
                    doris_reader->set_col_name_to_block_idx(&_src_block_name_to_idx);
1131
0
                }
1132
0
                _cur_reader = std::move(doris_reader);
1133
0
            } else {
1134
0
                auto arrow_reader =
1135
0
                        ArrowStreamReader::create_unique(_state, _profile, &_counter, *_params,
1136
0
                                                         range, _file_slot_descs, _io_ctx.get());
1137
0
                init_status =
1138
0
                        static_cast<GenericReader*>(arrow_reader.get())->init_reader(&arrow_ctx);
1139
0
                _cur_reader = std::move(arrow_reader);
1140
0
            }
1141
0
            break;
1142
0
        }
1143
0
        default:
1144
0
            return Status::NotSupported("Not supported create reader for file format: {}.",
1145
0
                                        to_string(_params->format_type));
1146
1
        }
1147
1148
1
        if (_cur_reader == nullptr) {
1149
1
            return Status::NotSupported(
1150
1
                    "Not supported create reader for table format: {} / file format: {}.",
1151
1
                    range.__isset.table_format_params ? range.table_format_params.table_format_type
1152
1
                                                      : "NotSet",
1153
1
                    to_string(_params->format_type));
1154
1
        }
1155
0
        COUNTER_UPDATE(_file_counter, 1);
1156
        // The FileScanner for external table may try to open not exist files,
1157
        // Because FE file cache for external table may out of date.
1158
        // So, NOT_FOUND for FileScanner is not a fail case.
1159
        // Will remove this after file reader refactor.
1160
0
        if (init_status.is<END_OF_FILE>()) {
1161
0
            COUNTER_UPDATE(_empty_file_counter, 1);
1162
0
            continue;
1163
0
        } else if (init_status.is<ErrorCode::NOT_FOUND>()) {
1164
0
            if (config::ignore_not_found_file_in_external_table) {
1165
0
                COUNTER_UPDATE(_not_found_file_counter, 1);
1166
0
                continue;
1167
0
            }
1168
0
            return Status::InternalError("failed to find reader, err: {}", init_status.to_string());
1169
0
        } else if (!init_status.ok()) {
1170
0
            return Status::InternalError("failed to init reader, err: {}", init_status.to_string());
1171
0
        }
1172
1173
        // For table-level COUNT pushdown, offsets are undefined so we must skip
1174
        // _set_fill_or_truncate_columns (it uses [start_offset, end_offset] to
1175
        // filter row groups, which would produce incorrect empty results).
1176
0
        bool is_table_level_count = _get_push_down_agg_type() == TPushAggOp::type::COUNT &&
1177
0
                                    range.__isset.table_format_params &&
1178
0
                                    range.table_format_params.table_level_row_count >= 0;
1179
0
        if (!is_table_level_count) {
1180
0
            Status status = _set_fill_or_truncate_columns(need_to_get_parsed_schema);
1181
0
            if (status.is<END_OF_FILE>()) { // all parquet row groups are filtered
1182
0
                continue;
1183
0
            } else if (!status.ok()) {
1184
0
                return Status::InternalError("failed to set_fill_or_truncate_columns, err: {}",
1185
0
                                             status.to_string());
1186
0
            }
1187
0
        }
1188
1189
        // Unified COUNT(*) pushdown: replace the real reader with CountReader
1190
        // decorator if the reader accepts COUNT and can provide a total row count.
1191
0
        if (_cur_reader->get_push_down_agg_type() == TPushAggOp::type::COUNT) {
1192
0
            int64_t total_rows = -1;
1193
0
            if (is_table_level_count) {
1194
                // FE-provided count (may account for table-format deletions)
1195
0
                total_rows = range.table_format_params.table_level_row_count;
1196
0
            } else if (_cur_reader->supports_count_pushdown()) {
1197
                // File metadata count (ORC footer / Parquet row groups)
1198
0
                total_rows = _cur_reader->get_total_rows();
1199
0
            }
1200
0
            if (total_rows >= 0) {
1201
0
                auto batch_size = _state->query_options().batch_size;
1202
0
                _cur_reader = std::make_unique<CountReader>(total_rows, batch_size,
1203
0
                                                            std::move(_cur_reader));
1204
0
            }
1205
0
        }
1206
0
        _cur_reader_eof = false;
1207
0
        break;
1208
0
    }
1209
0
    return Status::OK();
1210
1
}
1211
1212
Status FileScanner::_init_parquet_reader(FileMetaCache* file_meta_cache_ptr,
1213
14
                                         std::unique_ptr<ParquetReader> parquet_reader) {
1214
14
    const TFileRangeDesc& range = _current_range;
1215
14
    Status init_status = Status::OK();
1216
1217
14
    phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> slot_id_to_predicates =
1218
14
            _local_state
1219
14
                    ? _local_state->cast<FileScanLocalState>()._slot_id_to_predicates
1220
14
                    : phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> {};
1221
1222
    // Build unified ParquetInitContext (shared by all Parquet reader variants)
1223
14
    ParquetInitContext pctx;
1224
14
    _fill_base_init_context(&pctx);
1225
14
    pctx.conjuncts = &_push_down_conjuncts;
1226
14
    pctx.slot_id_to_predicates = &slot_id_to_predicates;
1227
14
    pctx.colname_to_slot_id = _col_name_to_slot_id;
1228
14
    pctx.not_single_slot_filter_conjuncts = &_not_single_slot_filter_conjuncts;
1229
14
    pctx.slot_id_to_filter_conjuncts = &_slot_id_to_filter_conjuncts;
1230
1231
14
    if (range.__isset.table_format_params &&
1232
14
        range.table_format_params.table_format_type == "iceberg") {
1233
        // IcebergParquetReader IS-A ParquetReader (CRTP mixin), no wrapping needed
1234
0
        std::unique_ptr<IcebergParquetReader> iceberg_reader = IcebergParquetReader::create_unique(
1235
0
                _kv_cache, _profile, *_params, range, _state->query_options().batch_size,
1236
0
                &_state->timezone_obj(), _io_ctx.get(), _state, file_meta_cache_ptr);
1237
0
        iceberg_reader->set_create_row_id_column_iterator_func(
1238
0
                [this]() -> std::shared_ptr<segment_v2::RowIdColumnIteratorV2> {
1239
0
                    return _create_row_id_column_iterator();
1240
0
                });
1241
0
        init_status = static_cast<GenericReader*>(iceberg_reader.get())->init_reader(&pctx);
1242
0
        _cur_reader = std::move(iceberg_reader);
1243
14
    } else if (range.__isset.table_format_params &&
1244
14
               range.table_format_params.table_format_type == "paimon") {
1245
        // PaimonParquetReader IS-A ParquetReader, no wrapping needed
1246
0
        auto paimon_reader = PaimonParquetReader::create_unique(
1247
0
                _profile, *_params, range, _state->query_options().batch_size,
1248
0
                &_state->timezone_obj(), _kv_cache, _io_ctx.get(), _state, file_meta_cache_ptr);
1249
0
        init_status = static_cast<GenericReader*>(paimon_reader.get())->init_reader(&pctx);
1250
0
        _cur_reader = std::move(paimon_reader);
1251
14
    } else if (range.__isset.table_format_params &&
1252
14
               range.table_format_params.table_format_type == "hudi") {
1253
        // HudiParquetReader IS-A ParquetReader, no wrapping needed
1254
0
        auto hudi_reader = HudiParquetReader::create_unique(
1255
0
                _profile, *_params, range, _state->query_options().batch_size,
1256
0
                &_state->timezone_obj(), _io_ctx.get(), _state, file_meta_cache_ptr);
1257
0
        init_status = static_cast<GenericReader*>(hudi_reader.get())->init_reader(&pctx);
1258
0
        _cur_reader = std::move(hudi_reader);
1259
14
    } else if (range.table_format_params.table_format_type == "hive") {
1260
14
        auto hive_reader = HiveParquetReader::create_unique(
1261
14
                _profile, *_params, range, _state->query_options().batch_size,
1262
14
                &_state->timezone_obj(), _io_ctx.get(), _state, &_is_file_slot, file_meta_cache_ptr,
1263
14
                _state->query_options().enable_parquet_lazy_mat);
1264
14
        hive_reader->set_create_row_id_column_iterator_func(
1265
14
                [this]() -> std::shared_ptr<segment_v2::RowIdColumnIteratorV2> {
1266
0
                    return _create_row_id_column_iterator();
1267
0
                });
1268
14
        init_status = static_cast<GenericReader*>(hive_reader.get())->init_reader(&pctx);
1269
14
        _cur_reader = std::move(hive_reader);
1270
14
    } else if (range.table_format_params.table_format_type == "tvf") {
1271
0
        if (!parquet_reader) {
1272
0
            parquet_reader = ParquetReader::create_unique(
1273
0
                    _profile, *_params, range, _state->query_options().batch_size,
1274
0
                    &_state->timezone_obj(), _io_ctx.get(), _state, file_meta_cache_ptr,
1275
0
                    _state->query_options().enable_parquet_lazy_mat);
1276
0
        }
1277
0
        parquet_reader->set_create_row_id_column_iterator_func(
1278
0
                [this]() -> std::shared_ptr<segment_v2::RowIdColumnIteratorV2> {
1279
0
                    return _create_row_id_column_iterator();
1280
0
                });
1281
0
        init_status = static_cast<GenericReader*>(parquet_reader.get())->init_reader(&pctx);
1282
0
        _cur_reader = std::move(parquet_reader);
1283
0
    } else if (_is_load) {
1284
0
        if (!parquet_reader) {
1285
0
            parquet_reader = ParquetReader::create_unique(
1286
0
                    _profile, *_params, range, _state->query_options().batch_size,
1287
0
                    &_state->timezone_obj(), _io_ctx.get(), _state, file_meta_cache_ptr,
1288
0
                    _state->query_options().enable_parquet_lazy_mat);
1289
0
        }
1290
0
        init_status = static_cast<GenericReader*>(parquet_reader.get())->init_reader(&pctx);
1291
0
        _cur_reader = std::move(parquet_reader);
1292
0
    }
1293
1294
14
    return init_status;
1295
14
}
1296
1297
Status FileScanner::_init_orc_reader(FileMetaCache* file_meta_cache_ptr,
1298
11
                                     std::unique_ptr<OrcReader> orc_reader) {
1299
11
    const TFileRangeDesc& range = _current_range;
1300
11
    Status init_status = Status::OK();
1301
1302
    // Build unified OrcInitContext (shared by all ORC reader variants)
1303
11
    OrcInitContext octx;
1304
11
    _fill_base_init_context(&octx);
1305
11
    octx.conjuncts = &_push_down_conjuncts;
1306
11
    octx.not_single_slot_filter_conjuncts = &_not_single_slot_filter_conjuncts;
1307
11
    octx.slot_id_to_filter_conjuncts = &_slot_id_to_filter_conjuncts;
1308
1309
11
    if (range.__isset.table_format_params &&
1310
11
        range.table_format_params.table_format_type == "transactional_hive") {
1311
        // TransactionalHiveReader IS-A OrcReader, no wrapping needed
1312
0
        auto tran_orc_reader = TransactionalHiveReader::create_unique(
1313
0
                _profile, _state, *_params, range, _state->query_options().batch_size,
1314
0
                _state->timezone(), _io_ctx.get(), file_meta_cache_ptr);
1315
0
        tran_orc_reader->set_create_row_id_column_iterator_func(
1316
0
                [this]() -> std::shared_ptr<segment_v2::RowIdColumnIteratorV2> {
1317
0
                    return _create_row_id_column_iterator();
1318
0
                });
1319
0
        init_status = static_cast<GenericReader*>(tran_orc_reader.get())->init_reader(&octx);
1320
1321
0
        _cur_reader = std::move(tran_orc_reader);
1322
11
    } else if (range.__isset.table_format_params &&
1323
11
               range.table_format_params.table_format_type == "iceberg") {
1324
        // IcebergOrcReader IS-A OrcReader (CRTP mixin), no wrapping needed
1325
0
        std::unique_ptr<IcebergOrcReader> iceberg_reader = IcebergOrcReader::create_unique(
1326
0
                _kv_cache, _profile, _state, *_params, range, _state->query_options().batch_size,
1327
0
                _state->timezone(), _io_ctx.get(), file_meta_cache_ptr);
1328
0
        iceberg_reader->set_create_row_id_column_iterator_func(
1329
0
                [this]() -> std::shared_ptr<segment_v2::RowIdColumnIteratorV2> {
1330
0
                    return _create_row_id_column_iterator();
1331
0
                });
1332
0
        init_status = static_cast<GenericReader*>(iceberg_reader.get())->init_reader(&octx);
1333
1334
0
        _cur_reader = std::move(iceberg_reader);
1335
11
    } else if (range.__isset.table_format_params &&
1336
11
               range.table_format_params.table_format_type == "paimon") {
1337
        // PaimonOrcReader IS-A OrcReader, no wrapping needed
1338
0
        auto paimon_reader = PaimonOrcReader::create_unique(
1339
0
                _profile, _state, *_params, range, _state->query_options().batch_size,
1340
0
                _state->timezone(), _kv_cache, _io_ctx.get(), file_meta_cache_ptr);
1341
0
        init_status = static_cast<GenericReader*>(paimon_reader.get())->init_reader(&octx);
1342
1343
0
        _cur_reader = std::move(paimon_reader);
1344
11
    } else if (range.__isset.table_format_params &&
1345
11
               range.table_format_params.table_format_type == "hudi") {
1346
        // HudiOrcReader IS-A OrcReader, no wrapping needed
1347
0
        auto hudi_reader = HudiOrcReader::create_unique(
1348
0
                _profile, _state, *_params, range, _state->query_options().batch_size,
1349
0
                _state->timezone(), _io_ctx.get(), file_meta_cache_ptr);
1350
0
        init_status = static_cast<GenericReader*>(hudi_reader.get())->init_reader(&octx);
1351
1352
0
        _cur_reader = std::move(hudi_reader);
1353
11
    } else if (range.__isset.table_format_params &&
1354
11
               range.table_format_params.table_format_type == "hive") {
1355
11
        auto hive_reader = HiveOrcReader::create_unique(
1356
11
                _profile, _state, *_params, range, _state->query_options().batch_size,
1357
11
                _state->timezone(), _io_ctx.get(), &_is_file_slot, file_meta_cache_ptr,
1358
11
                _state->query_options().enable_orc_lazy_mat);
1359
11
        hive_reader->set_create_row_id_column_iterator_func(
1360
11
                [this]() -> std::shared_ptr<segment_v2::RowIdColumnIteratorV2> {
1361
0
                    return _create_row_id_column_iterator();
1362
0
                });
1363
11
        init_status = static_cast<GenericReader*>(hive_reader.get())->init_reader(&octx);
1364
1365
11
        _cur_reader = std::move(hive_reader);
1366
11
    } else if (range.__isset.table_format_params &&
1367
0
               range.table_format_params.table_format_type == "tvf") {
1368
0
        if (!orc_reader) {
1369
0
            orc_reader = OrcReader::create_unique(
1370
0
                    _profile, _state, *_params, range, _state->query_options().batch_size,
1371
0
                    _state->timezone(), _io_ctx.get(), file_meta_cache_ptr,
1372
0
                    _state->query_options().enable_orc_lazy_mat);
1373
0
        }
1374
0
        orc_reader->set_create_row_id_column_iterator_func(
1375
0
                [this]() -> std::shared_ptr<segment_v2::RowIdColumnIteratorV2> {
1376
0
                    return _create_row_id_column_iterator();
1377
0
                });
1378
0
        init_status = static_cast<GenericReader*>(orc_reader.get())->init_reader(&octx);
1379
0
        _cur_reader = std::move(orc_reader);
1380
0
    } else if (_is_load) {
1381
0
        if (!orc_reader) {
1382
0
            orc_reader = OrcReader::create_unique(
1383
0
                    _profile, _state, *_params, range, _state->query_options().batch_size,
1384
0
                    _state->timezone(), _io_ctx.get(), file_meta_cache_ptr,
1385
0
                    _state->query_options().enable_orc_lazy_mat);
1386
0
        }
1387
0
        init_status = static_cast<GenericReader*>(orc_reader.get())->init_reader(&octx);
1388
0
        _cur_reader = std::move(orc_reader);
1389
0
    }
1390
1391
11
    return init_status;
1392
11
}
1393
1394
25
Status FileScanner::_set_fill_or_truncate_columns(bool need_to_get_parsed_schema) {
1395
25
    _slot_lower_name_to_col_type.clear();
1396
1397
25
    std::unordered_map<std::string, DataTypePtr> name_to_col_type;
1398
25
    RETURN_IF_ERROR(_cur_reader->get_columns(&name_to_col_type));
1399
1400
309
    for (const auto& [col_name, col_type] : name_to_col_type) {
1401
309
        auto col_name_lower = to_lower(col_name);
1402
309
        if (_partition_col_descs.contains(col_name_lower)) {
1403
            /*
1404
             * `_slot_lower_name_to_col_type` is used by `_init_src_block` and `_cast_to_input_block` during LOAD to
1405
             * generate columns of the corresponding type, which records the columns existing in the file.
1406
             *
1407
             * When a column in `COLUMNS FROM PATH` exists in a file column, the column type in the block will
1408
             * not match the slot type in `_output_tuple_desc`, causing an error when
1409
             * Serde `deserialize_one_cell_from_json` fills the partition values.
1410
             *
1411
             * So for partition column not need fill _slot_lower_name_to_col_type.
1412
             */
1413
0
            continue;
1414
0
        }
1415
309
        _slot_lower_name_to_col_type.emplace(col_name_lower, col_type);
1416
309
    }
1417
1418
25
    RETURN_IF_ERROR(_generate_truncate_columns(need_to_get_parsed_schema));
1419
25
    return Status::OK();
1420
25
}
1421
1422
25
Status FileScanner::_generate_truncate_columns(bool need_to_get_parsed_schema) {
1423
25
    _source_file_col_name_types.clear();
1424
    //  The col names and types of source file, such as parquet, orc files.
1425
25
    if (_state->query_options().truncate_char_or_varchar_columns && need_to_get_parsed_schema) {
1426
0
        std::vector<std::string> source_file_col_names;
1427
0
        std::vector<DataTypePtr> source_file_col_types;
1428
0
        Status status =
1429
0
                _cur_reader->get_parsed_schema(&source_file_col_names, &source_file_col_types);
1430
0
        if (!status.ok() && status.code() != TStatusCode::NOT_IMPLEMENTED_ERROR) {
1431
0
            return status;
1432
0
        }
1433
0
        DCHECK_EQ(source_file_col_names.size(), source_file_col_types.size());
1434
0
        for (int i = 0; i < source_file_col_names.size(); ++i) {
1435
0
            _source_file_col_name_types[to_lower(source_file_col_names[i])] =
1436
0
                    source_file_col_types[i];
1437
0
        }
1438
0
    }
1439
25
    return Status::OK();
1440
25
}
1441
1442
16
Status FileScanner::prepare_for_read_lines(const TFileRangeDesc& range) {
1443
16
    _current_range = range;
1444
1445
16
    _file_cache_statistics.reset(new io::FileCacheStatistics());
1446
16
    _file_reader_stats.reset(new io::FileReaderStats());
1447
1448
16
    _file_read_bytes_counter =
1449
16
            ADD_COUNTER_WITH_LEVEL(_profile, FileReadBytesProfile, TUnit::BYTES, 1);
1450
16
    _file_read_time_counter = ADD_TIMER_WITH_LEVEL(_profile, FileReadTimeProfile, 1);
1451
1452
16
    RETURN_IF_ERROR(_init_io_ctx());
1453
16
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
1454
16
    _io_ctx->file_reader_stats = _file_reader_stats.get();
1455
16
    _default_val_row_desc.reset(new RowDescriptor((TupleDescriptor*)_real_tuple_desc));
1456
16
    RETURN_IF_ERROR(_init_expr_ctxes());
1457
1458
    // Since only one column is read from the file, there is no need to filter, so set these variables to empty.
1459
16
    _push_down_conjuncts.clear();
1460
16
    _not_single_slot_filter_conjuncts.clear();
1461
16
    _slot_id_to_filter_conjuncts.clear();
1462
16
    _kv_cache = nullptr;
1463
16
    return Status::OK();
1464
16
}
1465
1466
Status FileScanner::read_lines_from_range(const TFileRangeDesc& range,
1467
                                          const std::list<int64_t>& row_ids, Block* result_block,
1468
                                          const ExternalFileMappingInfo& external_info,
1469
25
                                          int64_t* init_reader_ms, int64_t* get_block_ms) {
1470
25
    _current_range = range;
1471
25
    RETURN_IF_ERROR(_generate_partition_columns());
1472
1473
25
    TFileFormatType::type format_type = _get_current_format_type();
1474
25
    Status init_status = Status::OK();
1475
1476
25
    auto file_meta_cache_ptr = external_info.enable_file_meta_cache
1477
25
                                       ? ExecEnv::GetInstance()->file_meta_cache()
1478
25
                                       : nullptr;
1479
1480
25
    RETURN_IF_ERROR(scope_timer_run(
1481
25
            [&]() -> Status {
1482
25
                switch (format_type) {
1483
25
                case TFileFormatType::FORMAT_PARQUET: {
1484
25
                    std::unique_ptr<ParquetReader> parquet_reader = ParquetReader::create_unique(
1485
25
                            _profile, *_params, range, 1, &_state->timezone_obj(), _io_ctx.get(),
1486
25
                            _state, file_meta_cache_ptr, false);
1487
25
                    RETURN_IF_ERROR(
1488
25
                            _init_parquet_reader(file_meta_cache_ptr, std::move(parquet_reader)));
1489
                    // _init_parquet_reader may create a new table-format specific reader
1490
                    // (e.g., HiveParquetReader) that replaces the original parquet_reader.
1491
                    // We need to re-apply read_by_rows to the actual _cur_reader.
1492
25
                    RETURN_IF_ERROR(_cur_reader->read_by_rows(row_ids));
1493
25
                    break;
1494
25
                }
1495
25
                case TFileFormatType::FORMAT_ORC: {
1496
25
                    std::unique_ptr<OrcReader> orc_reader = OrcReader::create_unique(
1497
25
                            _profile, _state, *_params, range, 1, _state->timezone(), _io_ctx.get(),
1498
25
                            file_meta_cache_ptr, false);
1499
25
                    RETURN_IF_ERROR(_init_orc_reader(file_meta_cache_ptr, std::move(orc_reader)));
1500
                    // Same as above: re-apply read_by_rows to the actual _cur_reader.
1501
25
                    RETURN_IF_ERROR(_cur_reader->read_by_rows(row_ids));
1502
25
                    break;
1503
25
                }
1504
25
                default: {
1505
25
                    return Status::NotSupported(
1506
25
                            "Not support create lines reader for file format: {},"
1507
25
                            "only support parquet and orc.",
1508
25
                            to_string(_params->format_type));
1509
25
                }
1510
25
                }
1511
25
                return Status::OK();
1512
25
            },
1513
25
            init_reader_ms));
1514
1515
25
    RETURN_IF_ERROR(_set_fill_or_truncate_columns(true));
1516
25
    _cur_reader_eof = false;
1517
1518
25
    RETURN_IF_ERROR(scope_timer_run(
1519
25
            [&]() -> Status {
1520
25
                while (!_cur_reader_eof) {
1521
25
                    bool eof = false;
1522
25
                    RETURN_IF_ERROR(_get_block_impl(_state, result_block, &eof));
1523
25
                }
1524
25
                return Status::OK();
1525
25
            },
1526
25
            get_block_ms));
1527
1528
25
    _cur_reader->collect_profile_before_close();
1529
25
    RETURN_IF_ERROR(_cur_reader->close());
1530
1531
25
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1532
25
    COUNTER_UPDATE(_file_read_time_counter, _file_reader_stats->read_time_ns);
1533
25
    return Status::OK();
1534
25
}
1535
1536
25
Status FileScanner::_generate_partition_columns() {
1537
25
    _partition_col_descs.clear();
1538
25
    _partition_value_is_null.clear();
1539
25
    const TFileRangeDesc& range = _current_range;
1540
25
    if (!range.__isset.columns_from_path_keys) {
1541
25
        return Status::OK();
1542
25
    }
1543
1544
0
    std::unordered_map<std::string, int> partition_name_to_key_index;
1545
0
    int index = 0;
1546
0
    for (const auto& key : range.columns_from_path_keys) {
1547
0
        partition_name_to_key_index.emplace(key, index++);
1548
0
    }
1549
1550
    // Iterate _column_descs to find PARTITION_KEY columns instead of _partition_slot_descs.
1551
0
    for (const auto& col_desc : _column_descs) {
1552
0
        if (col_desc.category != ColumnCategory::PARTITION_KEY) {
1553
0
            continue;
1554
0
        }
1555
0
        auto pit = partition_name_to_key_index.find(col_desc.name);
1556
0
        if (pit != partition_name_to_key_index.end()) {
1557
0
            int values_index = pit->second;
1558
0
            if (range.__isset.columns_from_path && values_index < range.columns_from_path.size()) {
1559
0
                _partition_col_descs.emplace(
1560
0
                        col_desc.name,
1561
0
                        std::make_tuple(range.columns_from_path[values_index], col_desc.slot_desc));
1562
0
                if (range.__isset.columns_from_path_is_null) {
1563
0
                    _partition_value_is_null.emplace(col_desc.name,
1564
0
                                                     range.columns_from_path_is_null[values_index]);
1565
0
                }
1566
0
            }
1567
0
        }
1568
0
    }
1569
0
    return Status::OK();
1570
25
}
1571
1572
16
Status FileScanner::_init_expr_ctxes() {
1573
16
    std::map<SlotId, int> full_src_index_map;
1574
16
    std::map<SlotId, SlotDescriptor*> full_src_slot_map;
1575
16
    std::map<std::string, int> partition_name_to_key_index_map;
1576
16
    int index = 0;
1577
117
    for (const auto& slot_desc : _real_tuple_desc->slots()) {
1578
117
        full_src_slot_map.emplace(slot_desc->id(), slot_desc);
1579
117
        full_src_index_map.emplace(slot_desc->id(), index++);
1580
117
    }
1581
1582
    // For external table query, find the index of column in path.
1583
    // Because query doesn't always search for all columns in a table
1584
    // and the order of selected columns is random.
1585
    // All ranges in _ranges vector should have identical columns_from_path_keys
1586
    // because they are all file splits for the same external table.
1587
    // So here use the first element of _ranges to fill the partition_name_to_key_index_map
1588
16
    if (_current_range.__isset.columns_from_path_keys) {
1589
0
        std::vector<std::string> key_map = _current_range.columns_from_path_keys;
1590
0
        if (!key_map.empty()) {
1591
0
            for (size_t i = 0; i < key_map.size(); i++) {
1592
0
                partition_name_to_key_index_map.emplace(key_map[i], i);
1593
0
            }
1594
0
        }
1595
0
    }
1596
1597
16
    _num_of_columns_from_file = _params->num_of_columns_from_file;
1598
117
    for (const auto& slot_info : _params->required_slots) {
1599
117
        auto slot_id = slot_info.slot_id;
1600
117
        auto it = full_src_slot_map.find(slot_id);
1601
117
        if (it == std::end(full_src_slot_map)) {
1602
0
            return Status::InternalError(
1603
0
                    fmt::format("Unknown source slot descriptor, slot_id={}", slot_id));
1604
0
        }
1605
1606
117
        ColumnDescriptor col_desc;
1607
117
        col_desc.name = it->second->col_name();
1608
117
        col_desc.slot_desc = it->second;
1609
1610
        // Read category from Thrift if available (new FE), otherwise fall back
1611
        // to slot_info.is_file_slot + partition_name_to_key_index_map for broker/stream load
1612
        // where the FE does not set TColumnCategory.
1613
117
        if (slot_info.__isset.category) {
1614
0
            switch (slot_info.category) {
1615
0
            case TColumnCategory::REGULAR:
1616
0
                col_desc.category = ColumnCategory::REGULAR;
1617
0
                break;
1618
0
            case TColumnCategory::PARTITION_KEY:
1619
0
                col_desc.category = ColumnCategory::PARTITION_KEY;
1620
0
                break;
1621
0
            case TColumnCategory::SYNTHESIZED:
1622
0
                col_desc.category = ColumnCategory::SYNTHESIZED;
1623
0
                break;
1624
0
            case TColumnCategory::GENERATED:
1625
0
                col_desc.category = ColumnCategory::GENERATED;
1626
0
                break;
1627
0
            }
1628
117
        } else if (partition_name_to_key_index_map.contains(it->second->col_name()) &&
1629
117
                   !slot_info.is_file_slot) {
1630
0
            col_desc.category = ColumnCategory::PARTITION_KEY;
1631
0
        }
1632
1633
        // Derive is_file_slot from category
1634
117
        bool is_file_slot = (col_desc.category == ColumnCategory::REGULAR ||
1635
117
                             col_desc.category == ColumnCategory::GENERATED);
1636
1637
117
        if (partition_name_to_key_index_map.contains(it->second->col_name())) {
1638
0
            if (_is_load) {
1639
0
                auto iti = full_src_index_map.find(slot_id);
1640
0
                _partition_slot_index_map.emplace(slot_id, iti->second - _num_of_columns_from_file);
1641
0
            } else {
1642
0
                auto kit = partition_name_to_key_index_map.find(it->second->col_name());
1643
0
                _partition_slot_index_map.emplace(slot_id, kit->second);
1644
0
            }
1645
0
        }
1646
1647
117
        if (is_file_slot) {
1648
117
            _is_file_slot.emplace(slot_id);
1649
117
            _file_slot_descs.emplace_back(it->second);
1650
117
            _file_col_names.push_back(it->second->col_name());
1651
117
        }
1652
1653
117
        _column_descs.push_back(col_desc);
1654
117
    }
1655
1656
    // set column name to default value expr map
1657
    // new inline TFileScanSlotInfo.default_value_expr (preferred)
1658
117
    for (const auto& slot_info : _params->required_slots) {
1659
117
        auto slot_id = slot_info.slot_id;
1660
117
        auto it = full_src_slot_map.find(slot_id);
1661
117
        if (it == std::end(full_src_slot_map)) {
1662
0
            continue;
1663
0
        }
1664
117
        const std::string& col_name = it->second->col_name();
1665
1666
117
        VExprContextSPtr ctx;
1667
117
        bool has_default = false;
1668
1669
        // Prefer inline default_value_expr from TFileScanSlotInfo (new FE)
1670
117
        if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
1671
0
            RETURN_IF_ERROR(VExpr::create_expr_tree(slot_info.default_value_expr, ctx));
1672
0
            RETURN_IF_ERROR(ctx->prepare(_state, *_default_val_row_desc));
1673
0
            RETURN_IF_ERROR(ctx->open(_state));
1674
0
            has_default = true;
1675
117
        } else if (slot_info.__isset.default_value_expr) {
1676
            // Empty nodes means null default (same as legacy empty TExpr)
1677
0
            has_default = true;
1678
0
        }
1679
1680
        // Fall back to legacy default_value_of_src_slot map for mixed-version FE/BE
1681
        // and callers that have not preserved inline default_value_expr yet.
1682
117
        if (!has_default) {
1683
117
            auto legacy_it = _params->default_value_of_src_slot.find(slot_id);
1684
117
            if (legacy_it != std::end(_params->default_value_of_src_slot)) {
1685
0
                if (!legacy_it->second.nodes.empty()) {
1686
0
                    RETURN_IF_ERROR(VExpr::create_expr_tree(legacy_it->second, ctx));
1687
0
                    RETURN_IF_ERROR(ctx->prepare(_state, *_default_val_row_desc));
1688
0
                    RETURN_IF_ERROR(ctx->open(_state));
1689
0
                }
1690
0
                has_default = true;
1691
0
            }
1692
117
        }
1693
1694
117
        if (has_default) {
1695
            // if expr is empty, the default value will be null
1696
0
            _col_default_value_ctx.emplace(col_name, ctx);
1697
0
        }
1698
117
    }
1699
1700
    // Populate default_expr in each ColumnDescriptor from _col_default_value_ctx.
1701
    // This makes default values available to readers via column_descs, eliminating the
1702
    // need for the separate _generate_missing_columns roundtrip.
1703
117
    for (auto& col_desc : _column_descs) {
1704
117
        auto it = _col_default_value_ctx.find(col_desc.name);
1705
117
        if (it != _col_default_value_ctx.end()) {
1706
0
            col_desc.default_expr = it->second;
1707
0
        }
1708
117
    }
1709
1710
16
    if (_is_load) {
1711
        // follow desc expr map is only for load task.
1712
0
        bool has_slot_id_map = _params->__isset.dest_sid_to_src_sid_without_trans;
1713
0
        int idx = 0;
1714
0
        for (auto* slot_desc : _output_tuple_desc->slots()) {
1715
0
            auto it = _params->expr_of_dest_slot.find(slot_desc->id());
1716
0
            if (it == std::end(_params->expr_of_dest_slot)) {
1717
0
                return Status::InternalError("No expr for dest slot, id={}, name={}",
1718
0
                                             slot_desc->id(), slot_desc->col_name());
1719
0
            }
1720
1721
0
            VExprContextSPtr ctx;
1722
0
            if (!it->second.nodes.empty()) {
1723
0
                RETURN_IF_ERROR(VExpr::create_expr_tree(it->second, ctx));
1724
0
                RETURN_IF_ERROR(ctx->prepare(_state, *_src_row_desc));
1725
0
                RETURN_IF_ERROR(ctx->open(_state));
1726
0
            }
1727
0
            _dest_vexpr_ctx.emplace_back(ctx);
1728
0
            _dest_slot_name_to_idx[slot_desc->col_name()] = idx++;
1729
1730
0
            if (has_slot_id_map) {
1731
0
                auto it1 = _params->dest_sid_to_src_sid_without_trans.find(slot_desc->id());
1732
0
                if (it1 == std::end(_params->dest_sid_to_src_sid_without_trans)) {
1733
0
                    _src_slot_descs_order_by_dest.emplace_back(nullptr);
1734
0
                } else {
1735
0
                    auto _src_slot_it = full_src_slot_map.find(it1->second);
1736
0
                    if (_src_slot_it == std::end(full_src_slot_map)) {
1737
0
                        return Status::InternalError("No src slot {} in src slot descs",
1738
0
                                                     it1->second);
1739
0
                    }
1740
0
                    _dest_slot_to_src_slot_index.emplace(_src_slot_descs_order_by_dest.size(),
1741
0
                                                         full_src_index_map[_src_slot_it->first]);
1742
0
                    _src_slot_descs_order_by_dest.emplace_back(_src_slot_it->second);
1743
0
                }
1744
0
            }
1745
0
        }
1746
0
    }
1747
16
    return Status::OK();
1748
16
}
1749
1750
3
bool FileScanner::_should_enable_condition_cache() {
1751
3
    DCHECK(_should_enable_condition_cache_handler != nullptr);
1752
3
    return _condition_cache_digest != 0 && (this->*_should_enable_condition_cache_handler)() &&
1753
3
           (!_conjuncts.empty() || !_push_down_conjuncts.empty());
1754
3
}
1755
1756
0
bool FileScanner::_should_enable_condition_cache_for_load() const {
1757
0
    return false;
1758
0
}
1759
1760
0
bool FileScanner::_should_enable_condition_cache_for_query() const {
1761
0
    return true;
1762
0
}
1763
1764
1
bool FileScanner::_should_push_down_predicates(TFileFormatType::type format_type) const {
1765
1
    DCHECK(_should_push_down_predicates_handler != nullptr);
1766
1
    return (this->*_should_push_down_predicates_handler)(format_type);
1767
1
}
1768
1769
1
bool FileScanner::_should_push_down_predicates_for_load(TFileFormatType::type format_type) const {
1770
1
    static_cast<void>(format_type);
1771
1
    return false;
1772
1
}
1773
1774
0
bool FileScanner::_should_push_down_predicates_for_query(TFileFormatType::type format_type) const {
1775
    // JNI readers handle predicate conversion in their own paths.
1776
0
    return format_type != TFileFormatType::FORMAT_JNI;
1777
0
}
1778
1779
0
void FileScanner::_init_reader_condition_cache() {
1780
0
    _condition_cache = nullptr;
1781
0
    _condition_cache_ctx = nullptr;
1782
1783
0
    if (!_should_enable_condition_cache() || !_cur_reader) {
1784
0
        return;
1785
0
    }
1786
1787
    // Disable condition cache when delete operations exist (e.g. Iceberg position/equality
1788
    // deletes, Hive ACID deletes). Cached granule results may become stale if delete files
1789
    // change between queries while the data file's cache key remains the same.
1790
0
    if (_cur_reader->has_delete_operations()) {
1791
0
        return;
1792
0
    }
1793
1794
0
    auto* cache = segment_v2::ConditionCache::instance();
1795
0
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
1796
0
            _current_range.path,
1797
0
            _current_range.__isset.modification_time ? _current_range.modification_time : 0,
1798
0
            _current_range.__isset.file_size ? _current_range.file_size : -1,
1799
0
            _condition_cache_digest,
1800
0
            _current_range.__isset.start_offset ? _current_range.start_offset : 0,
1801
0
            _current_range.__isset.size ? _current_range.size : -1);
1802
1803
0
    segment_v2::ConditionCacheHandle handle;
1804
0
    auto condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
1805
0
    if (condition_cache_hit) {
1806
0
        _condition_cache = handle.get_filter_result();
1807
0
        _condition_cache_hit_count++;
1808
0
    } else {
1809
        // Allocate cache pre-sized to total number of granules.
1810
        // We add +1 as a safety margin: when a file is split across multiple scanners
1811
        // and the first row of this scanner's range is not aligned to a granule boundary,
1812
        // the data may span one more granule than ceil(total_rows / GRANULE_SIZE).
1813
        // The extra element costs only 1 bit and never affects correctness (an extra
1814
        // false-granule beyond the actual data range won't overlap any real row range).
1815
0
        int64_t total_rows = _cur_reader->get_total_rows();
1816
0
        if (total_rows > 0) {
1817
0
            size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
1818
0
                                  ConditionCacheContext::GRANULE_SIZE;
1819
0
            _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
1820
0
        }
1821
0
    }
1822
1823
0
    if (_condition_cache) {
1824
        // Create context to pass to readers (native readers use it; non-native readers ignore it)
1825
0
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
1826
0
        _condition_cache_ctx->is_hit = condition_cache_hit;
1827
0
        _condition_cache_ctx->filter_result = _condition_cache;
1828
0
        _cur_reader->set_condition_cache_context(_condition_cache_ctx);
1829
0
    }
1830
0
}
1831
1832
3
void FileScanner::_finalize_reader_condition_cache() {
1833
3
    if (!_should_enable_condition_cache() || !_condition_cache_ctx ||
1834
3
        _condition_cache_ctx->is_hit) {
1835
3
        _condition_cache = nullptr;
1836
3
        _condition_cache_ctx = nullptr;
1837
3
        return;
1838
3
    }
1839
    // Only store the cache if the reader was fully consumed. If the scan was
1840
    // truncated early (e.g. by LIMIT), the cache is incomplete — unread granules
1841
    // would remain false and cause surviving rows to be incorrectly skipped on HIT.
1842
0
    if (!_cur_reader_eof) {
1843
0
        _condition_cache = nullptr;
1844
0
        _condition_cache_ctx = nullptr;
1845
0
        return;
1846
0
    }
1847
1848
0
    auto* cache = segment_v2::ConditionCache::instance();
1849
0
    cache->insert(_condition_cache_key, std::move(_condition_cache));
1850
0
    _condition_cache = nullptr;
1851
0
    _condition_cache_ctx = nullptr;
1852
0
}
1853
1854
2
Status FileScanner::close(RuntimeState* state) {
1855
2
    if (!_try_close()) {
1856
0
        return Status::OK();
1857
0
    }
1858
1859
2
    _finalize_reader_condition_cache();
1860
1861
2
    if (_cur_reader) {
1862
0
        RETURN_IF_ERROR(_cur_reader->close());
1863
0
    }
1864
1865
2
    RETURN_IF_ERROR(Scanner::close(state));
1866
2
    return Status::OK();
1867
2
}
1868
1869
0
void FileScanner::try_stop() {
1870
0
    Scanner::try_stop();
1871
0
    if (_io_ctx) {
1872
0
        _io_ctx->should_stop = true;
1873
0
    }
1874
0
}
1875
1876
0
void FileScanner::update_realtime_counters() {
1877
0
    FileScanLocalState* local_state = static_cast<FileScanLocalState*>(_local_state);
1878
1879
0
    COUNTER_UPDATE(local_state->_scan_bytes, _file_reader_stats->read_bytes);
1880
0
    COUNTER_UPDATE(local_state->_scan_rows, _file_reader_stats->read_rows);
1881
1882
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(
1883
0
            _file_reader_stats->read_rows);
1884
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(
1885
0
            _file_reader_stats->read_bytes);
1886
1887
0
    int64_t delta_bytes_read_from_local =
1888
0
            _file_cache_statistics->bytes_read_from_local - _last_bytes_read_from_local;
1889
0
    int64_t delta_bytes_read_from_remote =
1890
0
            _file_cache_statistics->bytes_read_from_remote - _last_bytes_read_from_remote;
1891
0
    if (_file_cache_statistics->bytes_read_from_local == 0 &&
1892
0
        _file_cache_statistics->bytes_read_from_remote == 0) {
1893
0
        _state->get_query_ctx()
1894
0
                ->resource_ctx()
1895
0
                ->io_context()
1896
0
                ->update_scan_bytes_from_remote_storage(_file_reader_stats->read_bytes);
1897
0
        DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1898
0
                _file_reader_stats->read_bytes);
1899
0
    } else {
1900
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
1901
0
                delta_bytes_read_from_local);
1902
0
        _state->get_query_ctx()
1903
0
                ->resource_ctx()
1904
0
                ->io_context()
1905
0
                ->update_scan_bytes_from_remote_storage(delta_bytes_read_from_remote);
1906
0
        DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1907
0
                delta_bytes_read_from_local);
1908
0
        DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
1909
0
                delta_bytes_read_from_remote);
1910
0
    }
1911
1912
0
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1913
1914
0
    DorisMetrics::instance()->query_scan_bytes->increment(_file_reader_stats->read_bytes);
1915
0
    DorisMetrics::instance()->query_scan_rows->increment(_file_reader_stats->read_rows);
1916
1917
0
    _file_reader_stats->read_bytes = 0;
1918
0
    _file_reader_stats->read_rows = 0;
1919
1920
0
    _last_bytes_read_from_local = _file_cache_statistics->bytes_read_from_local;
1921
0
    _last_bytes_read_from_remote = _file_cache_statistics->bytes_read_from_remote;
1922
0
}
1923
1924
0
void FileScanner::_collect_profile_before_close() {
1925
0
    Scanner::_collect_profile_before_close();
1926
0
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1927
0
        _profile != nullptr) {
1928
0
        io::FileCacheProfileReporter cache_profile(_profile);
1929
0
        cache_profile.update(_file_cache_statistics.get());
1930
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
1931
0
                _file_cache_statistics->bytes_write_into_cache);
1932
0
    }
1933
1934
0
    if (_cur_reader != nullptr) {
1935
0
        _cur_reader->collect_profile_before_close();
1936
0
    }
1937
1938
0
    FileScanLocalState* local_state = static_cast<FileScanLocalState*>(_local_state);
1939
0
    COUNTER_UPDATE(local_state->_scan_bytes, _file_reader_stats->read_bytes);
1940
0
    COUNTER_UPDATE(local_state->_scan_rows, _file_reader_stats->read_rows);
1941
1942
0
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1943
0
    COUNTER_UPDATE(_file_read_calls_counter, _file_reader_stats->read_calls);
1944
0
    COUNTER_UPDATE(_file_read_time_counter, _file_reader_stats->read_time_ns);
1945
0
    COUNTER_UPDATE(local_state->_condition_cache_hit_counter, _condition_cache_hit_count);
1946
0
    if (_io_ctx) {
1947
0
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter,
1948
0
                       _io_ctx->condition_cache_filtered_rows);
1949
0
    }
1950
1951
0
    DorisMetrics::instance()->query_scan_bytes->increment(_file_reader_stats->read_bytes);
1952
0
    DorisMetrics::instance()->query_scan_rows->increment(_file_reader_stats->read_rows);
1953
0
}
1954
1955
} // namespace doris