Coverage Report

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