Coverage Report

Created: 2026-08-03 15:36

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
44
std::string table_format_name(const TFileRangeDesc& range) {
82
44
    return range.__isset.table_format_params ? range.table_format_params.table_format_type
83
44
                                             : "NotSet";
84
44
}
85
86
TFileFormatType::type get_range_format_type(const TFileScanRangeParams& params,
87
49
                                            const TFileRangeDesc& range) {
88
49
    return range.__isset.format_type ? range.format_type : params.format_type;
89
49
}
90
91
32
bool is_supported_table_format(const TFileRangeDesc& range) {
92
32
    const auto table_format = table_format_name(range);
93
32
    if (table_format == "hudi" && range.__isset.table_format_params &&
94
32
        range.table_format_params.__isset.hudi_params &&
95
32
        range.table_format_params.hudi_params.__isset.delta_logs &&
96
32
        !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
31
    return table_format == "NotSet" || table_format == "tvf" || table_format == "hive" ||
102
31
           table_format == "iceberg" || table_format == "paimon" || table_format == "hudi";
103
32
}
104
105
3
bool is_supported_arrow_table_format(const TFileRangeDesc& range) {
106
3
    return table_format_name(range) == "remote_doris";
107
3
}
108
109
6
bool is_supported_jni_table_format(const TFileRangeDesc& range) {
110
6
    const auto table_format = table_format_name(range);
111
6
    if (table_format == "paimon") {
112
3
        if (!range.__isset.table_format_params ||
113
3
            !range.table_format_params.__isset.paimon_params) {
114
0
            return false;
115
0
        }
116
3
        const auto& params = range.table_format_params.paimon_params;
117
3
        if (params.__isset.reader_type) {
118
2
            if (params.reader_type == TPaimonReaderType::PAIMON_JNI) {
119
0
                return params.__isset.paimon_split;
120
0
            }
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
2
        }
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
3
    return table_format == "jdbc" || table_format == "iceberg" || table_format == "hudi" ||
134
3
           table_format == "max_compute" || table_format == "trino_connector";
135
6
}
136
137
0
bool is_iceberg_position_deletes_sys_table(const TFileRangeDesc& range) {
138
0
    return range.__isset.table_format_params &&
139
0
           range.table_format_params.table_format_type == "iceberg" &&
140
0
           range.table_format_params.__isset.iceberg_params &&
141
0
           range.table_format_params.iceberg_params.__isset.content &&
142
0
           (range.table_format_params.iceberg_params.content == kIcebergPositionDeleteContent ||
143
0
            range.table_format_params.iceberg_params.content == kIcebergDeletionVectorContent);
144
0
}
145
146
18
bool is_csv_format(TFileFormatType::type format_type) {
147
18
    switch (format_type) {
148
2
    case TFileFormatType::FORMAT_CSV_PLAIN:
149
3
    case TFileFormatType::FORMAT_CSV_GZ:
150
4
    case TFileFormatType::FORMAT_CSV_BZ2:
151
5
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
152
6
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
153
7
    case TFileFormatType::FORMAT_CSV_LZOP:
154
8
    case TFileFormatType::FORMAT_CSV_DEFLATE:
155
9
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
156
10
    case TFileFormatType::FORMAT_PROTO:
157
10
        return true;
158
8
    default:
159
8
        return false;
160
18
    }
161
18
}
162
163
8
bool is_text_format(TFileFormatType::type format_type) {
164
8
    return format_type == TFileFormatType::FORMAT_TEXT;
165
8
}
166
167
6
bool is_json_format(TFileFormatType::type format_type) {
168
6
    return format_type == TFileFormatType::FORMAT_JSON;
169
6
}
170
171
4
bool is_native_format(TFileFormatType::type format_type) {
172
4
    return format_type == TFileFormatType::FORMAT_NATIVE;
173
4
}
174
175
19
bool is_wal_format(TFileFormatType::type format_type) {
176
19
    return format_type == TFileFormatType::FORMAT_WAL;
177
19
}
178
179
6
bool is_partition_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
180
6
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
181
6
        column_name == BeConsts::ICEBERG_ROWID_COL) {
182
2
        return false;
183
2
    }
184
4
    return slot_info.__isset.category ? slot_info.category == TColumnCategory::PARTITION_KEY
185
4
                                      : !slot_info.is_file_slot;
186
6
}
187
188
8
bool is_data_file_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
189
8
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
190
8
        column_name == BeConsts::ICEBERG_ROWID_COL) {
191
2
        return false;
192
2
    }
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
6
    if (slot_info.__isset.category) {
198
4
        return slot_info.category == TColumnCategory::REGULAR ||
199
4
               slot_info.category == TColumnCategory::GENERATED;
200
4
    }
201
2
    return slot_info.is_file_slot;
202
6
}
203
204
Status rewrite_slot_refs_to_global_index(
205
        VExprSPtr* expr,
206
10
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
207
10
    DORIS_CHECK(expr != nullptr);
208
10
    if (*expr == nullptr) {
209
0
        return Status::OK();
210
0
    }
211
10
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr->get());
212
10
        runtime_filter != nullptr) {
213
1
        auto impl = runtime_filter->get_impl();
214
1
        DORIS_CHECK(impl != nullptr);
215
1
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&impl, slot_id_to_global_index));
216
1
        runtime_filter->set_impl(std::move(impl));
217
1
        return Status::OK();
218
1
    }
