Coverage Report

Created: 2026-06-01 18:52

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