Coverage Report

Created: 2026-08-06 12:21

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
365k
std::string table_format_name(const TFileRangeDesc& range) {
83
365k
    return range.__isset.table_format_params ? range.table_format_params.table_format_type
84
365k
                                             : "NotSet";
85
365k
}
86
87
TFileFormatType::type get_range_format_type(const TFileScanRangeParams& params,
88
636k
                                            const TFileRangeDesc& range) {
89
636k
    return range.__isset.format_type ? range.format_type : params.format_type;
90
636k
}
91
92
123k
bool is_supported_table_format(const TFileRangeDesc& range) {
93
123k
    const auto table_format = table_format_name(range);
94
123k
    if (table_format == "hudi" && range.__isset.table_format_params &&
95
123k
        range.table_format_params.__isset.hudi_params &&
96
123k
        range.table_format_params.hudi_params.__isset.delta_logs &&
97
123k
        !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
123k
    return table_format == "NotSet" || table_format == "tvf" || table_format == "hive" ||
103
123k
           table_format == "iceberg" || table_format == "paimon" || table_format == "hudi";
104
123k
}
105
106
102
bool is_supported_arrow_table_format(const TFileRangeDesc& range) {
107
102
    const auto table_format = table_format_name(range);
108
102
    return table_format == "remote_doris" || table_format == "adbc";
109
102
}
110
111
5.95k
bool is_supported_jni_table_format(const TFileRangeDesc& range) {
112
5.95k
    const auto table_format = table_format_name(range);
113
5.95k
    if (table_format == "paimon") {
114
2.17k
        if (!range.__isset.table_format_params ||
115
2.17k
            !range.table_format_params.__isset.paimon_params) {
116
0
            return false;
117
0
        }
118
2.17k
        const auto& params = range.table_format_params.paimon_params;
119
2.17k
        if (params.__isset.reader_type) {
120
2.17k
            if (params.reader_type == TPaimonReaderType::PAIMON_JNI) {
121
2.17k
                return params.__isset.paimon_split;
122
2.17k
            }
123
            // V2 cannot pass a logical DataSplit through a raw native child without silently
124
            // dropping its multi-file semantics, so PAIMON_CPP must remain on the V1 fallback.
125
2
            return false;
126
2.17k
        }
127
1
        if (params.__isset.paimon_split) {
128
            // Before reader_type was added, an encoded split unambiguously selected the Java
129
            // reader; native scans carried only their physical Parquet or ORC range.
130
1
            return true;
131
1
        }
132
0
        return params.__isset.file_format &&
133
0
               (params.file_format == "parquet" || params.file_format == "orc");
134
1
    }
135
3.77k
    return table_format == "jdbc" || table_format == "iceberg" || table_format == "hudi" ||
136
3.77k
           table_format == "max_compute" || table_format == "trino_connector";
137
5.95k
}
138
139
22.0k
bool is_iceberg_position_deletes_sys_table(const TFileRangeDesc& range) {
140
22.0k
    return range.__isset.table_format_params &&
141
22.0k
           range.table_format_params.table_format_type == "iceberg" &&
142
22.0k
           range.table_format_params.__isset.iceberg_params &&
143
22.0k
           range.table_format_params.iceberg_params.__isset.content &&
144
22.0k
           (range.table_format_params.iceberg_params.content == kIcebergPositionDeleteContent ||
145
1.32k
            range.table_format_params.iceberg_params.content == kIcebergDeletionVectorContent);
146
22.0k
}
147
148
6.23k
bool is_csv_format(TFileFormatType::type format_type) {
149
6.23k
    switch (format_type) {
150
811
    case TFileFormatType::FORMAT_CSV_PLAIN:
151
812
    case TFileFormatType::FORMAT_CSV_GZ:
152
813
    case TFileFormatType::FORMAT_CSV_BZ2:
153
814
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
154
815
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
155
816
    case TFileFormatType::FORMAT_CSV_LZOP:
156
817
    case TFileFormatType::FORMAT_CSV_DEFLATE:
157
818
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
158
819
    case TFileFormatType::FORMAT_PROTO:
159
819
        return true;
160
5.41k
    default:
161
5.41k
        return false;
162
6.23k
    }
163
6.23k
}
164
165
5.41k
bool is_text_format(TFileFormatType::type format_type) {
166
5.41k
    return format_type == TFileFormatType::FORMAT_TEXT;
167
5.41k
}
168
169
597
bool is_json_format(TFileFormatType::type format_type) {
170
597
    return format_type == TFileFormatType::FORMAT_JSON;
171
597
}
172
173
4
bool is_native_format(TFileFormatType::type format_type) {
174
4
    return format_type == TFileFormatType::FORMAT_NATIVE;
175
4
}
176
177
6.23k
bool is_wal_format(TFileFormatType::type format_type) {
178
6.23k
    return format_type == TFileFormatType::FORMAT_WAL;
179
6.23k
}
180
181
295k
bool is_partition_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
182
295k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
183
295k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
184
4.81k
        return false;
185
4.81k
    }
186
290k
    return slot_info.__isset.category ? slot_info.category == TColumnCategory::PARTITION_KEY
187
290k
                                      : !slot_info.is_file_slot;
188
295k
}
189
190
279k
bool is_data_file_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
191
279k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
192
279k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
193
4.81k
        return false;
194
4.81k
    }
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
274k
    if (slot_info.__isset.category) {
200
274k
        return slot_info.category == TColumnCategory::REGULAR ||
201
274k
               slot_info.category == TColumnCategory::GENERATED;
202
274k
    }
203
18.4E
    return slot_info.is_file_slot;