219
9
    if ((*expr)->is_slot_ref()) {
220
7
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr->get());
221
7
        const auto global_index_it = slot_id_to_global_index.find(slot_ref->slot_id());
222
7
        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
6
        const auto global_index = global_index_it->second;
228
6
        *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
229
6
                                        cast_set<int>(global_index.value()), -1,
230
6
                                        slot_ref->data_type(), slot_ref->column_name());
231
6
        RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
232
6
        return Status::OK();
233
6
    }
234
2
    auto children = (*expr)->children();
235
2
    for (auto& child : children) {
236
2
        if (child == nullptr) {
237
0
            continue;
238
0
        }
239
2
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&child, slot_id_to_global_index));
240
2
    }
241
2
    (*expr)->set_children(std::move(children));
242
2
    return Status::OK();
243
2
}
244
245
} // namespace
246
247
#ifdef BE_TEST
248
FileScannerV2::FileScannerV2(RuntimeState* state, RuntimeProfile* profile,
249
                             std::unique_ptr<format::TableReader> table_reader)
250
2
        : Scanner(state, profile), _table_reader(std::move(table_reader)) {}
251
252
Status FileScannerV2::TEST_validate_scan_range(const TFileScanRangeParams& params,
253
3
                                               const TFileRangeDesc& range) {
254
3
    return _validate_scan_range(params, range);
255
3
}
256
257
Status FileScannerV2::TEST_to_file_format(TFileFormatType::type format_type,
258
17
                                          format::FileFormat* file_format) {
259
17
    return _to_file_format(format_type, file_format);
260
17
}
261
262
bool FileScannerV2::TEST_is_partition_slot(const TFileScanSlotInfo& slot_info,
263
6
                                           const std::string& column_name) {
264
6
    return is_partition_slot(slot_info, column_name);
265
6
}
266
267
bool FileScannerV2::TEST_is_data_file_slot(const TFileScanSlotInfo& slot_info,
268
8
                                           const std::string& column_name) {
269
8
    return is_data_file_slot(slot_info, column_name);
270
8
}
271
272
Status FileScannerV2::TEST_rewrite_slot_refs_to_global_index(
273
        VExprSPtr* expr,
274
4
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
275
4
    return rewrite_slot_refs_to_global_index(expr, slot_id_to_global_index);
276
4
}
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
7
        int64_t* last_bytes_read_from_remote) {
284
7
    return _collect_realtime_counter_deltas(file_reader_stats, file_cache_statistics,
285
7
                                            uncached_reader_bytes_storage, last_read_bytes,
286
7
                                            last_read_rows, last_bytes_read_from_local,
287
7
                                            last_bytes_read_from_remote);
288
7
}
289
290
void FileScannerV2::TEST_report_file_cache_profile(
291
1
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
292
1
    _report_file_cache_profile(profile, file_cache_statistics);
293
1
}
294
295
4
bool FileScannerV2::TEST_should_skip_not_found(const Status& status, bool ignore_not_found) {
296
4
    return _should_skip_not_found(status, ignore_not_found);
297
4
}
298
299
4
bool FileScannerV2::TEST_should_skip_empty(const Status& status, bool stopped) {
300
4
    return _should_skip_empty(status, stopped);
301
4
}
302
#endif
303
304
45
bool FileScannerV2::is_supported(const TFileScanRangeParams& params, const TFileRangeDesc& range) {
305
45
    const auto format_type = get_range_format_type(params, range);
306
45
    if (format_type == TFileFormatType::FORMAT_PARQUET ||
307
45
        format_type == TFileFormatType::FORMAT_ORC) {
308
17
        return is_supported_table_format(range);
309
28
    } else if (format_type == TFileFormatType::FORMAT_ARROW) {
310
3
        return is_supported_arrow_table_format(range);
311
25
    } else if (format_type == TFileFormatType::FORMAT_JNI) {
312
6
        return is_supported_jni_table_format(range);
313
19
    } else if (is_wal_format(format_type)) {
314
1
        return table_format_name(range) == "NotSet";
315
18
    } else if (is_csv_format(format_type) || is_text_format(format_type) ||
316
18
               is_json_format(format_type) || is_native_format(format_type)) {
317
15
        return is_supported_table_format(range);
318
15
    } else {
319
3
        LOG(WARNING) << "Unsupported file format type " << format_type << " for file scanner v2";
320
3
        return false;
321
3
    }
322
45
}
323
324
Status FileScannerV2::_validate_scan_range(const TFileScanRangeParams& params,
325
3
                                           const TFileRangeDesc& range) {
326
3
    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
1
    return Status::OK();
332
3
}
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
0
        : Scanner(state, local_state, limit, profile),
339
0
          _split_source(std::move(split_source)),
340
0
          _kv_cache(kv_cache) {
341
0
    (void)colname_to_slot_id;
342
0
    if (state->get_query_ctx() != nullptr &&
343
0
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
344
0
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
345
0
    } else {
346
0
        _params = _split_source->get_params();
347
0
    }
348
0
}
349
350
0
Status FileScannerV2::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
351
0
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
352
0
    auto* profile = _local_state->scanner_profile();
353
0
    const auto hierarchy = file_scan_profile::ensure_hierarchy(profile);
354
0
    _scanner_total_timer = hierarchy.scanner;
355
0
    _io_timer = hierarchy.io;
356
0
    _init_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2InitTime",
357
0
                                             file_scan_profile::SCANNER, 1);
358
0
    _open_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2OpenTime",
359
0
                                             file_scan_profile::SCANNER, 1);
