Coverage Report

Created: 2026-07-23 08:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/file_scanner_v2.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_v2.h"
19
20
#include <gen_cpp/Exprs_types.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
23
#include <algorithm>
24
#include <map>
25
#include <memory>
26
#include <optional>
27
#include <string>
28
#include <utility>
29
30
#include "common/cast_set.h"
31
#include "common/config.h"
32
#include "common/consts.h"
33
#include "common/metrics/doris_metrics.h"
34
#include "common/status.h"
35
#include "core/assert_cast.h"
36
#include "core/block/column_with_type_and_name.h"
37
#include "core/column/column.h"
38
#include "core/data_type/data_type.h"
39
#include "core/data_type/data_type_nullable.h"
40
#include "core/data_type_serde/data_type_serde.h"
41
#include "core/string_ref.h"
42
#include "exec/common/util.hpp"
43
#include "exec/operator/scan_operator.h"
44
#include "exec/scan/access_path_parser.h"
45
#include "exec/scan/file_scan_io_context.h"
46
#include "exprs/runtime_filter_expr.h"
47
#include "exprs/vexpr.h"
48
#include "exprs/vexpr_context.h"
49
#include "exprs/vslot_ref.h"
50
#include "format/format_common.h"
51
#include "format/table/iceberg_scan_semantics.h"
52
#include "format_v2/column_mapper.h"
53
#include "format_v2/jni/iceberg_sys_table_reader.h"
54
#include "format_v2/jni/jdbc_reader.h"
55
#include "format_v2/jni/max_compute_jni_reader.h"
56
#include "format_v2/jni/trino_connector_jni_reader.h"
57
#include "format_v2/table/hive_reader.h"
58
#include "format_v2/table/hudi_reader.h"
59
#include "format_v2/table/iceberg_position_delete_sys_table_reader.h"
60
#include "format_v2/table/iceberg_reader.h"
61
#include "format_v2/table/paimon_reader.h"
62
#include "format_v2/table/remote_doris_reader.h"
63
#include "format_v2/table_reader.h"
64
#include "io/cache/block_file_cache_profile.h"
65
#include "io/fs/file_meta_cache.h"
66
#include "io/io_common.h"
67
#include "runtime/descriptors.h"
68
#include "runtime/exec_env.h"
69
#include "runtime/file_scan_profile.h"
70
#include "runtime/runtime_state.h"
71
#include "service/backend_options.h"
72
#include "storage/id_manager.h"
73
74
namespace doris {
75
namespace {
76
77
constexpr int kIcebergPositionDeleteContent = 1;
78
constexpr int kIcebergDeletionVectorContent = 3;
79
80
51.6k
std::string table_format_name(const TFileRangeDesc& range) {
81
51.6k
    return range.__isset.table_format_params ? range.table_format_params.table_format_type
82
51.6k
                                             : "NotSet";
83
51.6k
}
84
85
TFileFormatType::type get_range_format_type(const TFileScanRangeParams& params,
86
186k
                                            const TFileRangeDesc& range) {
87
186k
    return range.__isset.format_type ? range.format_type : params.format_type;
88
186k
}
89
90
31.0k
bool is_supported_table_format(const TFileRangeDesc& range) {
91
31.0k
    const auto table_format = table_format_name(range);
92
31.0k
    if (table_format == "hudi" && range.__isset.table_format_params &&
93
31.0k
        range.table_format_params.__isset.hudi_params &&
94
31.0k
        range.table_format_params.hudi_params.__isset.delta_logs &&
95
31.0k
        !range.table_format_params.hudi_params.delta_logs.empty()) {
96
        // Hudi MOR splits need log-file merge semantics and must stay on the existing JNI path.
97
        // FileScannerV2 currently supports native Parquet data files only.
98
1
        return false;
99
1
    }
100
31.0k
    return table_format == "NotSet" || table_format == "tvf" || table_format == "hive" ||
101
31.0k
           table_format == "iceberg" || table_format == "paimon" || table_format == "hudi";
102
31.0k
}
103
104
52
bool is_supported_arrow_table_format(const TFileRangeDesc& range) {
105
52
    return table_format_name(range) == "remote_doris";
106
52
}
107
108
5
bool is_supported_jni_table_format(const TFileRangeDesc& range) {
109
5
    const auto table_format = table_format_name(range);
110
5
    if (table_format == "paimon") {
111
2
        return range.__isset.table_format_params &&
112
2
               range.table_format_params.__isset.paimon_params &&
113
2
               range.table_format_params.paimon_params.__isset.reader_type &&
114
2
               range.table_format_params.paimon_params.reader_type == TPaimonReaderType::PAIMON_JNI;
115
2
    }
116
3
    return table_format == "jdbc" || table_format == "iceberg" || table_format == "hudi" ||
117
3
           table_format == "max_compute" || table_format == "trino_connector";
118
5
}
119
120
8.93k
bool is_iceberg_position_deletes_sys_table(const TFileRangeDesc& range) {
121
8.93k
    return range.__isset.table_format_params &&
122
8.93k
           range.table_format_params.table_format_type == "iceberg" &&
123
8.93k
           range.table_format_params.__isset.iceberg_params &&
124
8.93k
           range.table_format_params.iceberg_params.__isset.content &&
125
8.93k
           (range.table_format_params.iceberg_params.content == kIcebergPositionDeleteContent ||
126
563
            range.table_format_params.iceberg_params.content == kIcebergDeletionVectorContent);
127
8.93k
}
128
129
3.08k
bool is_csv_format(TFileFormatType::type format_type) {
130
3.08k
    switch (format_type) {
131
524
    case TFileFormatType::FORMAT_CSV_PLAIN:
132
525
    case TFileFormatType::FORMAT_CSV_GZ:
133
526
    case TFileFormatType::FORMAT_CSV_BZ2:
134
527
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
135
528
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
136
529
    case TFileFormatType::FORMAT_CSV_LZOP:
137
530
    case TFileFormatType::FORMAT_CSV_DEFLATE:
138
531
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
139
532
    case TFileFormatType::FORMAT_PROTO:
140
532
        return true;
141
2.55k
    default:
142
2.55k
        return false;
143
3.08k
    }
144
3.08k
}
145
146
2.55k
bool is_text_format(TFileFormatType::type format_type) {
147
2.55k
    return format_type == TFileFormatType::FORMAT_TEXT;
148
2.55k
}
149
150
303
bool is_json_format(TFileFormatType::type format_type) {
151
303
    return format_type == TFileFormatType::FORMAT_JSON;
152
303
}
153
154
6
bool is_native_format(TFileFormatType::type format_type) {
155
6
    return format_type == TFileFormatType::FORMAT_NATIVE;
156
6
}
157
158
120k
bool is_partition_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
159
120k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
160
120k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
161
2.34k
        return false;
162
2.34k
    }
163
117k
    return slot_info.__isset.category ? slot_info.category == TColumnCategory::PARTITION_KEY
164
117k
                                      : !slot_info.is_file_slot;
165
120k
}
166
167
114k
bool is_data_file_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
168
114k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
169
114k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
170
2.34k
        return false;
171
2.34k
    }
172
    // CSV and other non-self-describing formats need FE slot descriptors for only the columns that
173
    // are physically read from the file. Partition/default/virtual columns stay in TableReader's
174
    // mapping layer and are materialized after the file-local block is read. New FE provides an
175
    // explicit category; old FE falls back to `is_file_slot`.