204
274k
}
205
206
Status rewrite_slot_refs_to_global_index(
207
        VExprSPtr* expr,
208
423k
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
209
423k
    DORIS_CHECK(expr != nullptr);
210
423k
    if (*expr == nullptr) {
211
0
        return Status::OK();
212
0
    }
213
423k
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr->get());
214
423k
        runtime_filter != nullptr) {
215
20.4k
        auto impl = runtime_filter->get_impl();
216
20.4k
        DORIS_CHECK(impl != nullptr);
217
20.4k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&impl, slot_id_to_global_index));
218
20.4k
        runtime_filter->set_impl(std::move(impl));
219
20.4k
        return Status::OK();
220
20.4k
    }
221
402k
    if ((*expr)->is_slot_ref()) {
222
131k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr->get());
223
131k
        const auto global_index_it = slot_id_to_global_index.find(slot_ref->slot_id());
224
131k
        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
131k
        const auto global_index = global_index_it->second;
230
131k
        *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
231
131k
                                        cast_set<int>(global_index.value()), -1,
232
131k
                                        slot_ref->data_type(), slot_ref->column_name());
233
131k
        RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
234
131k
        return Status::OK();
235
131k
    }
236
271k
    auto children = (*expr)->children();
237
275k
    for (auto& child : children) {
238
275k
        if (child == nullptr) {
239
0
            continue;
240
0
        }
241
275k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&child, slot_id_to_global_index));
242
275k
    }
243
271k
    (*expr)->set_children(std::move(children));
244
271k
    return Status::OK();
245
271k
}
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
129k
bool FileScannerV2::is_supported(const TFileScanRangeParams& params, const TFileRangeDesc& range) {
307
129k
    const auto format_type = get_range_format_type(params, range);
308
129k
    if (format_type == TFileFormatType::FORMAT_PARQUET ||
309
129k
        format_type == TFileFormatType::FORMAT_ORC) {
310
117k
        return is_supported_table_format(range);
311
117k
    } else if (format_type == TFileFormatType::FORMAT_ARROW) {
312
102
        return is_supported_arrow_table_format(range);
313
12.1k
    } else if (format_type == TFileFormatType::FORMAT_JNI) {
314
5.95k
        return is_supported_jni_table_format(range);
315
6.24k
    } else if (is_wal_format(format_type)) {
316
1
        return table_format_name(range) == "NotSet";
317
6.24k
    } else if (is_csv_format(format_type) || is_text_format(format_type) ||
318
6.24k
               is_json_format(format_type) || is_native_format(format_type)) {
319
6.22k
        return is_supported_table_format(range);
320
6.22k
    } else {
321
13
        LOG(WARNING) << "Unsupported file format type " << format_type << " for file scanner v2";
322
13
        return false;
323
13
    }
324
129k
}
325
326
Status FileScannerV2::_validate_scan_range(const TFileScanRangeParams& params,
327
129k
                                           const TFileRangeDesc& range) {
328
129k
    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
129k
    return Status::OK();
334
129k
}
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
92.6k
        : Scanner(state, local_state, limit, profile),
341
92.6k
          _split_source(std::move(split_source)),
342
92.6k
          _kv_cache(kv_cache) {
343
92.6k
    (void)colname_to_slot_id;
344
92.6k
    if (state->get_query_ctx() != nullptr &&
345
92.7k
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
346
92.6k
        _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
92.6k
}
351
352
92.5k
Status FileScannerV2::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
353
92.5k
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
354
92.5k
    auto* profile = _local_state->scanner_profile();
355
92.5k
    const auto hierarchy = file_scan_profile::ensure_hierarchy(profile);
356
92.5k
    _scanner_total_timer = hierarchy.scanner;
357
92.5k
    _io_timer = hierarchy.io;
358
92.5k
    _init_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2InitTime",
359
92.5k
                                             file_scan_profile::SCANNER, 1);
360
92.5k
    _open_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2OpenTime",
361
92.5k
                                             file_scan_profile::SCANNER, 1);
362
92.5k
    _get_block_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2GetBlockTime",
363
92.5k
                                                  file_scan_profile::SCANNER, 1);
364
92.5k
    _prepare_split_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2PrepareSplitTime",
365
92.5k
                                                      file_scan_profile::SCANNER, 1);
366
92.5k
    _get_next_range_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2GetNextRangeTime",
367
92.5k
                                                       file_scan_profile::SCANNER, 1);
368
92.5k
    _close_timer = ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileScannerV2CloseTime",
369
92.5k
                                              file_scan_profile::SCANNER, 1);
370
92.5k
    _empty_file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "EmptyFileNum", TUnit::UNIT,
371
92.5k
                                                       file_scan_profile::SCANNER, 1);
372
92.5k
    _not_found_file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "NotFoundFileNum", TUnit::UNIT,
373
92.5k
                                                           file_scan_profile::SCANNER, 1);
374
92.5k
    _file_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileNumber", TUnit::UNIT,
375
92.5k
                                                 file_scan_profile::SCANNER, 1);
376
92.5k
    _file_read_bytes_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileReadBytes", TUnit::BYTES,
377
92.5k
                                                            file_scan_profile::IO, 1);
378
92.5k
    _file_read_calls_counter = ADD_CHILD_COUNTER_WITH_LEVEL(profile, "FileReadCalls", TUnit::UNIT,
379
92.5k
                                                            file_scan_profile::IO, 1);
380
92.5k
    _file_read_time_counter =
381
92.5k
            ADD_CHILD_TIMER_WITH_LEVEL(profile, "FileReadTime", file_scan_profile::IO, 1);
382
92.5k
    _adaptive_batch_predicted_rows_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
383
92.5k
            profile, "AdaptiveBatchPredictedRows", TUnit::UNIT, file_scan_profile::SCANNER, 1);
384
92.5k
    _adaptive_batch_actual_bytes_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
385
92.5k
            profile, "AdaptiveBatchActualBytes", TUnit::BYTES, file_scan_profile::SCANNER, 1);