360
0
    _get_block_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2GetBlockTime",
361
0
                                                  file_scan_profile::SCANNER, 1);
362
0
    _prepare_split_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2PrepareSplitTime",
363
0
                                                      file_scan_profile::SCANNER, 1);
364
0
    _get_next_range_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2GetNextRangeTime",
365
0
                                                       file_scan_profile::SCANNER, 1);
366
0
    _close_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2CloseTime",
367
0
                                              file_scan_profile::SCANNER, 1);
368
0
    _empty_file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "EmptyFileNum", TUnit::UNIT,
369
0
                                                       file_scan_profile::SCANNER, 1);
370
0
    _not_found_file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "NotFoundFileNum", TUnit::UNIT,
371
0
                                                           file_scan_profile::SCANNER, 1);
372
0
    _file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileNumber", TUnit::UNIT,
373
0
                                                 file_scan_profile::SCANNER, 1);
374
0
    _file_read_bytes_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileReadBytes", TUnit::BYTES,
375
0
                                                            file_scan_profile::IO, 1);
376
0
    _file_read_calls_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileReadCalls", TUnit::UNIT,
377
0
                                                            file_scan_profile::IO, 1);
378
0
    _file_read_time_counter =
379
0
            ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileReadTime", file_scan_profile::IO, 1);
380
0
    _adaptive_batch_predicted_rows_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
381
0
            profile, "AdaptiveBatchPredictedRows", TUnit::UNIT, file_scan_profile::SCANNER, 1);
382
0
    _adaptive_batch_actual_bytes_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
383
0
            profile, "AdaptiveBatchActualBytes", TUnit::BYTES, file_scan_profile::SCANNER, 1);
384
0
    _adaptive_batch_probe_count_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
385
0
            profile, "AdaptiveBatchProbeCount", TUnit::UNIT, file_scan_profile::SCANNER, 1);
386
0
    SCOPED_TIMER(_scanner_total_timer);
387
0
    SCOPED_TIMER(_init_timer);
388
0
    _file_cache_statistics = std::make_unique<io::FileCacheStatistics>();
389
0
    _file_reader_stats = std::make_unique<io::FileReaderStats>();
390
0
    RETURN_IF_ERROR(_init_io_ctx());
391
0
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
392
0
    _io_ctx->file_reader_stats = _file_reader_stats.get();
393
0
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
394
0
    return Status::OK();
395
0
}
396
397
0
Status FileScannerV2::_open_impl(RuntimeState* state) {
398
0
    SCOPED_TIMER(_scanner_total_timer);
399
0
    SCOPED_TIMER(_open_timer);
400
0
    RETURN_IF_CANCELLED(state);
401
0
    RETURN_IF_ERROR(Scanner::_open_impl(state));
402
0
    RETURN_IF_ERROR(_get_next_scan_range(&_first_scan_range));
403
0
    if (_first_scan_range) {
404
0
        RETURN_IF_ERROR(_create_table_reader_for_format(_current_range, &_table_reader));
405
0
        DORIS_CHECK(_table_reader != nullptr);
406
0
        RETURN_IF_ERROR(_init_expr_ctxes());
407
0
        RETURN_IF_ERROR(_init_table_reader(_current_range));
408
0
    }
409
0
    return Status::OK();
410
0
}
411
412
0
Status FileScannerV2::_get_next_scan_range(bool* has_next) {
413
0
    SCOPED_TIMER(_get_next_range_timer);
414
0
    DORIS_CHECK(has_next != nullptr);
415
0
    RETURN_IF_ERROR(_split_source->get_next(has_next, &_current_range));
416
0
    if (*has_next) {
417
0
        RETURN_IF_ERROR(_validate_scan_range(*_params, _current_range));
418
0
    }
419
0
    return Status::OK();
420
0
}
421
422
0
Status FileScannerV2::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
423
0
    SCOPED_TIMER(_scanner_total_timer);
424
0
    SCOPED_TIMER(_get_block_timer);
425
0
    while (true) {
426
0
        RETURN_IF_CANCELLED(state);
427
0
        if (!_has_prepared_split) {
428
0
            RETURN_IF_ERROR(_prepare_next_split(eof));
429
0
            if (*eof) {
430
0
                return Status::OK();
431
0
            }
432
0
        }
433
434
0
        {
435
0
            if (_should_run_adaptive_batch_size()) {
436
0
                _table_reader->set_batch_size(_predict_reader_batch_rows());
437
0
            }
438
0
            const auto status = _table_reader->get_block(block, eof);
439
0
            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
0
            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
0
            RETURN_IF_ERROR(status);
463
0
        }
464
0
        if (*eof) {
465
0
            _state->update_num_finished_scan_range(1);
466
0
            _has_prepared_split = false;
467
0
            *eof = false;
468
0
            continue;
469
0
        }
470
0
        _update_adaptive_batch_size(*block);
471
0
        return Status::OK();
472
0
    }
