Coverage Report

Created: 2026-07-23 19:28

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
7
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
187
7
    DORIS_CHECK(expr != nullptr);
188
7
    if (*expr == nullptr) {
189
0
        return Status::OK();
190
0
    }
191
7
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr->get());
192
7
        runtime_filter != nullptr) {
193
1
        auto impl = runtime_filter->get_impl();
194
1
        DORIS_CHECK(impl != nullptr);
195
1
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&impl, slot_id_to_global_index));
196
1
        runtime_filter->set_impl(std::move(impl));
197
1
        return Status::OK();
198
1
    }
199
6
    if ((*expr)->is_slot_ref()) {
200
4
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr->get());
201
4
        const auto global_index_it = slot_id_to_global_index.find(slot_ref->slot_id());
202
4
        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
3
        const auto global_index = global_index_it->second;
208
3
        *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
209
3
                                        cast_set<int>(global_index.value()), -1,
210
3
                                        slot_ref->data_type(), slot_ref->column_name());
211
3
        RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
212
3
        return Status::OK();
213
3
    }
214
2
    auto children = (*expr)->children();
215
2
    for (auto& child : children) {
216
2
        if (child == nullptr) {
217
0
            continue;
218
0
        }
219
2
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&child, slot_id_to_global_index));
220
2
    }
221
2
    (*expr)->set_children(std::move(children));
222
2
    return Status::OK();
223
2
}
224
225
} // namespace
226
227
#ifdef BE_TEST
228
FileScannerV2::FileScannerV2(RuntimeState* state, RuntimeProfile* profile,
229
                             std::unique_ptr<format::TableReader> table_reader)
230
4
        : Scanner(state, profile),
231
4
          _table_reader(std::move(table_reader)),
232
4
          _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
    VExprContextSPtrs table_conjuncts;
557
0
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
558
0
    std::optional<std::vector<format::GlobalIndex>> push_down_count_columns;
559
0
    const auto& push_down_count_slot_ids = _local_state->get_push_down_count_slot_ids();
560
0
    if (push_down_count_slot_ids.has_value()) {
561
0
        push_down_count_columns.emplace();
562
0
        push_down_count_columns->reserve(push_down_count_slot_ids->size());
563
0
        for (const auto slot_id : *push_down_count_slot_ids) {
564
0
            const auto global_index_it = _slot_id_to_global_index.find(slot_id);
565
0
            if (global_index_it == _slot_id_to_global_index.end()) {
566
0
                return Status::InternalError(
567
0
                        "Pushed-down COUNT argument is not a projected file scan slot, slot_id={}",
568
0
                        slot_id);
569
0
            }
570
0
            push_down_count_columns->push_back(global_index_it->second);
571
0
        }
572
0
    }
573
0
    RETURN_IF_ERROR(_table_reader->init({
574
0
            .projected_columns = _projected_columns,
575
0
            .conjuncts = std::move(table_conjuncts),
576
0
            .table_reader_owned_conjunct_count = _table_reader_owned_conjunct_count,
577
0
            .format = file_format,
578
0
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
579
0
            .io_ctx = _io_ctx,
580
0
            .runtime_state = _state,
581
0
            .scanner_profile = _local_state->scanner_profile(),
582
0
            .file_slot_descs = &_file_slot_descs,
583
0
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
584
0
            .push_down_count_columns = std::move(push_down_count_columns),
585
0
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
586
0
    }));
587
0
    _table_reader_applied_rf_num = _applied_rf_num;
588
    // RFs collected before TableReader initialization are already present in the full snapshot.
589
0
    _late_arrival_rf_conjuncts.clear();
590
0
    return Status::OK();
591
0
}
592
593
Status FileScannerV2::_create_table_reader_for_format(
594
0
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
595
0
    DORIS_CHECK(reader != nullptr);
596
0
    const auto table_format = table_format_name(range);
597
0
    if (table_format == "NotSet" || table_format == "tvf") {
598
0
        *reader = std::make_unique<format::TableReader>();
599
0
    } else if (table_format == "hive") {
600
0
        *reader = format::hive::HiveReader::create_unique();
601
0
    } else if (table_format == "iceberg") {
602
0
        if (is_iceberg_position_deletes_sys_table(range)) {
603
0
            *reader = std::make_unique<format::iceberg::IcebergPositionDeleteSysTableV2Reader>();
604
0
        } else if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
605
0
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
606
0
        } else {
607
0
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
608
0
        }
609
0
    } else if (table_format == "paimon") {
610
0
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
611
0
    } else if (table_format == "hudi") {
612
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
613
0
    } else if (table_format == "jdbc") {
614
0
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
615
0
    } else if (table_format == "max_compute") {
616
0
        const auto* mc_desc =
617
0
                static_cast<const MaxComputeTableDescriptor*>(_output_tuple_desc->table_desc());
618
0
        RETURN_IF_ERROR(mc_desc->init_status());
619
0
        *reader = std::make_unique<format::max_compute::MaxComputeJniReader>(mc_desc);
620
0
    } else if (table_format == "trino_connector") {
621
0
        *reader = std::make_unique<format::trino_connector::TrinoConnectorJniReader>();
622
0
    } else if (table_format == "remote_doris") {
623
0
        *reader = std::make_unique<format::remote_doris::RemoteDorisReader>();
624
0
    } else {
625
0
        return Status::NotSupported("FileScannerV2 does not support table format {}", table_format);
626
0
    }