386
92.5k
    _adaptive_batch_probe_count_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
387
92.5k
            profile, "AdaptiveBatchProbeCount", TUnit::UNIT, file_scan_profile::SCANNER, 1);
388
92.5k
    SCOPED_TIMER(_scanner_total_timer);
389
92.5k
    SCOPED_TIMER(_init_timer);
390
92.5k
    _file_cache_statistics = std::make_unique<io::FileCacheStatistics>();
391
92.5k
    _file_reader_stats = std::make_unique<io::FileReaderStats>();
392
92.5k
    RETURN_IF_ERROR(_init_io_ctx());
393
92.5k
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
394
92.5k
    _io_ctx->file_reader_stats = _file_reader_stats.get();
395
92.5k
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
396
92.5k
    return Status::OK();
397
92.5k
}
398
399
92.8k
Status FileScannerV2::_open_impl(RuntimeState* state) {
400
92.8k
    SCOPED_TIMER(_scanner_total_timer);
401
92.8k
    SCOPED_TIMER(_open_timer);
402
92.8k
    RETURN_IF_CANCELLED(state);
403
92.8k
    RETURN_IF_ERROR(Scanner::_open_impl(state));
404
92.8k
    RETURN_IF_ERROR(_get_next_scan_range(&_first_scan_range));
405
92.8k
    if (_first_scan_range) {
406
53.5k
        RETURN_IF_ERROR(_create_table_reader_for_format(_current_range, &_table_reader));
407
53.5k
        DORIS_CHECK(_table_reader != nullptr);
408
53.5k
        _table_reader_format = table_format_name(_current_range);
409
53.5k
        RETURN_IF_ERROR(_init_expr_ctxes());
410
53.5k
        RETURN_IF_ERROR(_init_table_reader(_current_range));
411
53.5k
    }
412
92.8k
    return Status::OK();
413
92.8k
}
414
415
260k
Status FileScannerV2::_get_next_scan_range(bool* has_next) {
416
260k
    SCOPED_TIMER(_get_next_range_timer);
417
260k
    DORIS_CHECK(has_next != nullptr);
418
260k
    RETURN_IF_ERROR(_split_source->get_next(has_next, &_current_range));
419
260k
    if (*has_next) {
420
129k
        RETURN_IF_ERROR(_validate_scan_range(*_params, _current_range));
421
129k
    }
422
260k
    return Status::OK();
423
260k
}
424
425
211k
Status FileScannerV2::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
426
211k
    SCOPED_TIMER(_scanner_total_timer);
427
211k
    SCOPED_TIMER(_get_block_timer);
428
339k
    while (true) {
429
339k
        RETURN_IF_CANCELLED(state);
430
339k
        if (!_has_prepared_split) {
431
220k
            RETURN_IF_ERROR(_prepare_next_split(eof));
432
220k
            if (*eof) {
433
92.2k
                return Status::OK();
434
92.2k
            }
435
220k
        }
436
437
247k
        {
438
247k
            if (_table_reader_rf_num != _applied_rf_num) {
439
16
                VExprContextSPtrs refreshed_conjuncts;
440
16
                RETURN_IF_ERROR(_build_table_conjuncts(&refreshed_conjuncts));
441
16
                RETURN_IF_ERROR(_table_reader->refresh_conjuncts(std::move(refreshed_conjuncts)));
442
16
                _table_reader_rf_num = _applied_rf_num;
443
16
            }
444
247k
            if (_should_run_adaptive_batch_size()) {
445
243k
                _table_reader->set_batch_size(_predict_reader_batch_rows());
446
243k
            }
447
247k
            const auto status = _table_reader->get_block(block, eof);
448
247k
            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
247k
            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
247k
            RETURN_IF_ERROR(status);
472
247k
        }
473
247k
        if (*eof) {
474
127k
            _state->update_num_finished_scan_range(1);
475
127k
            _has_prepared_split = false;
476
127k
            *eof = false;
477
127k
            continue;
478
127k
        }
479
119k
        _update_adaptive_batch_size(*block);
480
119k
        return Status::OK();
481
247k
    }
482
211k
}
483
484
119k
Status FileScannerV2::_filter_output_block(Block* block) {
485
119k
    return _contextualize_output_filter_status(Scanner::_filter_output_block(block),
486
119k
                                               _get_current_format_type());
487
119k
}
488
489
Status FileScannerV2::_contextualize_output_filter_status(Status status,
490
119k
                                                          TFileFormatType::type format_type) {
491
119k
    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
119k
    return status;
497
119k
}
498
499
220k
Status FileScannerV2::_prepare_next_split(bool* eos) {
500
220k
    SCOPED_TIMER(_prepare_split_timer);
501
221k
    while (true) {
502
221k
        bool has_next = _first_scan_range;
503
221k
        if (!_first_scan_range) {
504
168k
            RETURN_IF_ERROR(_get_next_scan_range(&has_next));
505
168k
        }
506
221k
        _first_scan_range = false;
507
221k
        if (!has_next || _should_stop) {
508
92.2k
            *eos = true;
509
92.2k
            return Status::OK();
510
92.2k
        }
511
129k
        DORIS_CHECK(_table_reader != nullptr);
512
129k
        _current_range_path = _current_range.path;
513
514
129k
        bool reader_rebuilt = false;
515
129k
        RETURN_IF_ERROR(_rebuild_table_reader_if_format_changed(_current_range, &reader_rebuilt));
516
129k
        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
129k
        const auto format_type = get_range_format_type(*_params, _current_range);
523
129k
        _init_adaptive_batch_size_state(format_type);
524
129k
        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
129k
            _table_reader->set_batch_size(_predict_reader_batch_rows());
531
129k
        }
532
129k
        std::map<std::string, Field> partition_values;
533
129k
        RETURN_IF_ERROR(_generate_partition_values(_current_range, &partition_values));
534
129k
        const auto status =
535
129k
                _prepare_table_reader_split(_current_range, std::move(partition_values));
536
129k
        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
129k
        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
129k
        RETURN_IF_ERROR(status);
553
129k
        if (_table_reader->current_split_pruned()) {
554
1.09k
            _state->update_num_finished_scan_range(1);
555
1.09k
            continue;
556
1.09k
        }
557
128k
        COUNTER_UPDATE(_file_counter, 1);
558
128k
        _has_prepared_split = true;
559
128k
        _table_reader_rf_num = _applied_rf_num;
560
128k
        *eos = false;
561
128k
        return Status::OK();
562
129k
    }
