Coverage Report

Created: 2026-07-30 16:19

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