Coverage Report

Created: 2026-07-06 09:38

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