176
111k
    if (slot_info.__isset.category) {
177
111k
        return slot_info.category == TColumnCategory::REGULAR ||
178
111k
               slot_info.category == TColumnCategory::GENERATED;
179
111k
    }
180
3
    return slot_info.is_file_slot;
181
111k
}
182
183
Status rewrite_slot_refs_to_global_index(
184
        VExprSPtr* expr,
185
184k
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
186
184k
    DORIS_CHECK(expr != nullptr);
187
184k
    if (*expr == nullptr) {
188
0
        return Status::OK();
189
0
    }
190
184k
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr->get());
191
184k
        runtime_filter != nullptr) {
192
7.67k
        auto impl = runtime_filter->get_impl();
193
7.67k
        DORIS_CHECK(impl != nullptr);
194
7.67k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&impl, slot_id_to_global_index));
195
7.67k
        runtime_filter->set_impl(std::move(impl));
196
7.67k
        return Status::OK();
197
7.67k
    }
198
177k
    if ((*expr)->is_slot_ref()) {
199
56.1k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr->get());
200
56.1k
        const auto global_index_it = slot_id_to_global_index.find(slot_ref->slot_id());
201
56.1k
        if (global_index_it == slot_id_to_global_index.end()) {
202
1
            return Status::InternalError(
203
1
                    "Can not resolve source slot id {} to a table global index for column {}",
204
1
                    slot_ref->slot_id(), slot_ref->column_name());
205
1
        }
206
56.1k
        const auto global_index = global_index_it->second;
207
56.1k
        *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
208
56.1k
                                        cast_set<int>(global_index.value()), -1,
209
56.1k
                                        slot_ref->data_type(), slot_ref->column_name());
210
56.1k
        RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
211
56.1k
        return Status::OK();
212
56.1k
    }
213
120k
    auto children = (*expr)->children();
214
123k
    for (auto& child : children) {
215
123k
        if (child == nullptr) {
216
0
            continue;
217
0
        }
218
123k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&child, slot_id_to_global_index));
219
123k
    }
220
120k
    (*expr)->set_children(std::move(children));
221
120k
    return Status::OK();
222
120k
}
223
224
} // namespace
225
226
#ifdef BE_TEST
227
FileScannerV2::FileScannerV2(RuntimeState* state, RuntimeProfile* profile,
228
                             std::unique_ptr<format::TableReader> table_reader)
229
        : Scanner(state, profile), _table_reader(std::move(table_reader)) {}
230
231
Status FileScannerV2::TEST_validate_scan_range(const TFileScanRangeParams& params,
232
                                               const TFileRangeDesc& range) {
233
    return _validate_scan_range(params, range);
234
}
235
236
Status FileScannerV2::TEST_to_file_format(TFileFormatType::type format_type,
237
                                          format::FileFormat* file_format) {
238
    return _to_file_format(format_type, file_format);
239
}
240
241
bool FileScannerV2::TEST_is_partition_slot(const TFileScanSlotInfo& slot_info,
242
                                           const std::string& column_name) {
243
    return is_partition_slot(slot_info, column_name);
244
}
245
246
bool FileScannerV2::TEST_is_data_file_slot(const TFileScanSlotInfo& slot_info,
247
                                           const std::string& column_name) {
248
    return is_data_file_slot(slot_info, column_name);
249
}
250
251
Status FileScannerV2::TEST_rewrite_slot_refs_to_global_index(
252
        VExprSPtr* expr,
253
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
254
    return rewrite_slot_refs_to_global_index(expr, slot_id_to_global_index);
255
}
256
257
FileScannerV2::RealtimeCounterDeltas FileScannerV2::TEST_collect_realtime_counter_deltas(
258
        const io::FileReaderStats& file_reader_stats,
259
        const io::FileCacheStatistics& file_cache_statistics,
260
        UncachedReaderBytesStorage uncached_reader_bytes_storage, int64_t* last_read_bytes,
261
        int64_t* last_read_rows, int64_t* last_bytes_read_from_local,
262
        int64_t* last_bytes_read_from_remote) {
263
    return _collect_realtime_counter_deltas(file_reader_stats, file_cache_statistics,
264
                                            uncached_reader_bytes_storage, last_read_bytes,
265
                                            last_read_rows, last_bytes_read_from_local,
266
                                            last_bytes_read_from_remote);
267
}
268
269
void FileScannerV2::TEST_report_file_cache_profile(
270
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
271
    _report_file_cache_profile(profile, file_cache_statistics);
272
}
273
274
bool FileScannerV2::TEST_should_skip_not_found(const Status& status, bool ignore_not_found) {
275
    return _should_skip_not_found(status, ignore_not_found);
276
}
277
278
bool FileScannerV2::TEST_should_skip_empty(const Status& status, bool stopped) {
279
    return _should_skip_empty(status, stopped);
280
}
281
#endif
282
283
31.1k
bool FileScannerV2::is_supported(const TFileScanRangeParams& params, const TFileRangeDesc& range) {
284
31.1k
    const auto format_type = get_range_format_type(params, range);
285
31.1k
    if (format_type == TFileFormatType::FORMAT_PARQUET ||
286
31.1k
        format_type == TFileFormatType::FORMAT_ORC) {
287
28.0k
        return is_supported_table_format(range);
288
28.0k
    } else if (format_type == TFileFormatType::FORMAT_ARROW) {
289
52
        return is_supported_arrow_table_format(range);
290
3.09k
    } else if (format_type == TFileFormatType::FORMAT_JNI) {
291
5
        return is_supported_jni_table_format(range);
292
3.09k
    } else if (is_csv_format(format_type) || is_text_format(format_type) ||
293
3.09k
               is_json_format(format_type) || is_native_format(format_type)) {
294
3.08k
        return is_supported_table_format(range);
295
3.08k
    } else {
296
9
        LOG(WARNING) << "Unsupported file format type " << format_type << " for file scanner v2";
297
9
        return false;
298
9
    }
299
31.1k
}
300
301
Status FileScannerV2::_validate_scan_range(const TFileScanRangeParams& params,
302
31.1k
                                           const TFileRangeDesc& range) {
303
31.1k
    if (!is_supported(params, range)) {
304
1
        return Status::NotSupported(
305
1
                "FileScannerV2 does not support table format {} with file format {}",
306
1
                table_format_name(range), to_string(get_range_format_type(params, range)));
307
1
    }
308
31.1k
    return Status::OK();
309
31.1k
}
310
311
FileScannerV2::FileScannerV2(RuntimeState* state, FileScanLocalState* local_state, int64_t limit,
312
                             std::shared_ptr<SplitSourceConnector> split_source,
313
                             RuntimeProfile* profile, ShardedKVCache* kv_cache,
314
                             const std::unordered_map<std::string, int>* colname_to_slot_id)
315
37.8k
        : Scanner(state, local_state, limit, profile),
316
37.8k
          _split_source(std::move(split_source)),
317
37.8k
          _kv_cache(kv_cache) {
318
37.8k
    (void)colname_to_slot_id;
319
37.8k
    if (state->get_query_ctx() != nullptr &&
320
37.9k
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
321
37.8k
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
322
18.4E
    } else {
323
18.4E
        _params = _split_source->get_params();
324
18.4E
    }
325
37.8k
}
326
327
37.8k
Status FileScannerV2::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
328
37.8k
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
329
37.8k
    auto* profile = _local_state->scanner_profile();
330
37.8k
    const auto hierarchy = file_scan_profile::ensure_hierarchy(profile);