473
0
}
474
475
0
Status FileScannerV2::_filter_output_block(Block* block) {
476
0
    return _contextualize_output_filter_status(Scanner::_filter_output_block(block),
477
0
                                               _get_current_format_type());
478
0
}
479
480
Status FileScannerV2::_contextualize_output_filter_status(Status status,
481
2
                                                          TFileFormatType::type format_type) {
482
2
    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
2
    return status;
488
2
}
489
490
0
Status FileScannerV2::_prepare_next_split(bool* eos) {
491
0
    SCOPED_TIMER(_prepare_split_timer);
492
0
    while (true) {
493
0
        bool has_next = _first_scan_range;
494
0
        if (!_first_scan_range) {
495
0
            RETURN_IF_ERROR(_get_next_scan_range(&has_next));
496
0
        }
497
0
        _first_scan_range = false;
498
0
        if (!has_next || _should_stop) {
499
0
            *eos = true;
500
0
            return Status::OK();
501
0
        }
502
0
        DORIS_CHECK(_table_reader != nullptr);
503
0
        _current_range_path = _current_range.path;
504
505
0
        const auto format_type = get_range_format_type(*_params, _current_range);
506
0
        _init_adaptive_batch_size_state(format_type);
507
0
        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
0
            _table_reader->set_batch_size(_predict_reader_batch_rows());
514
0
        }
515
0
        std::map<std::string, Field> partition_values;
516
0
        RETURN_IF_ERROR(_generate_partition_values(_current_range, &partition_values));
517
0
        const auto status =
518
0
                _prepare_table_reader_split(_current_range, std::move(partition_values));
519
0
        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
0
        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
0
        RETURN_IF_ERROR(status);
536
0
        if (_table_reader->current_split_pruned()) {
537
0
            _state->update_num_finished_scan_range(1);
538
0
            continue;
539
0
        }
540
0
        COUNTER_UPDATE(_file_counter, 1);
541
0
        _has_prepared_split = true;
542
0
        *eos = false;
543
0
        return Status::OK();
544
0
    }
545
0
}
546
547
0
Status FileScannerV2::_init_table_reader(const TFileRangeDesc& range) {
548
0
    const auto format_type = get_range_format_type(*_params, range);
549
0
    format::FileFormat file_format;
550
0
    RETURN_IF_ERROR(_to_file_format(format_type, &file_format));
551
0
    DORIS_CHECK(_table_reader != nullptr);
552
553
0
    VExprContextSPtrs table_conjuncts;
554
0
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
555
0
    std::optional<std::vector<format::GlobalIndex>> push_down_count_columns;
556
0
    const auto& push_down_count_slot_ids = _local_state->get_push_down_count_slot_ids();
557
0
    if (push_down_count_slot_ids.has_value()) {
558
0
        push_down_count_columns.emplace();
559
0
        push_down_count_columns->reserve(push_down_count_slot_ids->size());
560
0
        for (const auto slot_id : *push_down_count_slot_ids) {
561
0
            const auto global_index_it = _slot_id_to_global_index.find(slot_id);
562
0
            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
0
            push_down_count_columns->push_back(global_index_it->second);
568
0
        }
569
0
    }
570
0
    RETURN_IF_ERROR(_table_reader->init({
571
0
            .projected_columns = _projected_columns,
572
0
            .conjuncts = std::move(table_conjuncts),
573
0
            .format = file_format,
574
0
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
575
0
            .io_ctx = _io_ctx,
576
0
            .runtime_state = _state,
577
0
            .scanner_profile = _local_state->scanner_profile(),
578
0
            .file_slot_descs = &_file_slot_descs,
579
0
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
580
0
            .push_down_count_columns = std::move(push_down_count_columns),
581
0
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
582
0
    }));
583
0
    return Status::OK();
584
0
}
585
586
Status FileScannerV2::_create_table_reader_for_format(
587
0
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
588
0
    DORIS_CHECK(reader != nullptr);
589
0
    const auto file_format = get_range_format_type(*_params, range);
590
0
    if (file_format == TFileFormatType::FORMAT_WAL) {
591
0
        *reader = std::make_unique<format::wal::WalTableReader>();
592
0
        return Status::OK();
593
0
    }
594
0
    const auto table_format = table_format_name(range);
595
0
    if (table_format == "NotSet" || table_format == "tvf") {
596
0
        *reader = std::make_unique<format::TableReader>();
597
0
    } else if (table_format == "hive") {
598
0
        *reader = format::hive::HiveReader::create_unique();
599
0
    } else if (table_format == "iceberg") {
600
0
        if (is_iceberg_position_deletes_sys_table(range)) {
601
0
            *reader = std::make_unique<format::iceberg::IcebergPositionDeleteSysTableV2Reader>();
602
0
        } else if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
603
0
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
604
0
        } else {
605
0
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
606
0
        }
607
0
    } else if (table_format == "paimon") {
608
0
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
609
0
    } else if (table_format == "hudi") {
610
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
611
0
    } else if (table_format == "jdbc") {
612
0
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
613
0
    } 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
0
    } else if (table_format == "trino_connector") {
619
0
        *reader = std::make_unique<format::trino_connector::TrinoConnectorJniReader>();
620
0
    } else if (table_format == "remote_doris") {
621
0
        *reader = std::make_unique<format::remote_doris::RemoteDorisReader>();
622
0
    } else {
623
0
        return Status::NotSupported("FileScannerV2 does not support table format {}", table_format);
624
0
    }
625
0
    return Status::OK();
