Coverage Report

Created: 2026-08-06 12:11

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