Coverage Report

Created: 2026-07-25 14:45

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