626
0
}
627
628
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range,
629
2
                                                  std::map<std::string, Field> partition_values) {
630
2
    format::FileFormat current_split_format;
631
2
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
632
2
    VExprContextSPtrs conjuncts;
633
2
    RETURN_IF_ERROR(_build_table_conjuncts(&conjuncts));
634
2
    VExprContextSPtrs partition_prune_conjuncts;
635
2
    if (!partition_values.empty()) {
636
        // A split without partition constants cannot be pruned here, so avoid cloning every
637
        // conjunct solely for a consumer that must return immediately. FileScannerV2 otherwise
638
        // keeps safe partition pruning enabled independently of the legacy session gate.
639
1
        RETURN_IF_ERROR(_build_table_conjuncts(&partition_prune_conjuncts));
640
1
    }
641
2
    RETURN_IF_ERROR(_table_reader->prepare_split({
642
2
            .partition_values = std::move(partition_values),
643
2
            .conjuncts = std::move(conjuncts),
644
2
            .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
2
            .all_runtime_filters_applied = _applied_rf_num == _total_rf_num,
648
2
            .condition_cache_digest = _current_condition_cache_digest(),
649
2
            .cache = _kv_cache,
650
2
            .current_range = range,
651
2
            .current_split_format = current_split_format,
652
2
            .global_rowid_context = _create_global_rowid_context(range),
653
2
    }));
654
2
    return Status::OK();
655
2
}
656
657
4
bool FileScannerV2::_should_skip_not_found(const Status& status, bool ignore_not_found) {
658
4
    return ignore_not_found && status.is<ErrorCode::NOT_FOUND>();
659
4
}
660
661
4
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
4
    return !stopped && status.is<ErrorCode::END_OF_FILE>();
667
4
}
668
669
0
bool FileScannerV2::_should_enable_file_meta_cache() const {
670
0
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
671
0
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
672
0
}
673
674
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
675
2
        const TFileRangeDesc& range) const {
676
2
    if (!_need_global_rowid_column) {
677
2
        return std::nullopt;
678
2
    }
679
0
    auto& id_file_map = _state->get_id_file_map();
680
0
    DORIS_CHECK(id_file_map != nullptr);
681
0
    const auto file_id = id_file_map->get_file_mapping_id(
682
0
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
683
0
                                          range, _should_enable_file_meta_cache()));
684
0
    return format::GlobalRowIdContext {
685
0
            .version = IdManager::ID_VERSION,
686
0
            .backend_id = BackendOptions::get_backend_id(),
687
0
            .file_id = file_id,
688
0
    };
689
2
}
690
691
Status FileScannerV2::_generate_partition_values(
692
0
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
693
0
    DORIS_CHECK(partition_values != nullptr);
694
0
    partition_values->clear();
695
0
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
696
0
        return Status::OK();
697
0
    }
698
0
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
699
0
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
700
0
        const auto& key = range.columns_from_path_keys[idx];
701
0
        const auto it = _partition_slot_descs.find(key);
702
0
        if (it == _partition_slot_descs.end()) {
703
0
            continue;
704
0
        }
705
0
        const auto& value = range.columns_from_path[idx];
706
0
        const bool is_null = range.__isset.columns_from_path_is_null &&
707
0
                             idx < range.columns_from_path_is_null.size() &&
708
0
                             range.columns_from_path_is_null[idx];
709
0
        Field field;
710
0
        DORIS_CHECK(it->second.slot_desc != nullptr);
711
0
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
712
0
        partition_values->emplace(it->second.canonical_name, std::move(field));
713
0
    }
714
0
    return Status::OK();
715
0
}
716
717
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
718
                                             const std::string& value, bool is_null,
719
0
                                             Field* field) const {
720
0
    DORIS_CHECK(slot_desc != nullptr);
721
0
    DORIS_CHECK(field != nullptr);
722
0
    if (is_null) {
723
0
        *field = Field::create_field<TYPE_NULL>(Null());
724
0
        return Status::OK();
725
0
    }
726
0
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
727
0
    auto column = data_type->create_column();
728
0
    auto serde = data_type->get_serde();
729
0
    DataTypeSerDe::FormatOptions options;
730
0
    options.converted_from_string = true;
731
0
    StringRef ref(value.data(), value.size());
732
0
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
733
0
    DORIS_CHECK(column->size() == 1);
734
0
    *field = (*column)[0];
735
0
    return Status::OK();
736
0
}
737
738
0
Status FileScannerV2::_init_expr_ctxes() {
739
0
    _slot_id_to_desc.clear();
740
0
    _slot_id_to_global_index.clear();
741
0
    _partition_slot_descs.clear();
742
0
    _file_slot_descs.clear();
743
0
    for (const auto* slot_desc : _output_tuple_desc->slots()) {
744
0
        _slot_id_to_desc.emplace(slot_desc->id(), slot_desc);
745
0
    }
746
0
    DORIS_CHECK(_table_reader != nullptr);
747
0
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
748
0
    return Status::OK();
749
0
}
750
751
0
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
752
0
    _projected_columns.clear();
753
0
    _projected_columns.reserve(_params->required_slots.size());
754
0
    _need_global_rowid_column = false;
755
0
    format::ProjectedColumnBuildContext build_context {
756
0
            .scan_params = _params,
757
0
            .range = &_current_range,
758
0
            .runtime_state = _state,
759
0
    };
760
    // Field 34 is the rollout boundary for root and nested exact-name precedence.
761
0
    const bool prefer_exact_name_match =
762
0
            !_params->__isset.history_schema_info || supports_iceberg_scan_semantics_v1(_params);
763
764
0
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
765
0
        const auto& slot_info = _params->required_slots[slot_idx];
766
0
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
767
0
        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
0
        auto column = _build_table_column(it->second);
772
0
        build_context.slot_desc = it->second;
773
0
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
774
0
            _need_global_rowid_column = true;
775
0
        }
776
0
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
777
0
        build_context.schema_column.reset();
778
0
        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
0
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
783
0
                &column, it->second,