563
220k
}
564
565
53.4k
Status FileScannerV2::_init_table_reader(const TFileRangeDesc& range) {
566
53.4k
    const auto format_type = get_range_format_type(*_params, range);
567
53.4k
    format::FileFormat file_format;
568
53.4k
    RETURN_IF_ERROR(_to_file_format(format_type, &file_format));
569
53.4k
    DORIS_CHECK(_table_reader != nullptr);
570
571
53.4k
    VExprContextSPtrs table_conjuncts;
572
53.4k
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
573
53.4k
    std::optional<std::vector<format::GlobalIndex>> push_down_count_columns;
574
53.4k
    const auto& push_down_count_slot_ids = _local_state->get_push_down_count_slot_ids();
575
53.4k
    if (push_down_count_slot_ids.has_value()) {
576
53.4k
        push_down_count_columns.emplace();
577
53.4k
        push_down_count_columns->reserve(push_down_count_slot_ids->size());
578
53.4k
        for (const auto slot_id : *push_down_count_slot_ids) {
579
712
            const auto global_index_it = _slot_id_to_global_index.find(slot_id);
580
712
            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
712
            push_down_count_columns->push_back(global_index_it->second);
586
712
        }
587
53.4k
    }
588
53.4k
    RETURN_IF_ERROR(_table_reader->init({
589
53.4k
            .projected_columns = _projected_columns,
590
53.4k
            .conjuncts = std::move(table_conjuncts),
591
53.4k
            .format = file_format,
592
53.4k
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
593
53.4k
            .io_ctx = _io_ctx,
594
53.4k
            .runtime_state = _state,
595
53.4k
            .scanner_profile = _local_state->scanner_profile(),
596
53.4k
            .file_slot_descs = &_file_slot_descs,
597
53.4k
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
598
53.4k
            .push_down_count_columns = std::move(push_down_count_columns),
599
53.4k
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
600
53.4k
    }));
601
53.4k
    return Status::OK();
602
53.4k
}
603
604
Status FileScannerV2::_rebuild_table_reader_if_format_changed(const TFileRangeDesc& range,
605
129k
                                                              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
129k
    auto table_format = table_format_name(range);
618
129k
    if (table_format == _table_reader_format) {
619
129k
        *rebuilt = false;
620
129k
        return Status::OK();
621
129k
    }
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
53.5k
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
631
53.5k
    DORIS_CHECK(reader != nullptr);
632
53.5k
    const auto file_format = get_range_format_type(*_params, range);
633
53.5k
    if (file_format == TFileFormatType::FORMAT_WAL) {
634
0
        *reader = std::make_unique<format::wal::WalTableReader>();
635
0
        return Status::OK();
636
0
    }
637
53.5k
    const auto table_format = table_format_name(range);
638
53.5k
    if (table_format == "NotSet" || table_format == "tvf") {
639
4.12k
        *reader = std::make_unique<format::TableReader>();
640
49.3k
    } else if (table_format == "hive") {
641
18.7k
        *reader = format::hive::HiveReader::create_unique();
642
30.5k
    } else if (table_format == "iceberg") {
643
22.0k
        if (is_iceberg_position_deletes_sys_table(range)) {
644
190
            *reader = std::make_unique<format::iceberg::IcebergPositionDeleteSysTableV2Reader>();
645
21.8k
        } else if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
646
1.72k
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
647
20.1k
        } else {
648
20.1k
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
649
20.1k
        }
650
22.0k
    } else if (table_format == "paimon") {
651
6.65k
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
652
6.65k
    } else if (table_format == "hudi") {
653
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
654
1.91k
    } else if (table_format == "jdbc") {
655
1.18k
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
656
1.18k
    } 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
732
    } else if (table_format == "trino_connector") {
662
632
        *reader = std::make_unique<format::trino_connector::TrinoConnectorJniReader>();
663
632
    } else if (table_format == "remote_doris") {
664
98
        *reader = std::make_unique<format::remote_doris::RemoteDorisReader>();
665
98
    } else if (table_format == "adbc") {
666
0
        *reader = std::make_unique<format::adbc::AdbcReader>();
667
2
    } else {
668
2
        return Status::NotSupported("FileScannerV2 does not support table format {}", table_format);
669
2
    }
670
53.4k
    return Status::OK();
671
53.5k
}
672
673
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range,
674
129k
                                                  std::map<std::string, Field> partition_values) {
675
129k
    format::FileFormat current_split_format;
676
129k
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
677
129k
    VExprContextSPtrs conjuncts;
678
129k
    RETURN_IF_ERROR(_build_table_conjuncts(&conjuncts));
679
129k
    VExprContextSPtrs partition_prune_conjuncts;
680
129k
    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
11.9k
        RETURN_IF_ERROR(_build_table_conjuncts(&partition_prune_conjuncts));
685
11.9k
    }