627
0
    return Status::OK();
628
0
}
629
630
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range,
631
0
                                                  std::map<std::string, Field> partition_values) {
632
0
    format::FileFormat current_split_format;
633
0
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
634
0
    VExprContextSPtrs partition_prune_conjuncts;
635
0
    if (_state->query_options().enable_runtime_filter_partition_prune) {
636
0
        RETURN_IF_ERROR(_build_table_conjuncts(&partition_prune_conjuncts));
637
0
    }
638
0
    RETURN_IF_ERROR(_table_reader->prepare_split({
639
0
            .partition_values = std::move(partition_values),
640
0
            .partition_prune_conjuncts = std::move(partition_prune_conjuncts),
641
            // A metadata COUNT split may span scheduler turns. Do not enter that irreversible
642
            // synthetic-row path while a runtime filter can still arrive between batches.
643
0
            .all_runtime_filters_applied = _applied_rf_num == _total_rf_num,
644
0
            .condition_cache_digest = _current_condition_cache_digest(),
645
0
            .cache = _kv_cache,
646
0
            .current_range = range,
647
0
            .current_split_format = current_split_format,
648
0
            .global_rowid_context = _create_global_rowid_context(range),
649
0
    }));
650
0
    return Status::OK();
651
0
}
652
653
4
bool FileScannerV2::_should_skip_not_found(const Status& status, bool ignore_not_found) {
654
4
    return ignore_not_found && status.is<ErrorCode::NOT_FOUND>();
655
4
}
656
657
4
bool FileScannerV2::_should_skip_empty(const Status& status, bool stopped) {
658
    // Several readers use END_OF_FILE both for a valid zero-row split and for an interrupted IO.
659
    // For example, DeletionVectorReader returns END_OF_FILE("stop read.") after try_stop() marks
660
    // the shared IOContext. That status must unwind the stopped scanner; counting it as an empty
661
    // file would incorrectly finish the scan range and increment EmptyFileNum.
662
4
    return !stopped && status.is<ErrorCode::END_OF_FILE>();
663
4
}
664
665
0
bool FileScannerV2::_should_enable_file_meta_cache() const {
666
0
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
667
0
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
668
0
}
669
670
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
671
0
        const TFileRangeDesc& range) const {
672
0
    if (!_need_global_rowid_column) {
673
0
        return std::nullopt;
674
0
    }
675
0
    auto& id_file_map = _state->get_id_file_map();
676
0
    DORIS_CHECK(id_file_map != nullptr);
677
0
    const auto file_id = id_file_map->get_file_mapping_id(
678
0
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
679
0
                                          range, _should_enable_file_meta_cache()));
680
0
    return format::GlobalRowIdContext {
681
0
            .version = IdManager::ID_VERSION,
682
0
            .backend_id = BackendOptions::get_backend_id(),
683
0
            .file_id = file_id,
684
0
    };
685
0
}
686
687
Status FileScannerV2::_generate_partition_values(
688
0
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
689
0
    DORIS_CHECK(partition_values != nullptr);
690
0
    partition_values->clear();
691
0
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
692
0
        return Status::OK();
693
0
    }
694
0
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
695
0
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
696
0
        const auto& key = range.columns_from_path_keys[idx];
697
0
        const auto it = _partition_slot_descs.find(key);
698
0
        if (it == _partition_slot_descs.end()) {
699
0
            continue;
700
0
        }
701
0
        const auto& value = range.columns_from_path[idx];
702
0
        const bool is_null = range.__isset.columns_from_path_is_null &&
703
0
                             idx < range.columns_from_path_is_null.size() &&
704
0
                             range.columns_from_path_is_null[idx];
705
0
        Field field;