784
0
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr,
785
0
                prefer_exact_name_match));
786
0
        if (is_partition_slot(slot_info, column.name)) {
787
0
            column.is_partition_key = true;
788
0
            _partition_slot_descs.emplace(
789
0
                    column.name,
790
0
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
791
0
            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
0
        } else if (is_data_file_slot(slot_info, column.name)) {
797
0
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
798
0
        }
799
0
        const auto global_index = format::GlobalIndex(slot_idx);
800
0
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
801
0
        _projected_columns.push_back(std::move(column));
802
0
    }
803
0
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
804
0
    return Status::OK();
805
0
}
806
807
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
808
0
                                          VExprContextSPtr* ctx) const {
809
0
    DORIS_CHECK(ctx != nullptr);
810
0
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
811
0
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
812
0
    }
813
814
0
    if (_params->__isset.default_value_of_src_slot) {
815
0
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
816
0
        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
0
    }
820
0
    return Status::OK();
821
0
}
822
823
0
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
824
0
    DORIS_CHECK(slot_desc != nullptr);
825
0
    format::ColumnDefinition column;
826
    // TODO(gabriel): why always BY_NAME here?
827
0
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
828
0
    column.name = slot_desc->col_name();
829
0
    column.type = slot_desc->get_data_type_ptr();
830
0
    return column;
831
0
}
832
833
3
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
834
3
    DORIS_CHECK(conjuncts != nullptr);
835
3
    conjuncts->clear();
836
3
    conjuncts->reserve(_conjuncts.size());
837
3
    for (const auto& conjunct : _conjuncts) {
838
3
        VExprSPtr root;
839
3
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
840
3
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
841
3
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
842
3
    }
843
3
    return Status::OK();
844
3
}
845
846
0
TFileFormatType::type FileScannerV2::_get_current_format_type() const {
847
0
    return get_range_format_type(*_params, _current_range);
848
0
}
849
850
Status FileScannerV2::_to_file_format(TFileFormatType::type format_type,
851
19
                                      format::FileFormat* file_format) {
852
19
    DORIS_CHECK(file_format != nullptr);
853
19
    switch (format_type) {
854
3
    case TFileFormatType::FORMAT_PARQUET:
855
3
        *file_format = format::FileFormat::PARQUET;
856
3
        return Status::OK();
857
1
    case TFileFormatType::FORMAT_ORC:
858
1
        *file_format = format::FileFormat::ORC;
859
1
        return Status::OK();
860
1
    case TFileFormatType::FORMAT_JNI:
861
1
        *file_format = format::FileFormat::JNI;
862
1
        return Status::OK();
863
1
    case TFileFormatType::FORMAT_CSV_PLAIN:
864
2
    case TFileFormatType::FORMAT_CSV_GZ:
865
3
    case TFileFormatType::FORMAT_CSV_BZ2:
866
4
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
867
5
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
868
6
    case TFileFormatType::FORMAT_CSV_LZOP:
869
7
    case TFileFormatType::FORMAT_CSV_DEFLATE:
870
8
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
871
9
    case TFileFormatType::FORMAT_PROTO:
872
9
        *file_format = format::FileFormat::CSV;
873
9
        return Status::OK();
874
1
    case TFileFormatType::FORMAT_TEXT:
875
1
        *file_format = format::FileFormat::TEXT;
876
1
        return Status::OK();
877
1
    case TFileFormatType::FORMAT_JSON:
878
1
        *file_format = format::FileFormat::JSON;
879
1
        return Status::OK();
880
1
    case TFileFormatType::FORMAT_NATIVE:
881
1
        *file_format = format::FileFormat::NATIVE;
882
1
        return Status::OK();
883
1
    case TFileFormatType::FORMAT_ARROW:
884
1
        *file_format = format::FileFormat::ARROW;
885
1
        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
19
    }
893
19
}
894
895
0
Status FileScannerV2::_init_io_ctx() {
896
0
    _io_ctx = create_file_scan_io_context(_state);
897
0
    return Status::OK();
898
0
}
899
900
0
void FileScannerV2::_reset_adaptive_batch_size_state() {
901
0
    _block_size_predictor.reset();
902
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
903
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
904
0
}
905
906
0
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
907
0
    _reset_adaptive_batch_size_state();
908
0
    if (!_should_enable_adaptive_batch_size(format_type)) {
909
0
        return;
910
0
    }
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
0
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
916
0
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
917
0
            _state->batch_size());
918
0
}
919
920
0
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
921
0
    if (!config::enable_adaptive_batch_size) {
922
0
        return false;
923
0
    }
924
0
    switch (format_type) {
925
0
    case TFileFormatType::FORMAT_PARQUET:
926
0
    case TFileFormatType::FORMAT_ORC:
927
0
    case TFileFormatType::FORMAT_CSV_PLAIN:
928
0
    case TFileFormatType::FORMAT_CSV_GZ:
929
0
    case TFileFormatType::FORMAT_CSV_BZ2:
930
0
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
931
0
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
932
0
    case TFileFormatType::FORMAT_CSV_LZOP:
933
0
    case TFileFormatType::FORMAT_CSV_DEFLATE:
934
0
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
935
0
    case TFileFormatType::FORMAT_PROTO:
936
0
    case TFileFormatType::FORMAT_TEXT:
937
0
    case TFileFormatType::FORMAT_JSON:
938
0
    case TFileFormatType::FORMAT_JNI:
939
0
        return true;
940
0
    default:
941
0
        return false;
942
0
    }