686
129k
    RETURN_IF_ERROR(_table_reader->prepare_split({
687
129k
            .partition_values = std::move(partition_values),
688
129k
            .conjuncts = std::move(conjuncts),
689
129k
            .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
129k
            .all_runtime_filters_applied = _applied_rf_num == _total_rf_num,
693
129k
            .condition_cache_digest = _current_condition_cache_digest(),
694
129k
            .cache = _kv_cache,
695
129k
            .current_range = range,
696
129k
            .current_split_format = current_split_format,
697
129k
            .global_rowid_context = _create_global_rowid_context(range),
698
129k
    }));
699
129k
    return Status::OK();
700
129k
}
701
702
376k
bool FileScannerV2::_should_skip_not_found(const Status& status, bool ignore_not_found) {
703
376k
    return ignore_not_found && status.is<ErrorCode::NOT_FOUND>();
704
376k
}
705
706
376k
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
376k
    return !stopped && status.is<ErrorCode::END_OF_FILE>();
712
376k
}
713
714
6.30k
bool FileScannerV2::_should_enable_file_meta_cache() const {
715
6.30k
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
716
6.31k
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
717
6.30k
}
718
719
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
720
129k
        const TFileRangeDesc& range) const {
721
129k
    if (!_need_global_rowid_column) {
722
123k
        return std::nullopt;
723
123k
    }
724
6.29k
    auto& id_file_map = _state->get_id_file_map();
725
6.29k
    DORIS_CHECK(id_file_map != nullptr);
726
6.29k
    const auto file_id = id_file_map->get_file_mapping_id(
727
6.29k
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
728
6.29k
                                          range, _should_enable_file_meta_cache()));
729
6.29k
    return format::GlobalRowIdContext {
730
6.29k
            .version = IdManager::ID_VERSION,
731
6.29k
            .backend_id = BackendOptions::get_backend_id(),
732
6.29k
            .file_id = file_id,
733
6.29k
    };
734
129k
}
735
736
Status FileScannerV2::_generate_partition_values(
737
129k
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
738
129k
    DORIS_CHECK(partition_values != nullptr);
739
129k
    partition_values->clear();
740
129k
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
741
108k
        return Status::OK();
742
108k
    }
743
20.7k
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
744
53.3k
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
745
32.5k
        const auto& key = range.columns_from_path_keys[idx];
746
32.5k
        const auto it = _partition_slot_descs.find(key);
747
32.5k
        if (it == _partition_slot_descs.end()) {
748
14.8k
            continue;
749
14.8k
        }
750
17.6k
        const auto& value = range.columns_from_path[idx];
751
17.6k
        const bool is_null = range.__isset.columns_from_path_is_null &&
752
17.6k
                             idx < range.columns_from_path_is_null.size() &&
753
17.6k
                             range.columns_from_path_is_null[idx];
754
17.6k
        Field field;
755
17.6k
        DORIS_CHECK(it->second.slot_desc != nullptr);
756
17.6k
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
757
17.6k
        partition_values->emplace(it->second.canonical_name, std::move(field));
758
17.6k
    }
759
20.7k
    return Status::OK();
760
20.7k
}
761
762
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
763
                                             const std::string& value, bool is_null,
764
17.6k
                                             Field* field) const {
765
17.6k
    DORIS_CHECK(slot_desc != nullptr);
766
17.6k
    DORIS_CHECK(field != nullptr);
767
17.6k
    if (is_null) {
768
1.35k
        *field = Field::create_field<TYPE_NULL>(Null());
769
1.35k
        return Status::OK();
770
1.35k
    }
771
16.3k
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
772
16.3k
    auto column = data_type->create_column();
773
16.3k
    auto serde = data_type->get_serde();
774
16.3k
    DataTypeSerDe::FormatOptions options;
775
16.3k
    options.converted_from_string = true;
776
16.3k
    StringRef ref(value.data(), value.size());
777
16.3k
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
778
16.3k
    DORIS_CHECK(column->size() == 1);
779
16.3k
    *field = (*column)[0];
780
16.3k
    return Status::OK();
781
16.3k
}
782
783
53.4k
Status FileScannerV2::_init_expr_ctxes() {
784
53.4k
    _slot_id_to_desc.clear();
785
53.4k
    _slot_id_to_global_index.clear();
786
53.4k
    _partition_slot_descs.clear();
787
53.4k
    _file_slot_descs.clear();
788
294k
    for (const auto* slot_desc : _output_tuple_desc->slots()) {
789
294k
        _slot_id_to_desc.emplace(slot_desc->id(), slot_desc);
790
294k
    }
791
53.4k
    DORIS_CHECK(_table_reader != nullptr);
792
53.4k
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
793
53.4k
    return Status::OK();
794
53.4k
}
795
796
53.5k
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
797
53.5k
    _projected_columns.clear();
798
53.5k
    _projected_columns.reserve(_params->required_slots.size());
799
53.5k
    _need_global_rowid_column = false;
800
53.5k
    format::ProjectedColumnBuildContext build_context {
801
53.5k
            .scan_params = _params,
802
53.5k
            .range = &_current_range,
803
53.5k
            .runtime_state = _state,
804
53.5k
    };
805
    // Field 34 is the rollout boundary for root and nested exact-name precedence.
806
53.5k
    const bool prefer_exact_name_match =
807
53.5k
            !_params->__isset.history_schema_info || supports_iceberg_scan_semantics_v1(_params);
808
809
349k
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
810
295k
        const auto& slot_info = _params->required_slots[slot_idx];
811
295k
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
812
295k
        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
295k
        auto column = _build_table_column(it->second);
817
295k
        build_context.slot_desc = it->second;
818
295k
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
819
4.26k
            _need_global_rowid_column = true;
820
4.26k
        }
821
295k
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
822
295k
        build_context.schema_column.reset();
823
295k
        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
295k
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
828
295k
                &column, it->second,
829
295k
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr,
830
295k
                prefer_exact_name_match));