706
0
        DORIS_CHECK(it->second.slot_desc != nullptr);
707
0
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
708
0
        partition_values->emplace(it->second.canonical_name, std::move(field));
709
0
    }
710
0
    return Status::OK();
711
0
}
712
713
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
714
                                             const std::string& value, bool is_null,
715
0
                                             Field* field) const {
716
0
    DORIS_CHECK(slot_desc != nullptr);
717
0
    DORIS_CHECK(field != nullptr);
718
0
    if (is_null) {
719
0
        *field = Field::create_field<TYPE_NULL>(Null());
720
0
        return Status::OK();
721
0
    }
722
0
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
723
0
    auto column = data_type->create_column();
724
0
    auto serde = data_type->get_serde();
725
0
    DataTypeSerDe::FormatOptions options;
726
0
    options.converted_from_string = true;
727
0
    StringRef ref(value.data(), value.size());
728
0
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
729
0
    DORIS_CHECK(column->size() == 1);
730
0
    *field = (*column)[0];
731
0
    return Status::OK();
732
0
}
733
734
0
Status FileScannerV2::_init_expr_ctxes() {
735
0
    _slot_id_to_desc.clear();
736
0
    _slot_id_to_global_index.clear();
737
0
    _partition_slot_descs.clear();
738
0
    _file_slot_descs.clear();
739
0
    for (const auto* slot_desc : _output_tuple_desc->slots()) {
740
0
        _slot_id_to_desc.emplace(slot_desc->id(), slot_desc);
741
0
    }
742
0
    DORIS_CHECK(_table_reader != nullptr);
743
0
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
744
0
    return Status::OK();
745
0
}
746
747
0
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
748
0
    _projected_columns.clear();
749
0
    _projected_columns.reserve(_params->required_slots.size());
750
0
    _need_global_rowid_column = false;
751
0
    format::ProjectedColumnBuildContext build_context {
752
0
            .scan_params = _params,
753
0
            .range = &_current_range,
754
0
            .runtime_state = _state,
755
0
    };
756
    // Field 34 is the rollout boundary for root and nested exact-name precedence.
757
0
    const bool prefer_exact_name_match =
758
0
            !_params->__isset.history_schema_info || supports_iceberg_scan_semantics_v1(_params);
759
760
0
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
761
0
        const auto& slot_info = _params->required_slots[slot_idx];
762
0
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
763
0
        if (it == _slot_id_to_desc.end()) {
764
0
            return Status::InternalError("Unknown source slot descriptor, slot_id={}",
765
0
                                         slot_info.slot_id);
766
0
        }
767
0
        auto column = _build_table_column(it->second);
768
0
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
769
0
            _need_global_rowid_column = true;
770
0
        }
771
0
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
772
0
        build_context.schema_column.reset();
773
0
        RETURN_IF_ERROR(table_reader.annotate_projected_column(slot_info, &build_context, &column));
774
        // Build nested children from access paths generated by the slot's access-path
775
        // expressions. A projected column can therefore contain only a subset of the schema
776
        // column's nested children.
777
0
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
778
0
                &column, it->second,
779
0
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr,
780
0
                prefer_exact_name_match));
781
0
        if (is_partition_slot(slot_info, column.name)) {
782
0
            column.is_partition_key = true;
783
0
            _partition_slot_descs.emplace(
784
0
                    column.name,
785
0
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
786
0
            for (const auto& alias : column.name_mapping) {
787
0
                _partition_slot_descs.emplace(
788
0
                        alias,
789
0
                        PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
790
0
            }
791
0
        } else if (is_data_file_slot(slot_info, column.name)) {
792
0
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
793
0
        }
794
0
        const auto global_index = format::GlobalIndex(slot_idx);
795
0
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
796
0
        _projected_columns.push_back(std::move(column));
797
0
    }
798
0
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
799
0
    return Status::OK();
800
0
}
801
802
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
803
0
                                          VExprContextSPtr* ctx) const {
804
0
    DORIS_CHECK(ctx != nullptr);
805
0
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
806
0
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
807
0
    }
808
809
0
    if (_params->__isset.default_value_of_src_slot) {
810
0
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
811
0
        if (it != _params->default_value_of_src_slot.end() && !it->second.nodes.empty()) {
812
0
            return VExpr::create_expr_tree(it->second, *ctx);
813
0
        }
814
0
    }
815
0
    return Status::OK();
816
0
}
817
818
0
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
819
0
    DORIS_CHECK(slot_desc != nullptr);
820
0
    format::ColumnDefinition column;