331
37.8k
    _scanner_total_timer = hierarchy.scanner;
332
37.8k
    _io_timer = hierarchy.io;
333
37.8k
    _init_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2InitTime",
334
37.8k
                                             file_scan_profile::SCANNER, 1);
335
37.8k
    _open_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2OpenTime",
336
37.8k
                                             file_scan_profile::SCANNER, 1);
337
37.8k
    _get_block_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2GetBlockTime",
338
37.8k
                                                  file_scan_profile::SCANNER, 1);
339
37.8k
    _prepare_split_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2PrepareSplitTime",
340
37.8k
                                                      file_scan_profile::SCANNER, 1);
341
37.8k
    _get_next_range_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2GetNextRangeTime",
342
37.8k
                                                       file_scan_profile::SCANNER, 1);
343
37.8k
    _close_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2CloseTime",
344
37.8k
                                              file_scan_profile::SCANNER, 1);
345
37.8k
    _empty_file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "EmptyFileNum", TUnit::UNIT,
346
37.8k
                                                       file_scan_profile::SCANNER, 1);
347
37.8k
    _not_found_file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "NotFoundFileNum", TUnit::UNIT,
348
37.8k
                                                           file_scan_profile::SCANNER, 1);
349
37.8k
    _file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileNumber", TUnit::UNIT,
350
37.8k
                                                 file_scan_profile::SCANNER, 1);
351
37.8k
    _file_read_bytes_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileReadBytes", TUnit::BYTES,
352
37.8k
                                                            file_scan_profile::IO, 1);
353
37.8k
    _file_read_calls_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileReadCalls", TUnit::UNIT,
354
37.8k
                                                            file_scan_profile::IO, 1);
355
37.8k
    _file_read_time_counter =
356
37.8k
            ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileReadTime", file_scan_profile::IO, 1);
357
37.8k
    _adaptive_batch_predicted_rows_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
358
37.8k
            profile, "AdaptiveBatchPredictedRows", TUnit::UNIT, file_scan_profile::SCANNER, 1);
359
37.8k
    _adaptive_batch_actual_bytes_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
360
37.8k
            profile, "AdaptiveBatchActualBytes", TUnit::BYTES, file_scan_profile::SCANNER, 1);
361
37.8k
    _adaptive_batch_probe_count_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
362
37.8k
            profile, "AdaptiveBatchProbeCount", TUnit::UNIT, file_scan_profile::SCANNER, 1);
363
37.8k
    SCOPED_TIMER(_scanner_total_timer);
364
37.8k
    SCOPED_TIMER(_init_timer);
365
37.8k
    _file_cache_statistics = std::make_unique<io::FileCacheStatistics>();
366
37.8k
    _file_reader_stats = std::make_unique<io::FileReaderStats>();
367
37.8k
    RETURN_IF_ERROR(_init_io_ctx());
368
37.8k
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
369
37.8k
    _io_ctx->file_reader_stats = _file_reader_stats.get();
370
37.8k
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
371
37.8k
    return Status::OK();
372
37.8k
}
373
374
37.9k
Status FileScannerV2::_open_impl(RuntimeState* state) {
375
37.9k
    SCOPED_TIMER(_scanner_total_timer);
376
37.9k
    SCOPED_TIMER(_open_timer);
377
37.9k
    RETURN_IF_CANCELLED(state);
378
37.9k
    RETURN_IF_ERROR(Scanner::_open_impl(state));
379
37.9k
    RETURN_IF_ERROR(_get_next_scan_range(&_first_scan_range));
380
37.9k
    if (_first_scan_range) {
381
20.5k
        RETURN_IF_ERROR(_create_table_reader_for_format(_current_range, &_table_reader));
382
20.5k
        DORIS_CHECK(_table_reader != nullptr);
383
20.5k
        RETURN_IF_ERROR(_init_expr_ctxes());
384
20.5k
        RETURN_IF_ERROR(_init_table_reader(_current_range));
385
20.5k
    }
386
37.9k
    return Status::OK();
387
37.9k
}
388
389
86.1k
Status FileScannerV2::_get_next_scan_range(bool* has_next) {
390
86.1k
    SCOPED_TIMER(_get_next_range_timer);
391
86.1k
    DORIS_CHECK(has_next != nullptr);
392
86.1k
    RETURN_IF_ERROR(_split_source->get_next(has_next, &_current_range));
393
86.1k
    if (*has_next) {
394
31.1k
        RETURN_IF_ERROR(_validate_scan_range(*_params, _current_range));
395
31.1k
    }
396
86.1k
    return Status::OK();
397
86.1k
}
398
399
101k
Status FileScannerV2::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
400
101k
    SCOPED_TIMER(_scanner_total_timer);
401
101k
    SCOPED_TIMER(_get_block_timer);
402
132k
    while (true) {
403
132k
        RETURN_IF_CANCELLED(state);
404
132k
        if (!_has_prepared_split) {
405
68.6k
            RETURN_IF_ERROR(_prepare_next_split(eof));
406
68.6k
            if (*eof) {
407
37.6k
                return Status::OK();
408
37.6k
            }
409
68.6k
        }
410
411
94.6k
        {
412
94.6k
            if (_should_run_adaptive_batch_size()) {
413
92.9k
                _table_reader->set_batch_size(_predict_reader_batch_rows());
414
92.9k
            }
415
94.6k
            const auto status = _table_reader->get_block(block, eof);
416
94.6k
            if (_should_skip_not_found(status, config::ignore_not_found_file_in_external_table)) {
417
0
                RETURN_IF_ERROR(_table_reader->abort_split());
418
0
                COUNTER_UPDATE(_not_found_file_counter, 1);
419
0
                _state->update_num_finished_scan_range(1);
420
0
                _has_prepared_split = false;
421
0
                block->clear_column_data(cast_set<int64_t>(_projected_columns.size()));
422
0
                *eof = false;
423
0
                continue;
424
0
            }
425
94.6k
            if (_should_skip_empty(status, _should_stop || _io_ctx->should_stop)) {
426
                // END_OF_FILE here means the reader discovered a valid split with no data while
427
                // opening or probing it, not that the Scanner has exhausted all splits. Examples
428
                // are a zero-byte CSV with an explicit schema and a Doris Native file containing
429
                // only its 12-byte header. Treat it like V1's empty-file path: finish this range,
430
                // discard partial reader state, and let the loop fetch the next split.
431
0
                RETURN_IF_ERROR(_table_reader->abort_split());
432
0
                COUNTER_UPDATE(_empty_file_counter, 1);
433
0
                _state->update_num_finished_scan_range(1);
434
0
                _has_prepared_split = false;
435
0
                block->clear_column_data(cast_set<int64_t>(_projected_columns.size()));
436
0
                *eof = false;
437
0
                continue;
438
0
            }
439
94.6k
            RETURN_IF_ERROR(status);
440
94.6k
        }
441
94.6k
        if (*eof) {
442
30.6k
            _state->update_num_finished_scan_range(1);
443
30.6k
            _has_prepared_split = false;
444
30.6k
            *eof = false;
445
30.6k
            continue;
446
30.6k
        }
447
63.9k
        _update_adaptive_batch_size(*block);
448
63.9k
        return Status::OK();
449
94.6k
    }