831
295k
        if (is_partition_slot(slot_info, column.name)) {
832
15.8k
            column.is_partition_key = true;
833
15.8k
            _partition_slot_descs.emplace(
834
15.8k
                    column.name,
835
15.8k
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
836
15.8k
            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
279k
        } else if (is_data_file_slot(slot_info, column.name)) {
842
274k
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
843
274k
        }
844
295k
        const auto global_index = format::GlobalIndex(slot_idx);
845
295k
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
846
295k
        _projected_columns.push_back(std::move(column));
847
295k
    }
848
53.5k
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
849
53.5k
    return Status::OK();
850
53.5k
}
851
852
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
853
295k
                                          VExprContextSPtr* ctx) const {
854
295k
    DORIS_CHECK(ctx != nullptr);
855
295k
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
856
289k
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
857
289k
    }
858
859
6.37k
    if (_params->__isset.default_value_of_src_slot) {
860
6.37k
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
861
6.37k
        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
6.37k
    }
865
6.33k
    return Status::OK();
866
6.33k
}
867
868
295k
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
869
295k
    DORIS_CHECK(slot_desc != nullptr);
870
295k
    format::ColumnDefinition column;
871
    // TODO(gabriel): why always BY_NAME here?
872
295k
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
873
295k
    column.name = slot_desc->col_name();
874
295k
    column.type = slot_desc->get_data_type_ptr();
875
295k
    return column;
876
295k
}
877
878
194k
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
879
194k
    DORIS_CHECK(conjuncts != nullptr);
880
194k
    conjuncts->clear();
881
194k
    conjuncts->reserve(_conjuncts.size());
882
194k
    for (const auto& conjunct : _conjuncts) {
883
127k
        VExprSPtr root;
884
127k
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
885
127k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
886
127k
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
887
127k
    }
888
194k
    return Status::OK();
889
194k
}
890
891
119k
TFileFormatType::type FileScannerV2::_get_current_format_type() const {
892
119k
    return get_range_format_type(*_params, _current_range);
893
119k
}
894
895
Status FileScannerV2::_to_file_format(TFileFormatType::type format_type,
896
182k
                                      format::FileFormat* file_format) {
897
182k
    DORIS_CHECK(file_format != nullptr);
898
182k
    switch (format_type) {
899
112k
    case TFileFormatType::FORMAT_PARQUET:
900
112k
        *file_format = format::FileFormat::PARQUET;
901
112k
        return Status::OK();
902
48.8k
    case TFileFormatType::FORMAT_ORC:
903
48.8k
        *file_format = format::FileFormat::ORC;
904
48.8k
        return Status::OK();
905
11.3k
    case TFileFormatType::FORMAT_JNI:
906
11.3k
        *file_format = format::FileFormat::JNI;
907
11.3k
        return Status::OK();
908
1.51k
    case TFileFormatType::FORMAT_CSV_PLAIN:
909
1.51k
    case TFileFormatType::FORMAT_CSV_GZ:
910
1.51k
    case TFileFormatType::FORMAT_CSV_BZ2:
911
1.51k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
912
1.51k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
913
1.51k
    case TFileFormatType::FORMAT_CSV_LZOP:
914
1.51k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
915
1.52k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
916
1.52k
    case TFileFormatType::FORMAT_PROTO:
917
1.52k
        *file_format = format::FileFormat::CSV;
918
1.52k
        return Status::OK();
919
7.28k
    case TFileFormatType::FORMAT_TEXT:
920
7.28k
        *file_format = format::FileFormat::TEXT;
921
7.28k
        return Status::OK();
922
1.18k
    case TFileFormatType::FORMAT_JSON:
923
1.18k
        *file_format = format::FileFormat::JSON;
924
1.18k
        return Status::OK();
925
1
    case TFileFormatType::FORMAT_NATIVE:
926
1
        *file_format = format::FileFormat::NATIVE;
927
1
        return Status::OK();
928
197
    case TFileFormatType::FORMAT_ARROW:
929
197
        *file_format = format::FileFormat::ARROW;
930
197
        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
182k
    }
938
182k
}
939
940
92.6k
Status FileScannerV2::_init_io_ctx() {
941
92.6k
    _io_ctx = create_file_scan_io_context(_state);
942
92.6k
    return Status::OK();
943
92.6k
}
944
945
129k
void FileScannerV2::_reset_adaptive_batch_size_state() {
946
129k
    _block_size_predictor.reset();
947
129k
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
948
129k
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
949
129k
}
950
951
129k
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
952
129k
    _reset_adaptive_batch_size_state();
953
129k
    if (!_should_enable_adaptive_batch_size(format_type)) {
954
98
        return;
955
98
    }
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
129k
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
961
129k
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
962
129k
            _state->batch_size());
963
129k
}
964
965
129k
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
966
129k
    if (!config::enable_adaptive_batch_size) {
967
0
        return false;
968
0
    }
969
129k
    switch (format_type) {
970
85.2k
    case TFileFormatType::FORMAT_PARQUET:
971
117k
    case TFileFormatType::FORMAT_ORC:
972
117k
    case TFileFormatType::FORMAT_CSV_PLAIN:
973
117k
    case TFileFormatType::FORMAT_CSV_GZ:
974
117k
    case TFileFormatType::FORMAT_CSV_BZ2:
975
117k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
976
117k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
977
117k
    case TFileFormatType::FORMAT_CSV_LZOP:
978
117k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
979
117k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
980
117k
    case TFileFormatType::FORMAT_PROTO:
981
122k
    case TFileFormatType::FORMAT_TEXT:
982
123k
    case TFileFormatType::FORMAT_JSON:
983
129k
    case TFileFormatType::FORMAT_JNI:
984
129k
        return true;
985
98
    default:
986
98
        return false;
987
129k
    }