821
    // TODO(gabriel): why always BY_NAME here?
822
0
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
823
0
    column.name = slot_desc->col_name();
824
0
    column.type = slot_desc->get_data_type_ptr();
825
0
    return column;
826
0
}
827
828
0
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
829
0
    return _build_table_conjuncts(_conjuncts, conjuncts);
830
0
}
831
832
Status FileScannerV2::_build_table_conjuncts(const VExprContextSPtrs& source,
833
0
                                             VExprContextSPtrs* conjuncts) const {
834
0
    DORIS_CHECK(conjuncts != nullptr);
835
0
    conjuncts->clear();
836
0
    conjuncts->reserve(source.size());
837
0
    for (const auto& conjunct : source) {
838
0
        VExprSPtr root;
839
0
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
840
0
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
841
0
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
842
0
    }
843
0
    return Status::OK();
844
0
}
845
846
3
size_t FileScannerV2::_safe_conjunct_prefix_size(const VExprContextSPtrs& conjuncts) {
847
4
    for (size_t conjunct_index = 0; conjunct_index < conjuncts.size(); ++conjunct_index) {
848
4
        if (!format::TableReader::is_safe_to_pre_execute(conjuncts[conjunct_index])) {
849
3
            return conjunct_index;
850
3
        }
851
4
    }
852
0
    return conjuncts.size();
853
3
}
854
855
3
void FileScannerV2::_initialize_scanner_residual_conjuncts() {
856
3
    _table_reader_owned_conjunct_count = _safe_conjunct_prefix_size(_conjuncts);
857
    // Preserve the entire suffix, not only the unsafe expression. Otherwise a later safe
858
    // predicate could run below Scanner before a stateful/error-preserving ordering barrier.
859
3
    _scanner_residual_conjuncts.assign(
860
3
            _conjuncts.begin() + cast_set<ptrdiff_t>(_table_reader_owned_conjunct_count),
861
3
            _conjuncts.end());
862
3
    _refresh_scanner_residual_profile();
863
3
}
864
865
3
void FileScannerV2::_refresh_scanner_residual_profile() {
866
3
    if (_scanner_profile == nullptr || _scanner_residual_conjuncts.empty()) {
867
0
        return;
868
0
    }
869
3
    std::ostringstream predicates;
870
3
    predicates << "[";
871
7
    for (size_t conjunct_index = 0; conjunct_index < _scanner_residual_conjuncts.size();
872
4
         ++conjunct_index) {
873
4
        if (conjunct_index > 0) {
874
1
            predicates << ", ";
875
1
        }
876
4
        predicates << _scanner_residual_conjuncts[conjunct_index]->root()->debug_string();
877
4
    }
878
3
    predicates << "]";
879
3
    _scanner_profile->add_info_string("ScannerResidualPredicates", predicates.str());
880
3
}
881
882
0
Status FileScannerV2::_sync_table_reader_conjuncts() {
883
0
    if (_table_reader == nullptr) {
884
0
        return Status::OK();
885
0
    }
886
0
    if (_table_reader_applied_rf_num == _applied_rf_num) {
887
0
        return Status::OK();
888
0
    }
889
0
    VExprContextSPtrs appended;
890
0
    RETURN_IF_ERROR(_build_table_conjuncts(_late_arrival_rf_conjuncts, &appended));
891
0
    const size_t owned_count = _scanner_residual_conjuncts.empty()
892
0
                                       ? _safe_conjunct_prefix_size(_late_arrival_rf_conjuncts)
893
0
                                       : 0;
894
    // Preserve existing expression state and append the identity-tracked RF delta. Cost sorting
895
    // may move a late RF ahead of an old stateful predicate in the full scanner snapshot.
896
0
    RETURN_IF_ERROR(_table_reader->append_conjuncts_with_ownership(appended, owned_count));
897
0
    _table_reader_owned_conjunct_count += owned_count;
898
0
    _scanner_residual_conjuncts.insert(
899
0
            _scanner_residual_conjuncts.end(),
900
0
            _late_arrival_rf_conjuncts.begin() + cast_set<ptrdiff_t>(owned_count),
901
0
            _late_arrival_rf_conjuncts.end());
902
0
    _refresh_scanner_residual_profile();
903
0
    _late_arrival_rf_conjuncts.clear();
904
0
    _table_reader_applied_rf_num = _applied_rf_num;
905
0
    return Status::OK();
906
0
}
907
908
0
TFileFormatType::type FileScannerV2::_get_current_format_type() const {
909
0
    return get_range_format_type(*_params, _current_range);
910
0
}
911
912
Status FileScannerV2::_to_file_format(TFileFormatType::type format_type,
913
16
                                      format::FileFormat* file_format) {
914
16
    DORIS_CHECK(file_format != nullptr);
915
16
    switch (format_type) {
916
1
    case TFileFormatType::FORMAT_PARQUET:
917
1
        *file_format = format::FileFormat::PARQUET;
918
1
        return Status::OK();
919
1
    case TFileFormatType::FORMAT_ORC:
920
1
        *file_format = format::FileFormat::ORC;
921
1
        return Status::OK();
922
1
    case TFileFormatType::FORMAT_JNI:
923
1
        *file_format = format::FileFormat::JNI;
924
1
        return Status::OK();
925
1
    case TFileFormatType::FORMAT_CSV_PLAIN:
926
2
    case TFileFormatType::FORMAT_CSV_GZ:
927
3
    case TFileFormatType::FORMAT_CSV_BZ2:
928
4
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
929
5
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
930
6
    case TFileFormatType::FORMAT_CSV_LZOP:
931
7
    case TFileFormatType::FORMAT_CSV_DEFLATE:
932
8
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
933
9
    case TFileFormatType::FORMAT_PROTO:
934
9
        *file_format = format::FileFormat::CSV;
935
9
        return Status::OK();
936
1
    case TFileFormatType::FORMAT_TEXT:
937
1
        *file_format = format::FileFormat::TEXT;
938
1
        return Status::OK();
939
1
    case TFileFormatType::FORMAT_JSON:
940
1
        *file_format = format::FileFormat::JSON;
941
1
        return Status::OK();
942
1
    case TFileFormatType::FORMAT_NATIVE:
943
1
        *file_format = format::FileFormat::NATIVE;
944
1
        return Status::OK();
945
1
    case TFileFormatType::FORMAT_ARROW:
946
1
        *file_format = format::FileFormat::ARROW;
947
1
        return Status::OK();
948
0
    default:
949
0
        return Status::NotSupported("FileScannerV2 does not support file format {}",
950
0
                                    to_string(format_type));
951
16
    }
952
16
}
953
954
0
Status FileScannerV2::_init_io_ctx() {
955
0
    _io_ctx = create_file_scan_io_context(_state);
956
0
    return Status::OK();
957
0
}
958
959
0
void FileScannerV2::_reset_adaptive_batch_size_state() {
960
0
    _block_size_predictor.reset();
961
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
962
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
963
0
}
964
965
0
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
966
0
    _reset_adaptive_batch_size_state();