450
101k
}
451
452
63.9k
Status FileScannerV2::_filter_output_block(Block* block) {
453
63.9k
    return _contextualize_output_filter_status(Scanner::_filter_output_block(block),
454
63.9k
                                               _get_current_format_type());
455
63.9k
}
456
457
Status FileScannerV2::_contextualize_output_filter_status(Status status,
458
63.9k
                                                          TFileFormatType::type format_type) {
459
63.9k
    if (!status.ok() && format_type == TFileFormatType::FORMAT_ORC) {
460
        // Error-preserving expressions cannot be reordered into the ORC reader and therefore run
461
        // at the scanner boundary; keep their error context identical to ORC callback failures.
462
1
        status.prepend("Orc row reader nextBatch failed. reason = ");
463
1
    }
464
63.9k
    return status;
465
63.9k
}
466
467
68.6k
Status FileScannerV2::_prepare_next_split(bool* eos) {
468
68.6k
    SCOPED_TIMER(_prepare_split_timer);
469
68.7k
    while (true) {
470
68.7k
        bool has_next = _first_scan_range;
471
68.7k
        if (!_first_scan_range) {
472
48.2k
            RETURN_IF_ERROR(_get_next_scan_range(&has_next));
473
48.2k
        }
474
68.7k
        _first_scan_range = false;
475
68.7k
        if (!has_next || _should_stop) {
476
37.6k
            *eos = true;
477
37.6k
            return Status::OK();
478
37.6k
        }
479
31.1k
        DORIS_CHECK(_table_reader != nullptr);
480
31.1k
        _current_range_path = _current_range.path;
481
482
31.1k
        const auto format_type = get_range_format_type(*_params, _current_range);
483
31.1k
        _init_adaptive_batch_size_state(format_type);
484
31.1k
        if (_block_size_predictor != nullptr) {
485
            // JNI readers open eagerly in prepare_split(). Always seed the probe before preparing
486
            // the next split: its metadata-COUNT decision is not available yet, and the state
487
            // exposed by TableReader can still describe the preceding split. Metadata shortcuts
488
            // ignore this batch size, while row-scan fallbacks need it for their first physical
489
            // read batch.
490
31.0k
            _table_reader->set_batch_size(_predict_reader_batch_rows());
491
31.0k
        }
492
31.1k
        std::map<std::string, Field> partition_values;
493
31.1k
        RETURN_IF_ERROR(_generate_partition_values(_current_range, &partition_values));
494
31.1k
        const auto status =
495
31.1k
                _prepare_table_reader_split(_current_range, std::move(partition_values));
496
31.1k
        if (_should_skip_not_found(status, config::ignore_not_found_file_in_external_table)) {
497
0
            RETURN_IF_ERROR(_table_reader->abort_split());
498
0
            COUNTER_UPDATE(_not_found_file_counter, 1);
499
0
            _state->update_num_finished_scan_range(1);
500
0
            continue;
501
0
        }
502
31.1k
        if (_should_skip_empty(status, _should_stop || _io_ctx->should_stop)) {
503
            // Schema discovery can reach EOF before a split becomes prepared. A header-only Native
504
            // file follows this path, while a reader that discovers emptiness on its first
505
            // get_block() follows the symmetric branch in _get_block_impl(). Both paths must
506
            // advance exactly one scan range and preserve later files in the same scan.
507
0
            RETURN_IF_ERROR(_table_reader->abort_split());
508
0
            COUNTER_UPDATE(_empty_file_counter, 1);
509
0
            _state->update_num_finished_scan_range(1);
510
0
            continue;
511
0
        }
512
31.1k
        RETURN_IF_ERROR(status);
513
31.1k
        if (_table_reader->current_split_pruned()) {
514
122
            _state->update_num_finished_scan_range(1);
515
122
            continue;
516
122
        }
517
30.9k
        COUNTER_UPDATE(_file_counter, 1);
518
30.9k
        _has_prepared_split = true;
519
30.9k
        *eos = false;
520
30.9k
        return Status::OK();
521
31.1k
    }
522
68.6k
}
523
524
20.5k
Status FileScannerV2::_init_table_reader(const TFileRangeDesc& range) {
525
20.5k
    const auto format_type = get_range_format_type(*_params, range);
526
20.5k
    format::FileFormat file_format;
527
20.5k
    RETURN_IF_ERROR(_to_file_format(format_type, &file_format));
528
20.5k
    DORIS_CHECK(_table_reader != nullptr);
529
530
20.5k
    VExprContextSPtrs table_conjuncts;
531
20.5k
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
532
20.5k
    std::optional<std::vector<format::GlobalIndex>> push_down_count_columns;
533
20.5k
    const auto& push_down_count_slot_ids = _local_state->get_push_down_count_slot_ids();
534
20.5k
    if (push_down_count_slot_ids.has_value()) {
535
20.5k
        push_down_count_columns.emplace();
536
20.5k
        push_down_count_columns->reserve(push_down_count_slot_ids->size());
537
20.5k
        for (const auto slot_id : *push_down_count_slot_ids) {
538
305
            const auto global_index_it = _slot_id_to_global_index.find(slot_id);
539
305
            if (global_index_it == _slot_id_to_global_index.end()) {
540
0
                return Status::InternalError(
541
0
                        "Pushed-down COUNT argument is not a projected file scan slot, slot_id={}",
542
0
                        slot_id);
543
0
            }
544
305
            push_down_count_columns->push_back(global_index_it->second);
545
305
        }
546
20.5k
    }
547
20.5k
    RETURN_IF_ERROR(_table_reader->init({
548
20.5k
            .projected_columns = _projected_columns,
549
20.5k
            .conjuncts = std::move(table_conjuncts),
550
20.5k
            .format = file_format,
551
20.5k
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
552
20.5k
            .io_ctx = _io_ctx,
553
20.5k
            .runtime_state = _state,
554
20.5k
            .scanner_profile = _local_state->scanner_profile(),
555
20.5k
            .file_slot_descs = &_file_slot_descs,
556
20.5k
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
557
20.5k
            .push_down_count_columns = std::move(push_down_count_columns),
558
20.5k
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
559
20.5k
    }));
560
20.5k
    return Status::OK();
561
20.5k
}
562
563
Status FileScannerV2::_create_table_reader_for_format(
564
20.5k
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
565
20.5k
    DORIS_CHECK(reader != nullptr);
566
20.5k
    const auto table_format = table_format_name(range);
567
20.5k
    if (table_format == "NotSet" || table_format == "tvf") {
568
2.20k
        *reader = std::make_unique<format::TableReader>();
569
18.3k
    } else if (table_format == "hive") {
570
9.32k
        *reader = format::hive::HiveReader::create_unique();
571
9.32k
    } else if (table_format == "iceberg") {
572
8.93k
        if (is_iceberg_position_deletes_sys_table(range)) {
573
0
            *reader = std::make_unique<format::iceberg::IcebergPositionDeleteSysTableV2Reader>();
574
8.93k
        } else if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
575
0
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
576
8.93k
        } else {
577
8.93k
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
578
8.93k
        }
579
8.93k
    } else if (table_format == "paimon") {
580
0
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
581
47
    } else if (table_format == "hudi") {
582
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
583
47
    } else if (table_format == "jdbc") {
584
0
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
585
47
    } else if (table_format == "max_compute") {
586
0
        const auto* mc_desc =
587
0
                static_cast<const MaxComputeTableDescriptor*>(_output_tuple_desc->table_desc());
588
0
        RETURN_IF_ERROR(mc_desc->init_status());
589
0
        *reader = std::make_unique<format::max_compute::MaxComputeJniReader>(mc_desc);
590
47
    } else if (table_format == "trino_connector") {
591
0
        *reader = std::make_unique<format::trino_connector::TrinoConnectorJniReader>();
592
49
    } else if (table_format == "remote_doris") {
593
49
        *reader = std::make_unique<format::remote_doris::RemoteDorisReader>();
594
18.4E
    } else {
595
18.4E
        return Status::NotSupported("FileScannerV2 does not support table format {}", table_format);
596
18.4E
    }
