Coverage Report

Created: 2026-07-30 08:54

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