Coverage Report

Created: 2026-08-06 20:25

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