597
20.5k
    return Status::OK();
598
20.5k
}
599
600
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range,
601
31.0k
                                                  std::map<std::string, Field> partition_values) {
602
31.0k
    format::FileFormat current_split_format;
603
31.0k
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
604
31.0k
    VExprContextSPtrs conjuncts;
605
31.0k
    RETURN_IF_ERROR(_build_table_conjuncts(&conjuncts));
606
31.0k
    VExprContextSPtrs partition_prune_conjuncts;
607
31.0k
    if (_state->query_options().enable_runtime_filter_partition_prune) {
608
30.3k
        RETURN_IF_ERROR(_build_table_conjuncts(&partition_prune_conjuncts));
609
30.3k
    }
610
31.0k
    RETURN_IF_ERROR(_table_reader->prepare_split({
611
31.0k
            .partition_values = std::move(partition_values),
612
31.0k
            .conjuncts = std::move(conjuncts),
613
31.0k
            .partition_prune_conjuncts = std::move(partition_prune_conjuncts),
614
            // A metadata COUNT split may span scheduler turns. Do not enter that irreversible
615
            // synthetic-row path while a runtime filter can still arrive between batches.
616
31.0k
            .all_runtime_filters_applied = _applied_rf_num == _total_rf_num,
617
31.0k
            .condition_cache_digest = _current_condition_cache_digest(),
618
31.0k
            .cache = _kv_cache,
619
31.0k
            .current_range = range,
620
31.0k
            .current_split_format = current_split_format,
621
31.0k
            .global_rowid_context = _create_global_rowid_context(range),
622
31.0k
    }));
623
31.0k
    return Status::OK();
624
31.0k
}
625
626
125k
bool FileScannerV2::_should_skip_not_found(const Status& status, bool ignore_not_found) {
627
125k
    return ignore_not_found && status.is<ErrorCode::NOT_FOUND>();
628
125k
}
629
630
125k
bool FileScannerV2::_should_skip_empty(const Status& status, bool stopped) {
631
    // Several readers use END_OF_FILE both for a valid zero-row split and for an interrupted IO.
632
    // For example, DeletionVectorReader returns END_OF_FILE("stop read.") after try_stop() marks
633
    // the shared IOContext. That status must unwind the stopped scanner; counting it as an empty
634
    // file would incorrectly finish the scan range and increment EmptyFileNum.
635
125k
    return !stopped && status.is<ErrorCode::END_OF_FILE>();
636
125k
}
637
638
3.77k
bool FileScannerV2::_should_enable_file_meta_cache() const {
639
3.77k
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
640
3.77k
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
641
3.77k
}
642
643
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
644
31.0k
        const TFileRangeDesc& range) const {
645
31.0k
    if (!_need_global_rowid_column) {
646
27.3k
        return std::nullopt;
647
27.3k
    }
648
3.76k
    auto& id_file_map = _state->get_id_file_map();
649
3.76k
    DORIS_CHECK(id_file_map != nullptr);
650
3.76k
    const auto file_id = id_file_map->get_file_mapping_id(
651
3.76k
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
652
3.76k
                                          range, _should_enable_file_meta_cache()));
653
3.76k
    return format::GlobalRowIdContext {
654
3.76k
            .version = IdManager::ID_VERSION,
655
3.76k
            .backend_id = BackendOptions::get_backend_id(),
656
3.76k
            .file_id = file_id,
657
3.76k
    };
658
31.0k
}
659
660
Status FileScannerV2::_generate_partition_values(
661
31.0k
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
662
31.0k
    DORIS_CHECK(partition_values != nullptr);
663
31.0k
    partition_values->clear();
664
31.0k
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
665
23.2k
        return Status::OK();
666
23.2k
    }
667
7.82k
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
668
21.3k
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
669
13.5k
        const auto& key = range.columns_from_path_keys[idx];
670
13.5k
        const auto it = _partition_slot_descs.find(key);
671
13.5k
        if (it == _partition_slot_descs.end()) {
672
6.94k
            continue;
673
6.94k
        }
674
6.56k
        const auto& value = range.columns_from_path[idx];
675
6.56k
        const bool is_null = range.__isset.columns_from_path_is_null &&
676
6.56k
                             idx < range.columns_from_path_is_null.size() &&
677
6.57k
                             range.columns_from_path_is_null[idx];
678
6.56k
        Field field;
679
6.56k
        DORIS_CHECK(it->second.slot_desc != nullptr);
680
6.56k
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
681
6.56k
        partition_values->emplace(it->second.canonical_name, std::move(field));
682
6.56k
    }
683
7.82k
    return Status::OK();
684
7.82k
}
685
686
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
687
                                             const std::string& value, bool is_null,
688
6.57k
                                             Field* field) const {
689
6.57k
    DORIS_CHECK(slot_desc != nullptr);
690
6.57k
    DORIS_CHECK(field != nullptr);
691
6.57k
    if (is_null) {
692
433
        *field = Field::create_field<TYPE_NULL>(Null());
693
433
        return Status::OK();
694
433
    }
695
6.14k
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
696
6.14k
    auto column = data_type->create_column();
697
6.14k
    auto serde = data_type->get_serde();
698
6.14k
    DataTypeSerDe::FormatOptions options;
699
6.14k
    options.converted_from_string = true;
700
6.14k
    StringRef ref(value.data(), value.size());
701
6.14k
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
702
6.14k
    DORIS_CHECK(column->size() == 1);
703
6.14k
    *field = (*column)[0];
704
6.14k
    return Status::OK();
705
6.14k
}
706
707
20.5k
Status FileScannerV2::_init_expr_ctxes() {
708
20.5k
    _slot_id_to_desc.clear();
709
20.5k
    _slot_id_to_global_index.clear();
710
20.5k
    _partition_slot_descs.clear();
711
20.5k
    _file_slot_descs.clear();
712
119k
    for (const auto* slot_desc : _output_tuple_desc->slots()) {
713
119k
        _slot_id_to_desc.emplace(slot_desc->id(), slot_desc);
714
119k
    }
715
20.5k
    DORIS_CHECK(_table_reader != nullptr);
716
20.5k
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
717
20.5k
    return Status::OK();
718
20.5k
}
719
720
20.5k
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
721
20.5k
    _projected_columns.clear();
722
20.5k
    _projected_columns.reserve(_params->required_slots.size());
723
20.5k
    _need_global_rowid_column = false;
724
20.5k
    format::ProjectedColumnBuildContext build_context {
725
20.5k
            .scan_params = _params,
726
20.5k
            .range = &_current_range,
727
20.5k
            .runtime_state = _state,
728
20.5k
    };
729
    // Field 34 is the rollout boundary for root and nested exact-name precedence.
730
20.5k
    const bool prefer_exact_name_match =
731
20.5k
            !_params->__isset.history_schema_info || supports_iceberg_scan_semantics_v1(_params);
732
733
140k
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
734
120k
        const auto& slot_info = _params->required_slots[slot_idx];