967
0
    if (!_should_enable_adaptive_batch_size(format_type)) {
968
0
        return;
969
0
    }
970
971
    // V2 native file readers do not have reliable row-width hints before the first batch. Start
972
    // every split with a small probe, then learn bytes-per-row from the materialized table block
973
    // and keep later batches close to RuntimeState::preferred_block_size_bytes().
974
0
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
975
0
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
976
0
            _state->batch_size());
977
0
}
978
979
0
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
980
0
    if (!config::enable_adaptive_batch_size) {
981
0
        return false;
982
0
    }
983
0
    switch (format_type) {
984
0
    case TFileFormatType::FORMAT_PARQUET:
985
0
    case TFileFormatType::FORMAT_ORC:
986
0
    case TFileFormatType::FORMAT_CSV_PLAIN:
987
0
    case TFileFormatType::FORMAT_CSV_GZ:
988
0
    case TFileFormatType::FORMAT_CSV_BZ2:
989
0
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
990
0
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
991
0
    case TFileFormatType::FORMAT_CSV_LZOP:
992
0
    case TFileFormatType::FORMAT_CSV_DEFLATE:
993
0
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
994
0
    case TFileFormatType::FORMAT_PROTO:
995
0
    case TFileFormatType::FORMAT_TEXT:
996
0
    case TFileFormatType::FORMAT_JSON:
997
0
    case TFileFormatType::FORMAT_JNI:
998
0
        return true;
999
0
    default:
1000
0
        return false;
1001
0
    }
