Coverage Report

Created: 2026-07-17 04:10

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