Coverage Report

Created: 2026-07-24 16:40

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