1002
0
}
1003
1004
0
bool FileScannerV2::_should_run_adaptive_batch_size() const {
1005
0
    DORIS_CHECK(_table_reader != nullptr);
1006
0
    return _should_run_adaptive_batch_size(_block_size_predictor != nullptr,
1007
0
                                           _table_reader->current_split_uses_metadata_count());
1008
0
}
1009
1010
bool FileScannerV2::_should_run_adaptive_batch_size(bool predictor_initialized,
1011
3
                                                    bool current_split_uses_metadata_count) {
1012
    // Metadata COUNT emits synthetic rows and has no physical row width to learn from. A raw COUNT
1013
    // opcode is not sufficient here: unsupported argument counts, mappings, filters, or deletes
1014
    // make TableReader fall back to materializing normal rows, which still need adaptive batching.
1015
3
    return predictor_initialized && !current_split_uses_metadata_count;
1016
3
}
1017
1018
0
size_t FileScannerV2::_predict_reader_batch_rows() {
1019
0
    DORIS_CHECK(_block_size_predictor != nullptr);
1020
    // Before history exists this returns the probe row count; after update(), it returns roughly
1021
    // preferred_block_size_bytes / EWMA(bytes_per_row), capped by RuntimeState::batch_size().
1022
0
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
1023
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
1024
0
    return predicted_rows;
1025
0
}
1026
1027
0
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
1028
0
    if (!_should_run_adaptive_batch_size()) {
1029
0
        return;
1030
0
    }
1031
0
    const auto& stats = _table_reader->last_materialized_block_stats();
1032
0
    const size_t rows = stats.has_materialized_input ? stats.rows : block.rows();
1033
0
    const size_t bytes = stats.has_materialized_input ? stats.bytes : block.bytes();
1034
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(bytes));
1035
0
    if (rows == 0) {
1036
0
        return;
1037
0
    }
1038
    // Residual predicates run after wide table columns are materialized. Learn from that pre-filter
1039
    // shape so selective predicates cannot make the next reader batch dangerously large.
1040
0
    if (!_block_size_predictor->has_history()) {
1041
0
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
1042
0
    }
1043
0
    _block_size_predictor->update(rows, bytes);
1044
0
}
1045
1046
3
Status FileScannerV2::close(RuntimeState* state) {
1047
3
    SCOPED_TIMER(_scanner_total_timer);
1048
3
    SCOPED_TIMER(_close_timer);
1049
3
    if (!_try_close()) {
1050
1
        return Status::OK();
1051
1
    }
1052
2
    if (_table_reader != nullptr) {
1053
2
        const auto close_status = _table_reader->close();
1054
2
        if (!close_status.ok()) {
1055
            // Reserve the close attempt with _try_close(), but commit the scanner-level closed
1056
            // state only after the retained table reader has completed its retryable cleanup.
1057
1
            _is_closed.store(false);
1058
1
            return close_status;
1059
1
        }
1060
1
        _report_condition_cache_profile();
1061
1
        _table_reader.reset();
1062
1
    }
1063
1
    return Scanner::close(state);
1064
2
}
1065
1066
0
void FileScannerV2::try_stop() {
1067
0
    Scanner::try_stop();
1068
0
    if (_io_ctx) {
1069
0
        _io_ctx->should_stop = true;
1070
0
    }
1071
0
}
1072
1073
0
void FileScannerV2::update_realtime_counters() {
1074
0
    if (_file_reader_stats == nullptr) {
1075
0
        return;
1076
0
    }
1077
0
    DORIS_CHECK(_file_cache_statistics != nullptr);
1078
0
    const int64_t bytes_read = cast_set<int64_t>(_file_reader_stats->read_bytes);
1079
0
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1080
0
    const auto file_type =
1081
0
            _current_range.__isset.file_type
1082
0
                    ? _current_range.file_type
1083
0
                    : (_params != nullptr && _params->__isset.file_type ? _params->file_type
1084
0
                                                                        : TFileType::FILE_LOCAL);
1085
0
    const auto deltas = _collect_realtime_counter_deltas(
1086
0
            *_file_reader_stats, *_file_cache_statistics, _uncached_reader_bytes_storage(file_type),
1087
0
            &_last_read_bytes, &_last_read_rows, &_last_bytes_read_from_local,
1088
0
            &_last_bytes_read_from_remote);
1089
1090
0
    COUNTER_UPDATE(local_state->_scan_bytes, deltas.scan_bytes);
1091
0
    COUNTER_UPDATE(local_state->_scan_rows, deltas.scan_rows);
1092
1093
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(deltas.scan_rows);
1094
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(deltas.scan_bytes);
1095
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
1096
0
            deltas.scan_bytes_from_local_storage);
1097
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_remote_storage(
1098
0
            deltas.scan_bytes_from_remote_storage);
1099
1100
0
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
1101
0
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1102
0
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1103
1104
0
    DorisMetrics::instance()->query_scan_bytes->increment(deltas.scan_bytes);
1105
0
    DorisMetrics::instance()->query_scan_rows->increment(deltas.scan_rows);