943
0
}
944
945
0
bool FileScannerV2::_should_run_adaptive_batch_size() const {
946
0
    DORIS_CHECK(_table_reader != nullptr);
947
0
    return _should_run_adaptive_batch_size(_block_size_predictor != nullptr,
948
0
                                           _table_reader->current_split_uses_metadata_count());
949
0
}
950
951
bool FileScannerV2::_should_run_adaptive_batch_size(bool predictor_initialized,
952
3
                                                    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
3
    return predictor_initialized && !current_split_uses_metadata_count;
957
3
}
958
959
0
size_t FileScannerV2::_predict_reader_batch_rows() {
960
0
    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
0
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
964
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
965
0
    return predicted_rows;
966
0
}
967
968
0
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
969
0
    if (!_should_run_adaptive_batch_size()) {
970
0
        return;
971
0
    }
972
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(block.bytes()));
973
0
    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
0
    if (!_block_size_predictor->has_history()) {
980
0
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
981
0
    }
982
0
    _block_size_predictor->update(block);
983
0
}
984
985
3
Status FileScannerV2::close(RuntimeState* state) {
986
3
    SCOPED_TIMER(_scanner_total_timer);
987
3
    SCOPED_TIMER(_close_timer);
988
3
    if (!_try_close()) {
989
1
        return Status::OK();
990
1
    }
991
2
    if (_table_reader != nullptr) {
992
2
        const auto close_status = _table_reader->close();
993
2
        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
1
        _report_condition_cache_profile();
1000
1
        _table_reader.reset();
1001
1
    }
1002
1
    return Scanner::close(state);
1003
2
}
1004
1005
0
void FileScannerV2::try_stop() {
1006
0
    Scanner::try_stop();
1007
0
    if (_io_ctx) {
1008
0
        _io_ctx->should_stop = true;
1009
0
    }
1010
0
}
1011
1012
0
void FileScannerV2::update_realtime_counters() {
1013
0
    if (_file_reader_stats == nullptr) {
1014
0
        return;
1015
0
    }
1016
0
    DORIS_CHECK(_file_cache_statistics != nullptr);
1017
0
    const int64_t bytes_read = cast_set<int64_t>(_file_reader_stats->read_bytes);
1018
0
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1019
0
    const auto file_type =
1020
0
            _current_range.__isset.file_type
1021
0
                    ? _current_range.file_type
1022
0
                    : (_params != nullptr && _params->__isset.file_type ? _params->file_type
1023
0
                                                                        : TFileType::FILE_LOCAL);
1024
0
    const auto deltas = _collect_realtime_counter_deltas(
1025
0
            *_file_reader_stats, *_file_cache_statistics, _uncached_reader_bytes_storage(file_type),
1026
0
            &_last_read_bytes, &_last_read_rows, &_last_bytes_read_from_local,
1027
0
            &_last_bytes_read_from_remote);
1028
1029
0
    COUNTER_UPDATE(local_state->_scan_bytes, deltas.scan_bytes);
1030
0
    COUNTER_UPDATE(local_state->_scan_rows, deltas.scan_rows);
1031
1032
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(deltas.scan_rows);
1033
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(deltas.scan_bytes);
1034
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
1035
0
            deltas.scan_bytes_from_local_storage);
1036
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_remote_storage(
1037
0
            deltas.scan_bytes_from_remote_storage);
1038
1039
0
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
1040
0
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1041
0
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1042
1043
0
    DorisMetrics::instance()->query_scan_bytes->increment(deltas.scan_bytes);
1044
0
    DorisMetrics::instance()->query_scan_rows->increment(deltas.scan_rows);
1045
0
    DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1046
0
            deltas.scan_bytes_from_local_storage);
1047
0
    DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
1048
0
            deltas.scan_bytes_from_remote_storage);
