Coverage Report

Created: 2026-08-04 06:47

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