1106
0
    DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1107
0
            deltas.scan_bytes_from_local_storage);
1108
0
    DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
1109
0
            deltas.scan_bytes_from_remote_storage);
1110
0
}
1111
1112
FileScannerV2::RealtimeCounterDeltas FileScannerV2::_collect_realtime_counter_deltas(
1113
        const io::FileReaderStats& file_reader_stats,
1114
        const io::FileCacheStatistics& file_cache_statistics,
1115
        UncachedReaderBytesStorage uncached_reader_bytes_storage, int64_t* last_read_bytes,
1116
        int64_t* last_read_rows, int64_t* last_bytes_read_from_local,
1117
7
        int64_t* last_bytes_read_from_remote) {
1118
7
    DORIS_CHECK(last_read_bytes != nullptr);
1119
7
    DORIS_CHECK(last_read_rows != nullptr);
1120
7
    DORIS_CHECK(last_bytes_read_from_local != nullptr);
1121
7
    DORIS_CHECK(last_bytes_read_from_remote != nullptr);
1122
1123
7
    const int64_t read_bytes = cast_set<int64_t>(file_reader_stats.read_bytes);
1124
7
    const int64_t read_rows = cast_set<int64_t>(file_reader_stats.read_rows);
1125
7
    const int64_t bytes_read_from_local = file_cache_statistics.bytes_read_from_local;
1126
7
    const int64_t bytes_read_from_remote = file_cache_statistics.bytes_read_from_remote;
1127
7
    DORIS_CHECK(read_bytes >= *last_read_bytes);
1128
7
    DORIS_CHECK(read_rows >= *last_read_rows);
1129
7
    DORIS_CHECK(bytes_read_from_local >= *last_bytes_read_from_local);
1130
7
    DORIS_CHECK(bytes_read_from_remote >= *last_bytes_read_from_remote);
1131
1132
7
    RealtimeCounterDeltas deltas;
1133
7
    deltas.scan_rows = read_rows - *last_read_rows;
1134
7
    deltas.scan_bytes = read_bytes - *last_read_bytes;
1135
    // Peer cache is a known cache source, but it is not remote object storage.
1136
7
    const bool has_cache_source_stats = file_cache_statistics.num_local_io_total != 0 ||
1137
7
                                        file_cache_statistics.num_remote_io_total != 0 ||
1138
7
                                        file_cache_statistics.num_peer_io_total != 0 ||
1139
7
                                        bytes_read_from_local != 0 || bytes_read_from_remote != 0 ||
1140
7
                                        file_cache_statistics.bytes_read_from_peer != 0;
1141
7
    if (!has_cache_source_stats) {
1142
4
        switch (uncached_reader_bytes_storage) {
1143
1
        case UncachedReaderBytesStorage::LOCAL:
1144
1
            deltas.scan_bytes_from_local_storage = deltas.scan_bytes;
1145
1
            break;
1146
3
        case UncachedReaderBytesStorage::REMOTE:
1147
3
            deltas.scan_bytes_from_remote_storage = deltas.scan_bytes;
1148
3
            break;
1149
0
        case UncachedReaderBytesStorage::NONE:
1150
0
            break;
1151
4
        }
1152
4
    } else {
1153
3
        deltas.scan_bytes_from_local_storage = bytes_read_from_local - *last_bytes_read_from_local;
1154
3
        deltas.scan_bytes_from_remote_storage =
1155
3
                bytes_read_from_remote - *last_bytes_read_from_remote;
1156
3
    }
1157
1158
7
    *last_read_bytes = read_bytes;
1159
7
    *last_read_rows = read_rows;
1160
7
    *last_bytes_read_from_local = bytes_read_from_local;
1161
7
    *last_bytes_read_from_remote = bytes_read_from_remote;
1162
7
    return deltas;
1163
7
}
1164
1165
FileScannerV2::UncachedReaderBytesStorage FileScannerV2::_uncached_reader_bytes_storage(
1166
0
        TFileType::type file_type) {
1167
0
    switch (file_type) {
1168
0
    case TFileType::FILE_LOCAL:
1169
0
        return UncachedReaderBytesStorage::LOCAL;
1170
0
    case TFileType::FILE_STREAM:
1171
0
        return UncachedReaderBytesStorage::NONE;
1172
0
    case TFileType::FILE_BROKER:
1173
0
    case TFileType::FILE_S3:
1174
0
    case TFileType::FILE_HDFS:
1175
0
    case TFileType::FILE_NET:
1176
0
    case TFileType::FILE_HTTP:
1177
0
        return UncachedReaderBytesStorage::REMOTE;
1178
0
    }
1179
0
    DORIS_CHECK(false) << "unknown file type: " << file_type;
1180
0
    return UncachedReaderBytesStorage::NONE;
1181
0
}
1182
1183
0
void FileScannerV2::_collect_profile_before_close() {
1184
0
    _report_file_reader_predicate_filtered_rows();
1185
0
    Scanner::_collect_profile_before_close();
1186
0
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1187
0
        _profile != nullptr) {
1188
0
        auto file_cache_delta = io::diff_file_cache_statistics(*_file_cache_statistics,
1189
0
                                                               _reported_file_cache_statistics);
1190
        // Profile collection can run more than once. Keep additive fields incremental while
1191
        // publishing high-water gauges and peer identities from the latest complete snapshot.
1192
0
        file_cache_delta.remote_only_on_miss_triggered =
1193
0
                _file_cache_statistics->remote_only_on_miss_triggered;
1194
0
        file_cache_delta.remote_only_on_miss_threshold_bytes =
1195
0
                _file_cache_statistics->remote_only_on_miss_threshold_bytes;
1196
0
        file_cache_delta.peer_hosts = _file_cache_statistics->peer_hosts;
1197
0
        _report_file_cache_profile(_profile, file_cache_delta);
1198
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
1199
0
                file_cache_delta.bytes_write_into_cache);