1049
0
}
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
7
        int64_t* last_bytes_read_from_remote) {
1057
7
    DORIS_CHECK(last_read_bytes != nullptr);
1058
7
    DORIS_CHECK(last_read_rows != nullptr);
1059
7
    DORIS_CHECK(last_bytes_read_from_local != nullptr);
1060
7
    DORIS_CHECK(last_bytes_read_from_remote != nullptr);
1061
1062
7
    const int64_t read_bytes = cast_set<int64_t>(file_reader_stats.read_bytes);
1063
7
    const int64_t read_rows = cast_set<int64_t>(file_reader_stats.read_rows);
1064
7
    const int64_t bytes_read_from_local = file_cache_statistics.bytes_read_from_local;
1065
7
    const int64_t bytes_read_from_remote = file_cache_statistics.bytes_read_from_remote;
1066
7
    DORIS_CHECK(read_bytes >= *last_read_bytes);
1067
7
    DORIS_CHECK(read_rows >= *last_read_rows);
1068
7
    DORIS_CHECK(bytes_read_from_local >= *last_bytes_read_from_local);
1069
7
    DORIS_CHECK(bytes_read_from_remote >= *last_bytes_read_from_remote);
1070
1071
7
    RealtimeCounterDeltas deltas;
1072
7
    deltas.scan_rows = read_rows - *last_read_rows;
1073
7
    deltas.scan_bytes = read_bytes - *last_read_bytes;
1074
    // Peer cache is a known cache source, but it is not remote object storage.
1075
7
    const bool has_cache_source_stats = file_cache_statistics.num_local_io_total != 0 ||
1076
7
                                        file_cache_statistics.num_remote_io_total != 0 ||
1077
7
                                        file_cache_statistics.num_peer_io_total != 0 ||
1078
7
                                        bytes_read_from_local != 0 || bytes_read_from_remote != 0 ||
1079
7
                                        file_cache_statistics.bytes_read_from_peer != 0;
1080
7
    if (!has_cache_source_stats) {
1081
4
        switch (uncached_reader_bytes_storage) {
1082
1
        case UncachedReaderBytesStorage::LOCAL:
1083
1
            deltas.scan_bytes_from_local_storage = deltas.scan_bytes;
1084
1
            break;
1085
3
        case UncachedReaderBytesStorage::REMOTE:
1086
3
            deltas.scan_bytes_from_remote_storage = deltas.scan_bytes;
1087
3
            break;
1088
0
        case UncachedReaderBytesStorage::NONE:
1089
0
            break;
1090
4
        }
1091
4
    } else {
1092
3
        deltas.scan_bytes_from_local_storage = bytes_read_from_local - *last_bytes_read_from_local;
1093
3
        deltas.scan_bytes_from_remote_storage =
1094
3
                bytes_read_from_remote - *last_bytes_read_from_remote;
1095
3
    }
1096
1097
7
    *last_read_bytes = read_bytes;
1098
7
    *last_read_rows = read_rows;
1099
7
    *last_bytes_read_from_local = bytes_read_from_local;
1100
7
    *last_bytes_read_from_remote = bytes_read_from_remote;
1101
7
    return deltas;
1102
7
}
1103
1104
FileScannerV2::UncachedReaderBytesStorage FileScannerV2::_uncached_reader_bytes_storage(
1105
0
        TFileType::type file_type) {
1106
0
    switch (file_type) {
1107
0
    case TFileType::FILE_LOCAL:
1108
0
        return UncachedReaderBytesStorage::LOCAL;
1109
0
    case TFileType::FILE_STREAM:
1110
0
        return UncachedReaderBytesStorage::NONE;
1111
0
    case TFileType::FILE_BROKER:
1112
0
    case TFileType::FILE_S3:
1113
0
    case TFileType::FILE_HDFS:
1114
0
    case TFileType::FILE_NET:
1115
0
    case TFileType::FILE_HTTP:
1116
0
        return UncachedReaderBytesStorage::REMOTE;
1117
0
    }
1118
0
    DORIS_CHECK(false) << "unknown file type: " << file_type;
1119
0
    return UncachedReaderBytesStorage::NONE;
1120
0
}
1121
1122
0
void FileScannerV2::_collect_profile_before_close() {
1123
0
    _report_file_reader_predicate_filtered_rows();
1124
0
    Scanner::_collect_profile_before_close();
1125
0
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1126
0
        _profile != nullptr) {
1127
0
        auto file_cache_delta = io::diff_file_cache_statistics(*_file_cache_statistics,
1128
0
                                                               _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
0
        file_cache_delta.remote_only_on_miss_triggered =
1132
0
                _file_cache_statistics->remote_only_on_miss_triggered;
1133
0
        file_cache_delta.remote_only_on_miss_threshold_bytes =
1134
0
                _file_cache_statistics->remote_only_on_miss_threshold_bytes;
1135
0
        file_cache_delta.peer_hosts = _file_cache_statistics->peer_hosts;
1136
0
        _report_file_cache_profile(_profile, file_cache_delta);
1137
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
1138
0
                file_cache_delta.bytes_write_into_cache);
1139
0
        _reported_file_cache_statistics = *_file_cache_statistics;
1140
0
    }
1141
0
    if (_file_reader_stats != nullptr) {
1142
0
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
1143
0
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1144
0
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1145
0
        const auto read_time = cast_set<int64_t>(_file_reader_stats->read_time_ns);
1146
0
        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
0
        COUNTER_UPDATE(_io_timer, read_time - _reported_io_read_time);
1151
0
        _reported_io_read_time = read_time;
1152
0
    }
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
0
    _report_condition_cache_profile();
1156
0
}
1157
1158
void FileScannerV2::_report_file_cache_profile(
1159
1
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
1160
1
    file_scan_profile::ensure_hierarchy(profile);
1161
1
    io::FileCacheProfileReporter cache_profile(profile, file_scan_profile::IO);
1162
1
    cache_profile.update(&file_cache_statistics);
1163
1
}
1164
1165
0
bool FileScannerV2::_should_update_load_counters() const {
1166
0
    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
0
    return (_params != nullptr && _params->__isset.file_type &&
1175
0
            _params->file_type == TFileType::FILE_STREAM) ||
1176
0
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
1177
0
}
1178
1179
0
void FileScannerV2::_report_file_reader_predicate_filtered_rows() {
1180
0
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->predicate_filtered_rows : 0;
1181
0
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
1182
0
    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
0
        _counter.num_rows_unselected += filtered_delta;
1187
0
        _reported_predicate_filtered_rows = filtered_rows;
1188
0
    }
1189
0
}
1190
1191
1
void FileScannerV2::_report_condition_cache_profile() {
1192
1
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1193
1
    const int64_t hit_count =
1194
1
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
1195
1
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
1196
1
    if (hit_delta > 0) {
1197
0
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
1198
0
        _reported_condition_cache_hit_count = hit_count;
1199
0
    }
1200
1
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
1201
1
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
1202
1
    if (filtered_delta > 0) {
1203
0
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
1204
0
        _reported_condition_cache_filtered_rows = filtered_rows;
1205
0
    }
1206
1
}
1207
1208
} // namespace doris