735
120k
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
736
120k
        if (it == _slot_id_to_desc.end()) {
737
0
            return Status::InternalError("Unknown source slot descriptor, slot_id={}",
738
0
                                         slot_info.slot_id);
739
0
        }
740
120k
        auto column = _build_table_column(it->second);
741
120k
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
742
2.13k
            _need_global_rowid_column = true;
743
2.13k
        }
744
120k
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
745
120k
        build_context.schema_column.reset();
746
120k
        RETURN_IF_ERROR(table_reader.annotate_projected_column(slot_info, &build_context, &column));
747
        // Build nested children from access paths generated by the slot's access-path
748
        // expressions. A projected column can therefore contain only a subset of the schema
749
        // column's nested children.
750
120k
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
751
120k
                &column, it->second,
752
120k
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr,
753
120k
                prefer_exact_name_match));
754
120k
        if (is_partition_slot(slot_info, column.name)) {
755
6.12k
            column.is_partition_key = true;
756
6.12k
            _partition_slot_descs.emplace(
757
6.12k
                    column.name,
758
6.12k
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
759
6.12k
            for (const auto& alias : column.name_mapping) {
760
0
                _partition_slot_descs.emplace(
761
0
                        alias,
762
0
                        PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
763
0
            }
764
114k
        } else if (is_data_file_slot(slot_info, column.name)) {
765
111k
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
766
111k
        }
767
120k
        const auto global_index = format::GlobalIndex(slot_idx);
768
120k
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
769
120k
        _projected_columns.push_back(std::move(column));
770
120k
    }
771
20.5k
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
772
20.5k
    return Status::OK();
773
20.5k
}
774
775
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
776
120k
                                          VExprContextSPtr* ctx) const {
777
120k
    DORIS_CHECK(ctx != nullptr);
778
120k
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
779
117k
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
780
117k
    }
781
782
2.64k
    if (_params->__isset.default_value_of_src_slot) {
783
2.64k
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
784
2.64k
        if (it != _params->default_value_of_src_slot.end() && !it->second.nodes.empty()) {
785
0
            return VExpr::create_expr_tree(it->second, *ctx);
786
0
        }
787
2.64k
    }
788
2.63k
    return Status::OK();
789
2.63k
}
790
791
120k
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
792
120k
    DORIS_CHECK(slot_desc != nullptr);
793
120k
    format::ColumnDefinition column;
794
    // TODO(gabriel): why always BY_NAME here?
795
120k
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
796
120k
    column.name = slot_desc->col_name();
797
120k
    column.type = slot_desc->get_data_type_ptr();
798
120k
    return column;
799
120k
}
800
801
81.9k
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
802
81.9k
    DORIS_CHECK(conjuncts != nullptr);
803
81.9k
    conjuncts->clear();
804
81.9k
    conjuncts->reserve(_conjuncts.size());
805
81.9k
    for (const auto& conjunct : _conjuncts) {
806
54.0k
        VExprSPtr root;
807
54.0k
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
808
54.0k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
809
54.0k
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
810
54.0k
    }
811
81.9k
    return Status::OK();
812
81.9k
}
813
814
63.9k
TFileFormatType::type FileScannerV2::_get_current_format_type() const {
815
63.9k
    return get_range_format_type(*_params, _current_range);
816
63.9k
}
817
818
Status FileScannerV2::_to_file_format(TFileFormatType::type format_type,
819
51.6k
                                      format::FileFormat* file_format) {
820
51.6k
    DORIS_CHECK(file_format != nullptr);
821
51.6k
    switch (format_type) {
822
27.2k
    case TFileFormatType::FORMAT_PARQUET:
823
27.2k
        *file_format = format::FileFormat::PARQUET;
824
27.2k
        return Status::OK();
825
19.2k
    case TFileFormatType::FORMAT_ORC:
826
19.2k
        *file_format = format::FileFormat::ORC;
827
19.2k
        return Status::OK();
828
1
    case TFileFormatType::FORMAT_JNI:
829
1
        *file_format = format::FileFormat::JNI;
830
1
        return Status::OK();
831
988
    case TFileFormatType::FORMAT_CSV_PLAIN:
832
989
    case TFileFormatType::FORMAT_CSV_GZ:
833
990
    case TFileFormatType::FORMAT_CSV_BZ2:
834
991
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
835
992
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
836
993
    case TFileFormatType::FORMAT_CSV_LZOP:
837
994
    case TFileFormatType::FORMAT_CSV_DEFLATE:
838
995
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
839
996
    case TFileFormatType::FORMAT_PROTO:
840
996
        *file_format = format::FileFormat::CSV;
841
996
        return Status::OK();
842
3.43k
    case TFileFormatType::FORMAT_TEXT:
843
3.43k
        *file_format = format::FileFormat::TEXT;
844
3.43k
        return Status::OK();
845
591
    case TFileFormatType::FORMAT_JSON:
846
591
        *file_format = format::FileFormat::JSON;
847
591
        return Status::OK();
848
3
    case TFileFormatType::FORMAT_NATIVE:
849
3
        *file_format = format::FileFormat::NATIVE;
850
3
        return Status::OK();
851
99
    case TFileFormatType::FORMAT_ARROW:
852
99
        *file_format = format::FileFormat::ARROW;
853
99
        return Status::OK();
854
0
    default:
855
0
        return Status::NotSupported("FileScannerV2 does not support file format {}",
856
0
                                    to_string(format_type));
857
51.6k
    }
858
51.6k
}
859
860
37.8k
Status FileScannerV2::_init_io_ctx() {
861
37.8k
    _io_ctx = create_file_scan_io_context(_state);
862
37.8k
    return Status::OK();
863
37.8k
}
864
865
31.0k
void FileScannerV2::_reset_adaptive_batch_size_state() {
866
31.0k
    _block_size_predictor.reset();
867
31.0k
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
868
31.0k
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
869
31.0k
}
870
871
31.0k
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
872
31.0k
    _reset_adaptive_batch_size_state();
873
31.0k
    if (!_should_enable_adaptive_batch_size(format_type)) {
874
50
        return;
875
50
    }
876
877
    // V2 native file readers do not have reliable row-width hints before the first batch. Start
878
    // every split with a small probe, then learn bytes-per-row from the materialized table block
879
    // and keep later batches close to RuntimeState::preferred_block_size_bytes().
880
31.0k
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
881
31.0k
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
882
31.0k
            _state->batch_size());
883
31.0k
}
884
885
31.1k
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
886
31.1k
    if (!config::enable_adaptive_batch_size) {
887
0
        return false;
888
0
    }
889
31.1k
    switch (format_type) {
890
16.0k
    case TFileFormatType::FORMAT_PARQUET:
891
27.9k
    case TFileFormatType::FORMAT_ORC:
892
28.5k
    case TFileFormatType::FORMAT_CSV_PLAIN:
893
28.5k
    case TFileFormatType::FORMAT_CSV_GZ:
894
28.5k
    case TFileFormatType::FORMAT_CSV_BZ2:
895
28.5k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
896
28.5k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
897
28.5k
    case TFileFormatType::FORMAT_CSV_LZOP:
898
28.5k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
899
28.5k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
900
28.5k
    case TFileFormatType::FORMAT_PROTO:
901
30.7k
    case TFileFormatType::FORMAT_TEXT:
902
31.0k
    case TFileFormatType::FORMAT_JSON:
903
31.0k
    case TFileFormatType::FORMAT_JNI:
904
31.0k
        return true;
905
50
    default:
906
50
        return false;
907
31.1k
    }
