Coverage Report

Created: 2026-07-14 07:07

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