1200
0
        _reported_file_cache_statistics = *_file_cache_statistics;
1201
0
    }
1202
0
    if (_file_reader_stats != nullptr) {
1203
0
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
1204
0
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1205
0
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1206
0
        const auto read_time = cast_set<int64_t>(_file_reader_stats->read_time_ns);
1207
0
        DORIS_CHECK(read_time >= _reported_io_read_time);
1208
        // Some transports (for example Arrow Flight) record directly into IO, while filesystem
1209
        // reads arrive through FileReaderStats. Add only the new traced delta so both paths remain
1210
        // visible without double counting repeated profile publication.
1211
0
        COUNTER_UPDATE(_io_timer, read_time - _reported_io_read_time);
1212
0
        _reported_io_read_time = read_time;
1213
0
    }
1214
    // Query profiles can be collected before Scanner::close() runs. Publish condition-cache
1215
    // counters here as well, using deltas so this method and close() cannot double count.
1216
0
    _report_condition_cache_profile();
1217
0
}
1218
1219
void FileScannerV2::_report_file_cache_profile(
1220
1
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
1221
1
    file_scan_profile::ensure_hierarchy(profile);
1222
1
    io::FileCacheProfileReporter cache_profile(profile, file_scan_profile::IO);
1223
1
    cache_profile.update(&file_cache_statistics);
1224
1
}
1225
1226
0
bool FileScannerV2::_should_update_load_counters() const {
1227
0
    if (_is_load) {
1228
0
        return true;
1229
0
    }
1230
    // TVF based loads (e.g. http_stream, group commit relay) plan the load source as a
1231
    // tvf query scan without src tuple desc, so _is_load is false. But rows filtered by
1232
    // the load's WHERE clause still need to be reported as unselected rows. FILE_STREAM
1233
    // is only reachable from such load entries, never from normal queries, so use it to
1234
    // identify these scanners.
1235
0
    return (_params != nullptr && _params->__isset.file_type &&
1236
0
            _params->file_type == TFileType::FILE_STREAM) ||
1237
0
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
1238
0
}
1239
1240
0
void FileScannerV2::_report_file_reader_predicate_filtered_rows() {
1241
0
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->predicate_filtered_rows : 0;
1242
0
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
1243
0
    if (filtered_delta > 0) {
1244
        // FileReader and TableReader both report their owned predicate rows through the shared IO
1245
        // context. Preserve scanner-level load statistics without re-evaluating either predicate.
1246
0
        _counter.num_rows_unselected += filtered_delta;
1247
0
        _reported_predicate_filtered_rows = filtered_rows;
1248
0
    }
1249
0
}
1250
1251
1
void FileScannerV2::_report_condition_cache_profile() {
1252
1
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1253
1
    const int64_t hit_count =
1254
1
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
1255
1
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
1256
1
    if (hit_delta > 0) {
1257
0
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
1258
0
        _reported_condition_cache_hit_count = hit_count;
1259
0
    }
1260
1
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
1261
1
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
1262
1
    if (filtered_delta > 0) {
1263
0
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
1264
0
        _reported_condition_cache_filtered_rows = filtered_rows;
1265
0
    }
1266
1
}
1267
1268
} // namespace doris