Coverage Report

Created: 2026-07-12 19:37

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