988
129k
}
989
990
366k
bool FileScannerV2::_should_run_adaptive_batch_size() const {
991
366k
    DORIS_CHECK(_table_reader != nullptr);
992
366k
    return _should_run_adaptive_batch_size(_block_size_predictor != nullptr,
993
366k
                                           _table_reader->current_split_uses_metadata_count());
994
366k
}
995
996
bool FileScannerV2::_should_run_adaptive_batch_size(bool predictor_initialized,
997
366k
                                                    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
366k
    return predictor_initialized && !current_split_uses_metadata_count;
1002
366k
}
1003
1004
372k
size_t FileScannerV2::_predict_reader_batch_rows() {
1005
372k
    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
372k
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
1009
372k
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
1010
372k
    return predicted_rows;
1011
372k
}
1012
1013
119k
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
1014
119k
    if (!_should_run_adaptive_batch_size()) {
1015
3.26k
        return;
1016
3.26k
    }
1017
116k
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(block.bytes()));
1018
116k
    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
116k
    if (!_block_size_predictor->has_history()) {
1025
60.8k
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
1026
60.8k
    }
1027
116k
    _block_size_predictor->update(block);
1028
116k
}
1029
1030
92.9k
Status FileScannerV2::close(RuntimeState* state) {
1031
92.9k
    SCOPED_TIMER(_scanner_total_timer);
1032
92.9k
    SCOPED_TIMER(_close_timer);
1033
92.9k
    if (!_try_close()) {
1034
1
        return Status::OK();
1035
1
    }
1036
92.9k
    if (_table_reader != nullptr) {
1037
53.5k
        const auto close_status = _table_reader->close();
1038
53.5k
        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
53.5k
        _report_condition_cache_profile();
1045
53.5k
        _table_reader.reset();
1046
53.5k
    }
1047
92.9k
    return Scanner::close(state);
1048
92.9k
}
1049
1050
92.9k
void FileScannerV2::try_stop() {
1051
92.9k
    Scanner::try_stop();
1052
92.9k
    if (_io_ctx) {
1053
92.9k
        _io_ctx->should_stop = true;
1054
92.9k
    }
1055
92.9k
}
1056
1057
149k
void FileScannerV2::update_realtime_counters() {
1058
149k
    if (_file_reader_stats == nullptr) {
1059
0
        return;
1060
0
    }
1061
149k
    DORIS_CHECK(_file_cache_statistics != nullptr);
1062
149k
    const int64_t bytes_read = cast_set<int64_t>(_file_reader_stats->read_bytes);
1063
149k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1064
149k
    const auto file_type =
1065
149k
            _current_range.__isset.file_type
1066
149k
                    ? _current_range.file_type
1067
149k
                    : (_params != nullptr && _params->__isset.file_type ? _params->file_type
1068
48.8k
                                                                        : TFileType::FILE_LOCAL);
1069
149k
    const auto deltas = _collect_realtime_counter_deltas(
1070
149k
            *_file_reader_stats, *_file_cache_statistics, _uncached_reader_bytes_storage(file_type),
1071
149k
            &_last_read_bytes, &_last_read_rows, &_last_bytes_read_from_local,
1072
149k
            &_last_bytes_read_from_remote);
1073
1074
149k
    COUNTER_UPDATE(local_state->_scan_bytes, deltas.scan_bytes);
1075
149k
    COUNTER_UPDATE(local_state->_scan_rows, deltas.scan_rows);
1076
1077
149k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(deltas.scan_rows);
1078
149k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(deltas.scan_bytes);
1079
149k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
1080
149k
            deltas.scan_bytes_from_local_storage);
1081
149k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_remote_storage(
1082
149k
            deltas.scan_bytes_from_remote_storage);
1083
1084
149k
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
1085
149k
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1086
149k
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1087
1088
149k
    DorisMetrics::instance()->query_scan_bytes->increment(deltas.scan_bytes);
1089
149k
    DorisMetrics::instance()->query_scan_rows->increment(deltas.scan_rows);
1090
149k
    DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1091
149k
            deltas.scan_bytes_from_local_storage);
1092
149k
    DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
1093
149k
            deltas.scan_bytes_from_remote_storage);