908
31.1k
}
909
910
158k
bool FileScannerV2::_should_run_adaptive_batch_size() const {
911
158k
    DORIS_CHECK(_table_reader != nullptr);
912
158k
    return _should_run_adaptive_batch_size(_block_size_predictor != nullptr,
913
158k
                                           _table_reader->current_split_uses_metadata_count());
914
158k
}
915
916
bool FileScannerV2::_should_run_adaptive_batch_size(bool predictor_initialized,
917
158k
                                                    bool current_split_uses_metadata_count) {
918
    // Metadata COUNT emits synthetic rows and has no physical row width to learn from. A raw COUNT
919
    // opcode is not sufficient here: unsupported argument counts, mappings, filters, or deletes
920
    // make TableReader fall back to materializing normal rows, which still need adaptive batching.
921
158k
    return predictor_initialized && !current_split_uses_metadata_count;
922
158k
}
923
924
123k
size_t FileScannerV2::_predict_reader_batch_rows() {
925
123k
    DORIS_CHECK(_block_size_predictor != nullptr);
926
    // Before history exists this returns the probe row count; after update(), it returns roughly
927
    // preferred_block_size_bytes / EWMA(bytes_per_row), capped by RuntimeState::batch_size().
928
123k
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
929
123k
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
930
123k
    return predicted_rows;
931
123k
}
932
933
63.9k
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
934
63.9k
    if (!_should_run_adaptive_batch_size()) {
935
1.58k
        return;
936
1.58k
    }
937
62.3k
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(block.bytes()));
938
62.3k
    if (block.rows() == 0) {
939
0
        return;
940
0
    }
941
    // The sample is taken after TableReader has finalized file-local columns to table columns.
942
    // This matches the memory shape seen by upstream operators and catches very wide nested
943
    // columns, such as map/string payloads, after the first probe batch.
944
62.3k
    if (!_block_size_predictor->has_history()) {
945
24.0k
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
946
24.0k
    }
947
62.3k
    _block_size_predictor->update(block);
948
62.3k
}
949
950
37.9k
Status FileScannerV2::close(RuntimeState* state) {
951
37.9k
    SCOPED_TIMER(_scanner_total_timer);
952
37.9k
    SCOPED_TIMER(_close_timer);
953
37.9k
    if (!_try_close()) {
954
1
        return Status::OK();
955
1
    }
956
37.9k
    if (_table_reader != nullptr) {
957
20.5k
        const auto close_status = _table_reader->close();
958
20.5k
        if (!close_status.ok()) {
959
            // Reserve the close attempt with _try_close(), but commit the scanner-level closed
960
            // state only after the retained table reader has completed its retryable cleanup.
961
1
            _is_closed.store(false);
962
1
            return close_status;
963
1
        }
964
20.5k
        _report_condition_cache_profile();
965
20.5k
        _table_reader.reset();
966
20.5k
    }
967
37.9k
    return Scanner::close(state);
968
37.9k
}
969
970
37.9k
void FileScannerV2::try_stop() {
971
37.9k
    Scanner::try_stop();
972
37.9k
    if (_io_ctx) {
973
37.9k
        _io_ctx->should_stop = true;
974
37.9k
    }
975
37.9k
}
976
977
64.6k
void FileScannerV2::update_realtime_counters() {
978
64.6k
    if (_file_reader_stats == nullptr) {
979
0
        return;
980
0
    }
981
64.6k
    DORIS_CHECK(_file_cache_statistics != nullptr);
982
64.6k
    const int64_t bytes_read = cast_set<int64_t>(_file_reader_stats->read_bytes);
983
64.6k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
984
64.6k
    const auto file_type =
985
64.6k
            _current_range.__isset.file_type
986
64.6k
                    ? _current_range.file_type
987
64.6k
                    : (_params != nullptr && _params->__isset.file_type ? _params->file_type
988
17.9k
                                                                        : TFileType::FILE_LOCAL);
989
64.6k
    const auto deltas = _collect_realtime_counter_deltas(
990
64.6k
            *_file_reader_stats, *_file_cache_statistics, _uncached_reader_bytes_storage(file_type),
991
64.6k
            &_last_read_bytes, &_last_read_rows, &_last_bytes_read_from_local,
992
64.6k
            &_last_bytes_read_from_remote);
993
994
64.6k
    COUNTER_UPDATE(local_state->_scan_bytes, deltas.scan_bytes);
995
64.6k
    COUNTER_UPDATE(local_state->_scan_rows, deltas.scan_rows);
996
997
64.6k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(deltas.scan_rows);
998
64.6k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(deltas.scan_bytes);
999
64.6k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
1000
64.6k
            deltas.scan_bytes_from_local_storage);
1001
64.6k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_remote_storage(
1002
64.6k
            deltas.scan_bytes_from_remote_storage);
1003
1004
64.6k
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
1005
64.6k
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1006
64.6k
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1007
1008
64.6k
    DorisMetrics::instance()->query_scan_bytes->increment(deltas.scan_bytes);
1009
64.6k
    DorisMetrics::instance()->query_scan_rows->increment(deltas.scan_rows);
1010
64.6k
    DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1011
64.6k
            deltas.scan_bytes_from_local_storage);
1012
64.6k
    DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
1013
64.6k
            deltas.scan_bytes_from_remote_storage);
