Coverage Report

Created: 2026-04-08 18:35

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