1094
149k
}
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
150k
        int64_t* last_bytes_read_from_remote) {
1102
150k
    DORIS_CHECK(last_read_bytes != nullptr);
1103
150k
    DORIS_CHECK(last_read_rows != nullptr);
1104
150k
    DORIS_CHECK(last_bytes_read_from_local != nullptr);
1105
150k
    DORIS_CHECK(last_bytes_read_from_remote != nullptr);
1106
1107
150k
    const int64_t read_bytes = cast_set<int64_t>(file_reader_stats.read_bytes);
1108
150k
    const int64_t read_rows = cast_set<int64_t>(file_reader_stats.read_rows);
1109
150k
    const int64_t bytes_read_from_local = file_cache_statistics.bytes_read_from_local;
1110
150k
    const int64_t bytes_read_from_remote = file_cache_statistics.bytes_read_from_remote;
1111
150k
    DORIS_CHECK(read_bytes >= *last_read_bytes);
1112
150k
    DORIS_CHECK(read_rows >= *last_read_rows);
1113
150k
    DORIS_CHECK(bytes_read_from_local >= *last_bytes_read_from_local);
1114
150k
    DORIS_CHECK(bytes_read_from_remote >= *last_bytes_read_from_remote);
1115
1116
150k
    RealtimeCounterDeltas deltas;
1117
150k
    deltas.scan_rows = read_rows - *last_read_rows;
1118
150k
    deltas.scan_bytes = read_bytes - *last_read_bytes;
1119
    // Peer cache is a known cache source, but it is not remote object storage.
1120
150k
    const bool has_cache_source_stats = file_cache_statistics.num_local_io_total != 0 ||
1121
150k
                                        file_cache_statistics.num_remote_io_total != 0 ||
1122
150k
                                        file_cache_statistics.num_peer_io_total != 0 ||
1123
150k
                                        bytes_read_from_local != 0 || bytes_read_from_remote != 0 ||
1124
150k
                                        file_cache_statistics.bytes_read_from_peer != 0;
1125
150k
    if (!has_cache_source_stats) {
1126
137k
        switch (uncached_reader_bytes_storage) {
1127
9.32k
        case UncachedReaderBytesStorage::LOCAL:
1128
9.32k
            deltas.scan_bytes_from_local_storage = deltas.scan_bytes;
1129
9.32k
            break;
1130
127k
        case UncachedReaderBytesStorage::REMOTE:
1131
127k
            deltas.scan_bytes_from_remote_storage = deltas.scan_bytes;
1132
127k
            break;
1133
95
        case UncachedReaderBytesStorage::NONE:
1134
95
            break;
1135
137k
        }
1136
137k
    } else {
1137
12.7k
        deltas.scan_bytes_from_local_storage = bytes_read_from_local - *last_bytes_read_from_local;
1138
12.7k
        deltas.scan_bytes_from_remote_storage =
1139
12.7k
                bytes_read_from_remote - *last_bytes_read_from_remote;
1140
12.7k
    }
1141
1142
150k
    *last_read_bytes = read_bytes;
1143
150k
    *last_read_rows = read_rows;
1144
150k
    *last_bytes_read_from_local = bytes_read_from_local;
1145
150k
    *last_bytes_read_from_remote = bytes_read_from_remote;
1146
150k
    return deltas;
1147
150k
}
1148
1149
FileScannerV2::UncachedReaderBytesStorage FileScannerV2::_uncached_reader_bytes_storage(
1150
150k
        TFileType::type file_type) {
1151
150k
    switch (file_type) {
1152
9.31k
    case TFileType::FILE_LOCAL:
1153
9.31k
        return UncachedReaderBytesStorage::LOCAL;
1154
95
    case TFileType::FILE_STREAM:
1155
95
        return UncachedReaderBytesStorage::NONE;
1156
0
    case TFileType::FILE_BROKER:
1157
62.7k
    case TFileType::FILE_S3:
1158
140k
    case TFileType::FILE_HDFS:
1159
140k
    case TFileType::FILE_NET:
1160
140k
    case TFileType::FILE_HTTP:
1161
140k
        return UncachedReaderBytesStorage::REMOTE;
1162
150k
    }
1163
0
    DORIS_CHECK(false) << "unknown file type: " << file_type;
1164
0
    return UncachedReaderBytesStorage::NONE;
1165
150k
}
1166
1167
92.8k
void FileScannerV2::_collect_profile_before_close() {
1168
92.8k
    _report_file_reader_predicate_filtered_rows();
1169
92.8k
    Scanner::_collect_profile_before_close();
1170
92.8k
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1171
92.8k
        _profile != nullptr) {
1172
1.05k
        auto file_cache_delta = io::diff_file_cache_statistics(*_file_cache_statistics,
1173
1.05k
                                                               _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
1.05k
        file_cache_delta.remote_only_on_miss_triggered =
1177
1.05k
                _file_cache_statistics->remote_only_on_miss_triggered;
1178
1.05k
        file_cache_delta.remote_only_on_miss_threshold_bytes =
1179
1.05k
                _file_cache_statistics->remote_only_on_miss_threshold_bytes;
1180
1.05k
        file_cache_delta.peer_hosts = _file_cache_statistics->peer_hosts;
1181
1.05k
        _report_file_cache_profile(_profile, file_cache_delta);
1182
1.05k
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
1183
1.05k
                file_cache_delta.bytes_write_into_cache);
1184
1.05k
        _reported_file_cache_statistics = *_file_cache_statistics;
1185
1.05k
    }
1186
92.8k
    if (_file_reader_stats != nullptr) {
1187
92.7k
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
1188
92.7k
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1189
92.7k
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1190
92.7k
        const auto read_time = cast_set<int64_t>(_file_reader_stats->read_time_ns);
1191
92.7k
        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
92.7k
        COUNTER_UPDATE(_io_timer, read_time - _reported_io_read_time);
1196
92.7k
        _reported_io_read_time = read_time;
1197
92.7k
    }
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
92.8k
    _report_condition_cache_profile();
1201
92.8k
}
1202
1203
void FileScannerV2::_report_file_cache_profile(
1204
1.04k
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
1205
1.04k
    file_scan_profile::ensure_hierarchy(profile);
1206
1.04k
    io::FileCacheProfileReporter cache_profile(profile, file_scan_profile::IO);
1207
1.04k
    cache_profile.update(&file_cache_statistics);
1208
1.04k
}
1209
1210
92.8k
bool FileScannerV2::_should_update_load_counters() const {
1211
92.8k
    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
92.8k
    return (_params != nullptr && _params->__isset.file_type &&
1220
92.8k
            _params->file_type == TFileType::FILE_STREAM) ||
1221
92.8k
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
1222
92.8k
}
1223
1224
92.8k
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
92.8k
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
1227
92.8k
    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
3.14k
        _counter.num_rows_unselected += filtered_delta;
1232
3.14k
        _reported_predicate_filtered_rows = filtered_rows;
1233
3.14k
    }
1234
92.8k
}
1235
1236
146k
void FileScannerV2::_report_condition_cache_profile() {
1237
146k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1238
146k
    const int64_t hit_count =
1239
146k
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
1240
146k
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
1241
146k
    if (hit_delta > 0) {
1242
2.95k
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
1243
2.95k
        _reported_condition_cache_hit_count = hit_count;
1244
2.95k
    }
1245
146k
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
1246
146k
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
1247
146k
    if (filtered_delta > 0) {
1248
574
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
1249
574
        _reported_condition_cache_filtered_rows = filtered_rows;
1250
574
    }
1251
146k
}
1252
1253
} // namespace doris