1014
64.6k
}
1015
1016
FileScannerV2::RealtimeCounterDeltas FileScannerV2::_collect_realtime_counter_deltas(
1017
        const io::FileReaderStats& file_reader_stats,
1018
        const io::FileCacheStatistics& file_cache_statistics,
1019
        UncachedReaderBytesStorage uncached_reader_bytes_storage, int64_t* last_read_bytes,
1020
        int64_t* last_read_rows, int64_t* last_bytes_read_from_local,
1021
64.6k
        int64_t* last_bytes_read_from_remote) {
1022
64.6k
    DORIS_CHECK(last_read_bytes != nullptr);
1023
64.6k
    DORIS_CHECK(last_read_rows != nullptr);
1024
64.6k
    DORIS_CHECK(last_bytes_read_from_local != nullptr);
1025
64.6k
    DORIS_CHECK(last_bytes_read_from_remote != nullptr);
1026
1027
64.6k
    const int64_t read_bytes = cast_set<int64_t>(file_reader_stats.read_bytes);
1028
64.6k
    const int64_t read_rows = cast_set<int64_t>(file_reader_stats.read_rows);
1029
64.6k
    const int64_t bytes_read_from_local = file_cache_statistics.bytes_read_from_local;
1030
64.6k
    const int64_t bytes_read_from_remote = file_cache_statistics.bytes_read_from_remote;
1031
64.6k
    DORIS_CHECK(read_bytes >= *last_read_bytes);
1032
64.6k
    DORIS_CHECK(read_rows >= *last_read_rows);
1033
64.6k
    DORIS_CHECK(bytes_read_from_local >= *last_bytes_read_from_local);
1034
64.6k
    DORIS_CHECK(bytes_read_from_remote >= *last_bytes_read_from_remote);
1035
1036
64.6k
    RealtimeCounterDeltas deltas;
1037
64.6k
    deltas.scan_rows = read_rows - *last_read_rows;
1038
64.6k
    deltas.scan_bytes = read_bytes - *last_read_bytes;
1039
    // Peer cache is a known cache source, but it is not remote object storage.
1040
64.6k
    const bool has_cache_source_stats = file_cache_statistics.num_local_io_total != 0 ||
1041
64.6k
                                        file_cache_statistics.num_remote_io_total != 0 ||
1042
64.6k
                                        file_cache_statistics.num_peer_io_total != 0 ||
1043
64.6k
                                        bytes_read_from_local != 0 || bytes_read_from_remote != 0 ||
1044
64.6k
                                        file_cache_statistics.bytes_read_from_peer != 0;
1045
64.6k
    if (!has_cache_source_stats) {
1046
57.9k
        switch (uncached_reader_bytes_storage) {
1047
426
        case UncachedReaderBytesStorage::LOCAL:
1048
426
            deltas.scan_bytes_from_local_storage = deltas.scan_bytes;
1049
426
            break;
1050
57.5k
        case UncachedReaderBytesStorage::REMOTE:
1051
57.5k
            deltas.scan_bytes_from_remote_storage = deltas.scan_bytes;
1052
57.5k
            break;
1053
62
        case UncachedReaderBytesStorage::NONE:
1054
62
            break;
1055
57.9k
        }
1056
57.9k
    } else {
1057
6.69k
        deltas.scan_bytes_from_local_storage = bytes_read_from_local - *last_bytes_read_from_local;
1058
6.69k
        deltas.scan_bytes_from_remote_storage =
1059
6.69k
                bytes_read_from_remote - *last_bytes_read_from_remote;
1060
6.69k
    }
1061
1062
64.6k
    *last_read_bytes = read_bytes;
1063
64.6k
    *last_read_rows = read_rows;
1064
64.6k
    *last_bytes_read_from_local = bytes_read_from_local;
1065
64.6k
    *last_bytes_read_from_remote = bytes_read_from_remote;
1066
64.6k
    return deltas;
1067
64.6k
}
1068
1069
FileScannerV2::UncachedReaderBytesStorage FileScannerV2::_uncached_reader_bytes_storage(
1070
64.6k
        TFileType::type file_type) {
1071
64.6k
    switch (file_type) {
1072
425
    case TFileType::FILE_LOCAL:
1073
425
        return UncachedReaderBytesStorage::LOCAL;
1074
62
    case TFileType::FILE_STREAM:
1075
62
        return UncachedReaderBytesStorage::NONE;
1076
0
    case TFileType::FILE_BROKER:
1077
26.4k
    case TFileType::FILE_S3:
1078
63.9k
    case TFileType::FILE_HDFS:
1079
63.9k
    case TFileType::FILE_NET:
1080
64.2k
    case TFileType::FILE_HTTP:
1081
64.2k
        return UncachedReaderBytesStorage::REMOTE;
1082
64.6k
    }
1083
0
    DORIS_CHECK(false) << "unknown file type: " << file_type;
1084
0
    return UncachedReaderBytesStorage::NONE;
1085
64.6k
}
1086
1087
37.9k
void FileScannerV2::_collect_profile_before_close() {
1088
37.9k
    _report_file_reader_predicate_filtered_rows();
1089
37.9k
    Scanner::_collect_profile_before_close();
1090
37.9k
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1091
37.9k
        _profile != nullptr) {
1092
93
        auto file_cache_delta = io::diff_file_cache_statistics(*_file_cache_statistics,
1093
93
                                                               _reported_file_cache_statistics);
1094
        // Profile collection can run more than once. Keep additive fields incremental while
1095
        // publishing high-water gauges and peer identities from the latest complete snapshot.
1096
93
        file_cache_delta.remote_only_on_miss_triggered =
1097
93
                _file_cache_statistics->remote_only_on_miss_triggered;
1098
93
        file_cache_delta.remote_only_on_miss_threshold_bytes =
1099
93
                _file_cache_statistics->remote_only_on_miss_threshold_bytes;
1100
93
        file_cache_delta.peer_hosts = _file_cache_statistics->peer_hosts;
1101
93
        _report_file_cache_profile(_profile, file_cache_delta);
1102
93
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
1103
93
                file_cache_delta.bytes_write_into_cache);
1104
93
        _reported_file_cache_statistics = *_file_cache_statistics;
1105
93
    }
1106
37.9k
    if (_file_reader_stats != nullptr) {
1107
37.9k
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
1108
37.9k
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1109
37.9k
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1110
37.9k
        const auto read_time = cast_set<int64_t>(_file_reader_stats->read_time_ns);
1111
37.9k
        DORIS_CHECK(read_time >= _reported_io_read_time);
1112
        // Some transports (for example Arrow Flight) record directly into IO, while filesystem
1113
        // reads arrive through FileReaderStats. Add only the new traced delta so both paths remain
1114
        // visible without double counting repeated profile publication.
1115
37.9k
        COUNTER_UPDATE(_io_timer, read_time - _reported_io_read_time);
1116
37.9k
        _reported_io_read_time = read_time;
1117
37.9k
    }
1118
    // Query profiles can be collected before Scanner::close() runs. Publish condition-cache
1119
    // counters here as well, using deltas so this method and close() cannot double count.
1120
37.9k
    _report_condition_cache_profile();
1121
37.9k
}
1122
1123
void FileScannerV2::_report_file_cache_profile(
1124
94
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
1125
94
    file_scan_profile::ensure_hierarchy(profile);
1126
94
    io::FileCacheProfileReporter cache_profile(profile, file_scan_profile::IO);
1127
94
    cache_profile.update(&file_cache_statistics);
1128
94
}
1129
1130
37.9k
bool FileScannerV2::_should_update_load_counters() const {
1131
37.9k
    if (_is_load) {
1132
0
        return true;
1133
0
    }
1134
    // TVF based loads (e.g. http_stream, group commit relay) plan the load source as a
1135
    // tvf query scan without src tuple desc, so _is_load is false. But rows filtered by
1136
    // the load's WHERE clause still need to be reported as unselected rows. FILE_STREAM
1137
    // is only reachable from such load entries, never from normal queries, so use it to
1138
    // identify these scanners.
1139
37.9k
    return (_params != nullptr && _params->__isset.file_type &&
1140
37.9k
            _params->file_type == TFileType::FILE_STREAM) ||
1141
37.9k
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
1142
37.9k
}
1143
1144
37.9k
void FileScannerV2::_report_file_reader_predicate_filtered_rows() {
1145
18.4E
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->predicate_filtered_rows : 0;
1146
37.9k
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
1147
37.9k
    if (filtered_delta > 0) {
1148
        // File readers can evaluate localized conjuncts before a block reaches Scanner. Count
1149
        // those rows as scanner-level unselected rows so load statistics stay identical no matter
1150
        // whether a predicate is pushed down or evaluated by Scanner::_filter_output_block().
1151
1.41k
        _counter.num_rows_unselected += filtered_delta;
1152
1.41k
        _reported_predicate_filtered_rows = filtered_rows;
1153
1.41k
    }
1154
37.9k
}
1155
1156
58.4k
void FileScannerV2::_report_condition_cache_profile() {
1157
58.4k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1158
58.4k
    const int64_t hit_count =
1159
58.4k
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
1160
58.4k
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
1161
58.4k
    if (hit_delta > 0) {
1162
1.29k
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
1163
1.29k
        _reported_condition_cache_hit_count = hit_count;
1164
1.29k
    }
1165
58.4k
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
1166
58.4k
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
1167
58.4k
    if (filtered_delta > 0) {
1168
220
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
1169
220
        _reported_condition_cache_filtered_rows = filtered_rows;
1170
220
    }
1171
58.4k
}
1172
1173
} // namespace doris