Coverage Report

Created: 2026-07-14 18:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/file_scanner_v2.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exec/scan/file_scanner_v2.h"
19
20
#include <gen_cpp/Exprs_types.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
23
#include <algorithm>
24
#include <map>
25
#include <memory>
26
#include <optional>
27
#include <string>
28
#include <utility>
29
30
#include "common/cast_set.h"
31
#include "common/config.h"
32
#include "common/consts.h"
33
#include "common/metrics/doris_metrics.h"
34
#include "common/status.h"
35
#include "core/assert_cast.h"
36
#include "core/block/column_with_type_and_name.h"
37
#include "core/column/column.h"
38
#include "core/data_type/data_type.h"
39
#include "core/data_type/data_type_nullable.h"
40
#include "core/data_type_serde/data_type_serde.h"
41
#include "core/string_ref.h"
42
#include "exec/common/util.hpp"
43
#include "exec/operator/scan_operator.h"
44
#include "exec/scan/access_path_parser.h"
45
#include "exec/scan/file_scan_io_context.h"
46
#include "exprs/runtime_filter_expr.h"
47
#include "exprs/vexpr.h"
48
#include "exprs/vexpr_context.h"
49
#include "exprs/vslot_ref.h"
50
#include "format/format_common.h"
51
#include "format_v2/column_mapper.h"
52
#include "format_v2/jni/iceberg_sys_table_reader.h"
53
#include "format_v2/jni/jdbc_reader.h"
54
#include "format_v2/jni/max_compute_jni_reader.h"
55
#include "format_v2/jni/trino_connector_jni_reader.h"
56
#include "format_v2/table/hive_reader.h"
57
#include "format_v2/table/hudi_reader.h"
58
#include "format_v2/table/iceberg_reader.h"
59
#include "format_v2/table/paimon_reader.h"
60
#include "format_v2/table/remote_doris_reader.h"
61
#include "format_v2/table_reader.h"
62
#include "io/cache/block_file_cache_profile.h"
63
#include "io/fs/file_meta_cache.h"
64
#include "io/io_common.h"
65
#include "runtime/descriptors.h"
66
#include "runtime/exec_env.h"
67
#include "runtime/runtime_state.h"
68
#include "service/backend_options.h"
69
#include "storage/id_manager.h"
70
71
namespace doris {
72
namespace {
73
74
1.16k
std::string table_format_name(const TFileRangeDesc& range) {
75
1.16k
    return range.__isset.table_format_params ? range.table_format_params.table_format_type
76
1.16k
                                             : "NotSet";
77
1.16k
}
78
79
TFileFormatType::type get_range_format_type(const TFileScanRangeParams& params,
80
2.29k
                                            const TFileRangeDesc& range) {
81
2.29k
    return range.__isset.format_type ? range.format_type : params.format_type;
82
2.29k
}
83
84
593
bool is_supported_table_format(const TFileRangeDesc& range) {
85
593
    const auto table_format = table_format_name(range);
86
593
    if (table_format == "hudi" && range.__isset.table_format_params &&
87
593
        range.table_format_params.__isset.hudi_params &&
88
593
        range.table_format_params.hudi_params.__isset.delta_logs &&
89
593
        !range.table_format_params.hudi_params.delta_logs.empty()) {
90
        // Hudi MOR splits need log-file merge semantics and must stay on the existing JNI path.
91
        // FileScannerV2 currently supports native Parquet data files only.
92
1
        return false;
93
1
    }
94
592
    return table_format == "NotSet" || table_format == "tvf" || table_format == "hive" ||
95
592
           table_format == "iceberg" || table_format == "paimon" || table_format == "hudi";
96
593
}
97
98
3
bool is_supported_arrow_table_format(const TFileRangeDesc& range) {
99
3
    return table_format_name(range) == "remote_doris";
100
3
}
101
102
5
bool is_supported_jni_table_format(const TFileRangeDesc& range) {
103
5
    const auto table_format = table_format_name(range);
104
5
    if (table_format == "paimon") {
105
2
        return range.__isset.table_format_params &&
106
2
               range.table_format_params.__isset.paimon_params &&
107
2
               range.table_format_params.paimon_params.__isset.reader_type &&
108
2
               range.table_format_params.paimon_params.reader_type == TPaimonReaderType::PAIMON_JNI;
109
2
    }
110
3
    return table_format == "jdbc" || table_format == "iceberg" || table_format == "hudi" ||
111
3
           table_format == "max_compute" || table_format == "trino_connector";
112
5
}
113
114
375
bool is_csv_format(TFileFormatType::type format_type) {
115
375
    switch (format_type) {
116
339
    case TFileFormatType::FORMAT_CSV_PLAIN:
117
340
    case TFileFormatType::FORMAT_CSV_GZ:
118
341
    case TFileFormatType::FORMAT_CSV_BZ2:
119
342
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
120
343
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
121
344
    case TFileFormatType::FORMAT_CSV_LZOP:
122
345
    case TFileFormatType::FORMAT_CSV_DEFLATE:
123
346
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
124
347
    case TFileFormatType::FORMAT_PROTO:
125
347
        return true;
126
28
    default:
127
28
        return false;
128
375
    }
129
375
}
130
131
28
bool is_text_format(TFileFormatType::type format_type) {
132
28
    return format_type == TFileFormatType::FORMAT_TEXT;
133
28
}
134
135
26
bool is_json_format(TFileFormatType::type format_type) {
136
26
    return format_type == TFileFormatType::FORMAT_JSON;
137
26
}
138
139
6
bool is_native_format(TFileFormatType::type format_type) {
140
6
    return format_type == TFileFormatType::FORMAT_NATIVE;
141
6
}
142
143
3.50k
bool is_partition_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
144
3.50k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
145
3.50k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
146
18
        return false;
147
18
    }
148
3.48k
    return slot_info.__isset.category ? slot_info.category == TColumnCategory::PARTITION_KEY
149
3.48k
                                      : !slot_info.is_file_slot;
150
3.50k
}
151
152
3.50k
bool is_data_file_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
153
3.50k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
154
3.50k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
155
18
        return false;
156
18
    }
157
    // CSV and other non-self-describing formats need FE slot descriptors for only the columns that
158
    // are physically read from the file. Partition/default/virtual columns stay in TableReader's
159
    // mapping layer and are materialized after the file-local block is read. New FE provides an
160
    // explicit category; old FE falls back to `is_file_slot`.
161
3.49k
    if (slot_info.__isset.category) {
162
3.48k
        return slot_info.category == TColumnCategory::REGULAR ||
163
3.48k
               slot_info.category == TColumnCategory::GENERATED;
164
3.48k
    }
165
2
    return slot_info.is_file_slot;
166
3.49k
}
167
168
Status rewrite_slot_refs_to_global_index(
169
        VExprSPtr* expr,
170
73
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
171
73
    DORIS_CHECK(expr != nullptr);
172
73
    if (*expr == nullptr) {
173
0
        return Status::OK();
174
0
    }
175
73
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr->get());
176
73
        runtime_filter != nullptr) {
177
1
        auto impl = runtime_filter->get_impl();
178
1
        DORIS_CHECK(impl != nullptr);
179
1
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&impl, slot_id_to_global_index));
180
1
        runtime_filter->set_impl(std::move(impl));
181
1
        return Status::OK();
182
1
    }
183
72
    if ((*expr)->is_slot_ref()) {
184
31
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr->get());
185
31
        const auto global_index_it = slot_id_to_global_index.find(slot_ref->slot_id());
186
31
        if (global_index_it == slot_id_to_global_index.end()) {
187
1
            DORIS_CHECK(slot_ref->slot_id() >= 0);
188
1
            const auto global_index = format::GlobalIndex(cast_set<size_t>(slot_ref->slot_id()));
189
1
            *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
190
1
                                            cast_set<int>(global_index.value()), -1,
191
1
                                            slot_ref->data_type(), slot_ref->column_name());
192
1
            RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
193
1
            return Status::OK();
194
1
        }
195
30
        const auto global_index = global_index_it->second;
196
30
        *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
197
30
                                        cast_set<int>(global_index.value()), -1,
198
30
                                        slot_ref->data_type(), slot_ref->column_name());
199
30
        RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
200
30
        return Status::OK();
201
30
    }
202
41
    auto children = (*expr)->children();
203
41
    for (auto& child : children) {
204
41
        if (child == nullptr) {
205
0
            continue;
206
0
        }
207
41
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&child, slot_id_to_global_index));
208
41
    }
209
41
    (*expr)->set_children(std::move(children));
210
41
    return Status::OK();
211
41
}
212
213
} // namespace
214
215
#ifdef BE_TEST
216
FileScannerV2::FileScannerV2(RuntimeState* state, RuntimeProfile* profile,
217
                             std::unique_ptr<format::TableReader> table_reader)
218
        : Scanner(state, profile), _table_reader(std::move(table_reader)) {}
219
220
Status FileScannerV2::TEST_validate_scan_range(const TFileScanRangeParams& params,
221
                                               const TFileRangeDesc& range) {
222
    return _validate_scan_range(params, range);
223
}
224
225
Status FileScannerV2::TEST_to_file_format(TFileFormatType::type format_type,
226
                                          format::FileFormat* file_format) {
227
    return _to_file_format(format_type, file_format);
228
}
229
230
bool FileScannerV2::TEST_is_partition_slot(const TFileScanSlotInfo& slot_info,
231
                                           const std::string& column_name) {
232
    return is_partition_slot(slot_info, column_name);
233
}
234
235
bool FileScannerV2::TEST_is_data_file_slot(const TFileScanSlotInfo& slot_info,
236
                                           const std::string& column_name) {
237
    return is_data_file_slot(slot_info, column_name);
238
}
239
240
Status FileScannerV2::TEST_rewrite_slot_refs_to_global_index(
241
        VExprSPtr* expr,
242
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
243
    return rewrite_slot_refs_to_global_index(expr, slot_id_to_global_index);
244
}
245
246
FileScannerV2::RealtimeCounterDeltas FileScannerV2::TEST_collect_realtime_counter_deltas(
247
        const io::FileReaderStats& file_reader_stats,
248
        const io::FileCacheStatistics& file_cache_statistics,
249
        UncachedReaderBytesStorage uncached_reader_bytes_storage, int64_t* last_read_bytes,
250
        int64_t* last_read_rows, int64_t* last_bytes_read_from_local,
251
        int64_t* last_bytes_read_from_remote) {
252
    return _collect_realtime_counter_deltas(file_reader_stats, file_cache_statistics,
253
                                            uncached_reader_bytes_storage, last_read_bytes,
254
                                            last_read_rows, last_bytes_read_from_local,
255
                                            last_bytes_read_from_remote);
256
}
257
258
void FileScannerV2::TEST_report_file_cache_profile(
259
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
260
    _report_file_cache_profile(profile, file_cache_statistics);
261
}
262
263
bool FileScannerV2::TEST_should_skip_not_found(const Status& status, bool ignore_not_found) {
264
    return _should_skip_not_found(status, ignore_not_found);
265
}
266
#endif
267
268
604
bool FileScannerV2::is_supported(const TFileScanRangeParams& params, const TFileRangeDesc& range) {
269
604
    const auto format_type = get_range_format_type(params, range);
270
604
    if (format_type == TFileFormatType::FORMAT_PARQUET ||
271
604
        format_type == TFileFormatType::FORMAT_ORC) {
272
221
        return is_supported_table_format(range);
273
383
    } else if (format_type == TFileFormatType::FORMAT_ARROW) {
274
3
        return is_supported_arrow_table_format(range);
275
380
    } else if (format_type == TFileFormatType::FORMAT_JNI) {
276
5
        return is_supported_jni_table_format(range);
277
375
    } else if (is_csv_format(format_type) || is_text_format(format_type) ||
278
375
               is_json_format(format_type) || is_native_format(format_type)) {
279
372
        return is_supported_table_format(range);
280
372
    } else {
281
3
        LOG(WARNING) << "Unsupported file format type " << format_type << " for file scanner v2";
282
3
        return false;
283
3
    }
284
604
}
285
286
Status FileScannerV2::_validate_scan_range(const TFileScanRangeParams& params,
287
566
                                           const TFileRangeDesc& range) {
288
566
    if (!is_supported(params, range)) {
289
1
        return Status::NotSupported(
290
1
                "FileScannerV2 does not support table format {} with file format {}",
291
1
                table_format_name(range), to_string(get_range_format_type(params, range)));
292
1
    }
293
565
    return Status::OK();
294
566
}
295
296
FileScannerV2::FileScannerV2(RuntimeState* state, FileScanLocalState* local_state, int64_t limit,
297
                             std::shared_ptr<SplitSourceConnector> split_source,
298
                             RuntimeProfile* profile, ShardedKVCache* kv_cache,
299
                             const std::unordered_map<std::string, int>* colname_to_slot_id)
300
564
        : Scanner(state, local_state, limit, profile),
301
564
          _split_source(std::move(split_source)),
302
564
          _kv_cache(kv_cache) {
303
564
    (void)colname_to_slot_id;
304
564
    if (state->get_query_ctx() != nullptr &&
305
564
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
306
564
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
307
564
    } else {
308
0
        _params = _split_source->get_params();
309
0
    }
310
564
}
311
312
564
Status FileScannerV2::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
313
564
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
314
564
    _get_block_timer =
315
564
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerV2GetBlockTime", 1);
316
564
    _not_found_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
317
564
                                                     "NotFoundFileNum", TUnit::UNIT, 1);
318
564
    _file_counter =
319
564
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "FileNumber", TUnit::UNIT, 1);
320
564
    _file_read_bytes_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
321
564
                                                      "FileReadBytes", TUnit::BYTES, 1);
322
564
    _file_read_calls_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
323
564
                                                      "FileReadCalls", TUnit::UNIT, 1);
324
564
    _file_read_time_counter =
325
564
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileReadTime", 1);
326
564
    _adaptive_batch_predicted_rows_counter = ADD_COUNTER_WITH_LEVEL(
327
564
            _local_state->scanner_profile(), "AdaptiveBatchPredictedRows", TUnit::UNIT, 1);
328
564
    _adaptive_batch_actual_bytes_counter = ADD_COUNTER_WITH_LEVEL(
329
564
            _local_state->scanner_profile(), "AdaptiveBatchActualBytes", TUnit::BYTES, 1);
330
564
    _adaptive_batch_probe_count_counter = ADD_COUNTER_WITH_LEVEL(
331
564
            _local_state->scanner_profile(), "AdaptiveBatchProbeCount", TUnit::UNIT, 1);
332
564
    _file_cache_statistics = std::make_unique<io::FileCacheStatistics>();
333
564
    _file_reader_stats = std::make_unique<io::FileReaderStats>();
334
564
    RETURN_IF_ERROR(_init_io_ctx());
335
564
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
336
564
    _io_ctx->file_reader_stats = _file_reader_stats.get();
337
564
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
338
564
    return Status::OK();
339
564
}
340
341
564
Status FileScannerV2::_open_impl(RuntimeState* state) {
342
564
    RETURN_IF_CANCELLED(state);
343
564
    RETURN_IF_ERROR(Scanner::_open_impl(state));
344
564
    RETURN_IF_ERROR(_get_next_scan_range(&_first_scan_range));
345
564
    if (_first_scan_range) {
346
562
        RETURN_IF_ERROR(_create_table_reader_for_format(_current_range, &_table_reader));
347
562
        DORIS_CHECK(_table_reader != nullptr);
348
562
        RETURN_IF_ERROR(_init_expr_ctxes());
349
562
        RETURN_IF_ERROR(_init_table_reader(_current_range));
350
562
    }
351
564
    return Status::OK();
352
564
}
353
354
1.13k
Status FileScannerV2::_get_next_scan_range(bool* has_next) {
355
1.13k
    DORIS_CHECK(has_next != nullptr);
356
1.13k
    RETURN_IF_ERROR(_split_source->get_next(has_next, &_current_range));
357
1.13k
    if (*has_next) {
358
564
        RETURN_IF_ERROR(_validate_scan_range(*_params, _current_range));
359
564
    }
360
1.13k
    return Status::OK();
361
1.13k
}
362
363
1.32k
Status FileScannerV2::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
364
1.89k
    while (true) {
365
1.89k
        RETURN_IF_CANCELLED(state);
366
1.89k
        if (!_has_prepared_split) {
367
1.12k
            RETURN_IF_ERROR(_prepare_next_split(eof));
368
1.12k
            if (*eof) {
369
564
                return Status::OK();
370
564
            }
371
1.12k
        }
372
373
1.32k
        {
374
1.32k
            SCOPED_TIMER(_get_block_timer);
375
1.32k
            if (_should_run_adaptive_batch_size()) {
376
1.31k
                _table_reader->set_batch_size(_predict_reader_batch_rows());
377
1.31k
            }
378
1.32k
            const auto status = _table_reader->get_block(block, eof);
379
1.32k
            if (_should_skip_not_found(status, config::ignore_not_found_file_in_external_table)) {
380
0
                RETURN_IF_ERROR(_table_reader->abort_split());
381
0
                COUNTER_UPDATE(_not_found_file_counter, 1);
382
0
                _state->update_num_finished_scan_range(1);
383
0
                _has_prepared_split = false;
384
0
                block->clear_column_data(cast_set<int64_t>(_projected_columns.size()));
385
0
                *eof = false;
386
0
                continue;
387
0
            }
388
1.32k
            RETURN_IF_ERROR(status);
389
1.32k
        }
390
1.32k
        if (*eof) {
391
564
            _state->update_num_finished_scan_range(1);
392
564
            _has_prepared_split = false;
393
564
            *eof = false;
394
564
            continue;
395
564
        }
396
762
        _update_adaptive_batch_size(*block);
397
762
        return Status::OK();
398
1.32k
    }
399
1.32k
}
400
401
1.12k
Status FileScannerV2::_prepare_next_split(bool* eos) {
402
1.12k
    while (true) {
403
1.12k
        bool has_next = _first_scan_range;
404
1.12k
        if (!_first_scan_range) {
405
566
            RETURN_IF_ERROR(_get_next_scan_range(&has_next));
406
566
        }
407
1.12k
        _first_scan_range = false;
408
1.12k
        if (!has_next || _should_stop) {
409
564
            *eos = true;
410
564
            return Status::OK();
411
564
        }
412
562
        DORIS_CHECK(_table_reader != nullptr);
413
562
        _current_range_path = _current_range.path;
414
415
562
        const auto format_type = get_range_format_type(*_params, _current_range);
416
562
        _init_adaptive_batch_size_state(format_type);
417
562
        if (_should_run_adaptive_batch_size()) {
418
            // JNI readers open eagerly in prepare_split(). Seed the probe size first so readers
419
            // such as Paimon also use it for their first physical read batch.
420
560
            _table_reader->set_batch_size(_predict_reader_batch_rows());
421
560
        }
422
562
        std::map<std::string, Field> partition_values;
423
562
        RETURN_IF_ERROR(_generate_partition_values(_current_range, &partition_values));
424
562
        const auto status =
425
562
                _prepare_table_reader_split(_current_range, std::move(partition_values));
426
562
        if (_should_skip_not_found(status, config::ignore_not_found_file_in_external_table)) {
427
0
            RETURN_IF_ERROR(_table_reader->abort_split());
428
0
            COUNTER_UPDATE(_not_found_file_counter, 1);
429
0
            _state->update_num_finished_scan_range(1);
430
0
            continue;
431
0
        }
432
562
        RETURN_IF_ERROR(status);
433
562
        if (_table_reader->current_split_pruned()) {
434
0
            _state->update_num_finished_scan_range(1);
435
0
            continue;
436
0
        }
437
562
        COUNTER_UPDATE(_file_counter, 1);
438
562
        _has_prepared_split = true;
439
562
        *eos = false;
440
562
        return Status::OK();
441
562
    }
442
1.12k
}
443
444
562
Status FileScannerV2::_init_table_reader(const TFileRangeDesc& range) {
445
562
    const auto format_type = get_range_format_type(*_params, range);
446
562
    format::FileFormat file_format;
447
562
    RETURN_IF_ERROR(_to_file_format(format_type, &file_format));
448
562
    DORIS_CHECK(_table_reader != nullptr);
449
450
562
    VExprContextSPtrs table_conjuncts;
451
562
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
452
562
    RETURN_IF_ERROR(_table_reader->init({
453
562
            .projected_columns = _projected_columns,
454
562
            .conjuncts = std::move(table_conjuncts),
455
562
            .format = file_format,
456
562
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
457
562
            .io_ctx = _io_ctx,
458
562
            .runtime_state = _state,
459
562
            .scanner_profile = _local_state->scanner_profile(),
460
562
            .file_slot_descs = &_file_slot_descs,
461
562
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
462
562
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
463
562
    }));
464
562
    return Status::OK();
465
562
}
466
467
Status FileScannerV2::_create_table_reader_for_format(
468
562
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
469
562
    DORIS_CHECK(reader != nullptr);
470
562
    const auto table_format = table_format_name(range);
471
562
    if (table_format == "NotSet" || table_format == "tvf") {
472
562
        *reader = std::make_unique<format::TableReader>();
473
562
    } else if (table_format == "hive") {
474
0
        *reader = format::hive::HiveReader::create_unique();
475
0
    } else if (table_format == "iceberg") {
476
0
        if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
477
0
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
478
0
        } else {
479
0
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
480
0
        }
481
0
    } else if (table_format == "paimon") {
482
0
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
483
0
    } else if (table_format == "hudi") {
484
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
485
0
    } else if (table_format == "jdbc") {
486
0
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
487
0
    } else if (table_format == "max_compute") {
488
0
        const auto* mc_desc =
489
0
                static_cast<const MaxComputeTableDescriptor*>(_output_tuple_desc->table_desc());
490
0
        RETURN_IF_ERROR(mc_desc->init_status());
491
0
        *reader = std::make_unique<format::max_compute::MaxComputeJniReader>(mc_desc);
492
0
    } else if (table_format == "trino_connector") {
493
0
        *reader = std::make_unique<format::trino_connector::TrinoConnectorJniReader>();
494
0
    } else if (table_format == "remote_doris") {
495
0
        *reader = std::make_unique<format::remote_doris::RemoteDorisReader>();
496
0
    } else {
497
0
        return Status::NotSupported("FileScannerV2 does not support table format {}", table_format);
498
0
    }
499
562
    return Status::OK();
500
562
}
501
502
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range,
503
563
                                                  std::map<std::string, Field> partition_values) {
504
563
    format::FileFormat current_split_format;
505
563
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
506
563
    VExprContextSPtrs conjuncts;
507
563
    RETURN_IF_ERROR(_build_table_conjuncts(&conjuncts));
508
563
    VExprContextSPtrs partition_prune_conjuncts;
509
563
    if (_state->query_options().enable_runtime_filter_partition_prune) {
510
141
        RETURN_IF_ERROR(_build_table_conjuncts(&partition_prune_conjuncts));
511
141
    }
512
563
    RETURN_IF_ERROR(_table_reader->prepare_split({
513
563
            .partition_values = std::move(partition_values),
514
563
            .conjuncts = std::move(conjuncts),
515
563
            .partition_prune_conjuncts = std::move(partition_prune_conjuncts),
516
            // A metadata COUNT split may span scheduler turns. Do not enter that irreversible
517
            // synthetic-row path while a runtime filter can still arrive between batches.
518
563
            .all_runtime_filters_applied = _applied_rf_num == _total_rf_num,
519
563
            .cache = _kv_cache,
520
563
            .current_range = range,
521
563
            .current_split_format = current_split_format,
522
563
            .global_rowid_context = _create_global_rowid_context(range),
523
563
    }));
524
563
    return Status::OK();
525
563
}
526
527
1.89k
bool FileScannerV2::_should_skip_not_found(const Status& status, bool ignore_not_found) {
528
1.89k
    return ignore_not_found && status.is<ErrorCode::NOT_FOUND>();
529
1.89k
}
530
531
16
bool FileScannerV2::_should_enable_file_meta_cache() const {
532
16
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
533
16
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
534
16
}
535
536
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
537
563
        const TFileRangeDesc& range) const {
538
563
    if (!_need_global_rowid_column) {
539
547
        return std::nullopt;
540
547
    }
541
16
    auto& id_file_map = _state->get_id_file_map();
542
16
    DORIS_CHECK(id_file_map != nullptr);
543
16
    const auto file_id = id_file_map->get_file_mapping_id(
544
16
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
545
16
                                          range, _should_enable_file_meta_cache()));
546
16
    return format::GlobalRowIdContext {
547
16
            .version = IdManager::ID_VERSION,
548
16
            .backend_id = BackendOptions::get_backend_id(),
549
16
            .file_id = file_id,
550
16
    };
551
563
}
552
553
Status FileScannerV2::_generate_partition_values(
554
563
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
555
563
    DORIS_CHECK(partition_values != nullptr);
556
563
    partition_values->clear();
557
564
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
558
564
        return Status::OK();
559
564
    }
560
18.4E
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
561
18.4E
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
562
0
        const auto& key = range.columns_from_path_keys[idx];
563
0
        const auto it = _partition_slot_descs.find(key);
564
0
        if (it == _partition_slot_descs.end()) {
565
0
            continue;
566
0
        }
567
0
        const auto& value = range.columns_from_path[idx];
568
0
        const bool is_null = range.__isset.columns_from_path_is_null &&
569
0
                             idx < range.columns_from_path_is_null.size() &&
570
0
                             range.columns_from_path_is_null[idx];
571
0
        Field field;
572
0
        DORIS_CHECK(it->second.slot_desc != nullptr);
573
0
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
574
0
        partition_values->emplace(it->second.canonical_name, std::move(field));
575
0
    }
576
18.4E
    return Status::OK();
577
18.4E
}
578
579
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
580
                                             const std::string& value, bool is_null,
581
0
                                             Field* field) const {
582
0
    DORIS_CHECK(slot_desc != nullptr);
583
0
    DORIS_CHECK(field != nullptr);
584
0
    if (is_null) {
585
0
        *field = Field::create_field<TYPE_NULL>(Null());
586
0
        return Status::OK();
587
0
    }
588
0
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
589
0
    auto column = data_type->create_column();
590
0
    auto serde = data_type->get_serde();
591
0
    DataTypeSerDe::FormatOptions options;
592
0
    options.converted_from_string = true;
593
0
    StringRef ref(value.data(), value.size());
594
0
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
595
0
    DORIS_CHECK(column->size() == 1);
596
0
    *field = (*column)[0];
597
0
    return Status::OK();
598
0
}
599
600
562
Status FileScannerV2::_init_expr_ctxes() {
601
562
    _slot_id_to_desc.clear();
602
562
    _slot_id_to_global_index.clear();
603
562
    _partition_slot_descs.clear();
604
562
    _file_slot_descs.clear();
605
3.50k
    for (const auto* slot_desc : _output_tuple_desc->slots()) {
606
3.50k
        _slot_id_to_desc.emplace(slot_desc->id(), slot_desc);
607
3.50k
    }
608
562
    DORIS_CHECK(_table_reader != nullptr);
609
562
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
610
562
    return Status::OK();
611
562
}
612
613
562
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
614
562
    _projected_columns.clear();
615
562
    _projected_columns.reserve(_params->required_slots.size());
616
562
    _need_global_rowid_column = false;
617
562
    format::ProjectedColumnBuildContext build_context {
618
562
            .scan_params = _params,
619
562
            .range = &_current_range,
620
562
            .runtime_state = _state,
621
562
    };
622
623
4.06k
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
624
3.50k
        const auto& slot_info = _params->required_slots[slot_idx];
625
3.50k
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
626
3.50k
        if (it == _slot_id_to_desc.end()) {
627
0
            return Status::InternalError("Unknown source slot descriptor, slot_id={}",
628
0
                                         slot_info.slot_id);
629
0
        }
630
3.50k
        auto column = _build_table_column(it->second);
631
3.50k
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
632
16
            _need_global_rowid_column = true;
633
16
        }
634
3.50k
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
635
3.50k
        build_context.schema_column.reset();
636
3.50k
        RETURN_IF_ERROR(table_reader.annotate_projected_column(slot_info, &build_context, &column));
637
        // Build nested children from access paths generated by the slot's access-path
638
        // expressions. A projected column can therefore contain only a subset of the schema
639
        // column's nested children.
640
3.50k
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
641
3.50k
                &column, it->second,
642
3.50k
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr));
643
3.50k
        if (is_partition_slot(slot_info, column.name)) {
644
0
            column.is_partition_key = true;
645
0
            _partition_slot_descs.emplace(
646
0
                    column.name,
647
0
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
648
0
            for (const auto& alias : column.name_mapping) {
649
0
                _partition_slot_descs.emplace(
650
0
                        alias,
651
0
                        PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
652
0
            }
653
3.50k
        } else if (is_data_file_slot(slot_info, column.name)) {
654
3.48k
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
655
3.48k
        }
656
3.50k
        const auto global_index = format::GlobalIndex(slot_idx);
657
3.50k
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
658
3.50k
        _projected_columns.push_back(std::move(column));
659
3.50k
    }
660
562
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
661
562
    return Status::OK();
662
562
}
663
664
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
665
3.50k
                                          VExprContextSPtr* ctx) const {
666
3.50k
    DORIS_CHECK(ctx != nullptr);
667
3.50k
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
668
3.48k
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
669
3.48k
    }
670
671
16
    if (_params->__isset.default_value_of_src_slot) {
672
16
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
673
16
        if (it != _params->default_value_of_src_slot.end() && !it->second.nodes.empty()) {
674
0
            return VExpr::create_expr_tree(it->second, *ctx);
675
0
        }
676
16
    }
677
16
    return Status::OK();
678
16
}
679
680
3.50k
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
681
3.50k
    DORIS_CHECK(slot_desc != nullptr);
682
3.50k
    format::ColumnDefinition column;
683
    // TODO(gabriel): why always BY_NAME here?
684
3.50k
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
685
3.50k
    column.name = slot_desc->col_name();
686
3.50k
    column.type = slot_desc->get_data_type_ptr();
687
3.50k
    return column;
688
3.50k
}
689
690
1.26k
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
691
1.26k
    DORIS_CHECK(conjuncts != nullptr);
692
1.26k
    conjuncts->clear();
693
1.26k
    conjuncts->reserve(_conjuncts.size());
694
1.26k
    for (const auto& conjunct : _conjuncts) {
695
27
        VExprSPtr root;
696
27
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
697
27
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
698
27
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
699
27
    }
700
1.26k
    return Status::OK();
701
1.26k
}
702
703
0
TFileFormatType::type FileScannerV2::_get_current_format_type() const {
704
0
    return get_range_format_type(*_params, _current_range);
705
0
}
706
707
Status FileScannerV2::_to_file_format(TFileFormatType::type format_type,
708
1.14k
                                      format::FileFormat* file_format) {
709
1.14k
    DORIS_CHECK(file_format != nullptr);
710
1.14k
    switch (format_type) {
711
221
    case TFileFormatType::FORMAT_PARQUET:
712
221
        *file_format = format::FileFormat::PARQUET;
713
221
        return Status::OK();
714
195
    case TFileFormatType::FORMAT_ORC:
715
195
        *file_format = format::FileFormat::ORC;
716
195
        return Status::OK();
717
1
    case TFileFormatType::FORMAT_JNI:
718
1
        *file_format = format::FileFormat::JNI;
719
1
        return Status::OK();
720
672
    case TFileFormatType::FORMAT_CSV_PLAIN:
721
673
    case TFileFormatType::FORMAT_CSV_GZ:
722
674
    case TFileFormatType::FORMAT_CSV_BZ2:
723
675
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
724
676
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
725
677
    case TFileFormatType::FORMAT_CSV_LZOP:
726
678
    case TFileFormatType::FORMAT_CSV_DEFLATE:
727
679
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
728
680
    case TFileFormatType::FORMAT_PROTO:
729
680
        *file_format = format::FileFormat::CSV;
730
680
        return Status::OK();
731
1
    case TFileFormatType::FORMAT_TEXT:
732
1
        *file_format = format::FileFormat::TEXT;
733
1
        return Status::OK();
734
37
    case TFileFormatType::FORMAT_JSON:
735
37
        *file_format = format::FileFormat::JSON;
736
37
        return Status::OK();
737
5
    case TFileFormatType::FORMAT_NATIVE:
738
5
        *file_format = format::FileFormat::NATIVE;
739
5
        return Status::OK();
740
1
    case TFileFormatType::FORMAT_ARROW:
741
1
        *file_format = format::FileFormat::ARROW;
742
1
        return Status::OK();
743
0
    default:
744
0
        return Status::NotSupported("FileScannerV2 does not support file format {}",
745
0
                                    to_string(format_type));
746
1.14k
    }
747
1.14k
}
748
749
564
Status FileScannerV2::_init_io_ctx() {
750
564
    _io_ctx = create_file_scan_io_context(_state);
751
564
    return Status::OK();
752
564
}
753
754
563
void FileScannerV2::_reset_adaptive_batch_size_state() {
755
563
    _block_size_predictor.reset();
756
563
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
757
563
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
758
563
}
759
760
563
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
761
563
    _reset_adaptive_batch_size_state();
762
563
    if (!_should_enable_adaptive_batch_size(format_type)) {
763
2
        return;
764
2
    }
765
766
    // V2 native file readers do not have reliable row-width hints before the first batch. Start
767
    // every split with a small probe, then learn bytes-per-row from the materialized table block
768
    // and keep later batches close to RuntimeState::preferred_block_size_bytes().
769
561
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
770
561
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
771
561
            _state->batch_size());
772
561
}
773
774
564
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
775
564
    if (!config::enable_adaptive_batch_size) {
776
0
        return false;
777
0
    }
778
564
    switch (format_type) {
779
110
    case TFileFormatType::FORMAT_PARQUET:
780
207
    case TFileFormatType::FORMAT_ORC:
781
543
    case TFileFormatType::FORMAT_CSV_PLAIN:
782
543
    case TFileFormatType::FORMAT_CSV_GZ:
783
543
    case TFileFormatType::FORMAT_CSV_BZ2:
784
543
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
785
543
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
786
543
    case TFileFormatType::FORMAT_CSV_LZOP:
787
543
    case TFileFormatType::FORMAT_CSV_DEFLATE:
788
543
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
789
543
    case TFileFormatType::FORMAT_PROTO:
790
543
    case TFileFormatType::FORMAT_TEXT:
791
561
    case TFileFormatType::FORMAT_JSON:
792
561
    case TFileFormatType::FORMAT_JNI:
793
561
        return true;
794
2
    default:
795
2
        return false;
796
564
    }
797
564
}
798
799
2.65k
bool FileScannerV2::_should_run_adaptive_batch_size() const {
800
    // COUNT pushdown emits synthetic rows from file metadata and does not materialize file columns,
801
    // so there is no useful row-width sample to learn from.
802
2.65k
    return _block_size_predictor != nullptr &&
803
2.65k
           _local_state->get_push_down_agg_type() != TPushAggOp::type::COUNT;
804
2.65k
}
805
806
1.87k
size_t FileScannerV2::_predict_reader_batch_rows() {
807
1.87k
    DORIS_CHECK(_block_size_predictor != nullptr);
808
    // Before history exists this returns the probe row count; after update(), it returns roughly
809
    // preferred_block_size_bytes / EWMA(bytes_per_row), capped by RuntimeState::batch_size().
810
1.87k
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
811
1.87k
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
812
1.87k
    return predicted_rows;
813
1.87k
}
814
815
763
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
816
763
    if (!_should_run_adaptive_batch_size()) {
817
12
        return;
818
12
    }
819
751
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(block.bytes()));
820
751
    if (block.rows() == 0) {
821
0
        return;
822
0
    }
823
    // The sample is taken after TableReader has finalized file-local columns to table columns.
824
    // This matches the memory shape seen by upstream operators and catches very wide nested
825
    // columns, such as map/string payloads, after the first probe batch.
826
751
    if (!_block_size_predictor->has_history()) {
827
562
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
828
562
    }
829
751
    _block_size_predictor->update(block);
830
751
}
831
832
567
Status FileScannerV2::close(RuntimeState* state) {
833
567
    if (!_try_close()) {
834
1
        return Status::OK();
835
1
    }
836
566
    if (_table_reader != nullptr) {
837
564
        const auto close_status = _table_reader->close();
838
564
        if (!close_status.ok()) {
839
            // Reserve the close attempt with _try_close(), but commit the scanner-level closed
840
            // state only after the retained table reader has completed its retryable cleanup.
841
1
            _is_closed.store(false);
842
1
            return close_status;
843
1
        }
844
563
        _report_condition_cache_profile();
845
563
        _table_reader.reset();
846
563
    }
847
565
    return Scanner::close(state);
848
566
}
849
850
564
void FileScannerV2::try_stop() {
851
564
    Scanner::try_stop();
852
564
    if (_io_ctx) {
853
564
        _io_ctx->should_stop = true;
854
564
    }
855
564
}
856
857
1.06k
void FileScannerV2::update_realtime_counters() {
858
1.06k
    if (_file_reader_stats == nullptr) {
859
0
        return;
860
0
    }
861
1.06k
    DORIS_CHECK(_file_cache_statistics != nullptr);
862
1.06k
    const int64_t bytes_read = cast_set<int64_t>(_file_reader_stats->read_bytes);
863
1.06k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
864
1.06k
    const auto file_type =
865
1.06k
            _current_range.__isset.file_type
866
1.06k
                    ? _current_range.file_type
867
1.06k
                    : (_params != nullptr && _params->__isset.file_type ? _params->file_type
868
294
                                                                        : TFileType::FILE_LOCAL);
869
1.06k
    const auto deltas = _collect_realtime_counter_deltas(
870
1.06k
            *_file_reader_stats, *_file_cache_statistics, _uncached_reader_bytes_storage(file_type),
871
1.06k
            &_last_read_bytes, &_last_read_rows, &_last_bytes_read_from_local,
872
1.06k
            &_last_bytes_read_from_remote);
873
874
1.06k
    COUNTER_UPDATE(local_state->_scan_bytes, deltas.scan_bytes);
875
1.06k
    COUNTER_UPDATE(local_state->_scan_rows, deltas.scan_rows);
876
877
1.06k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(deltas.scan_rows);
878
1.06k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(deltas.scan_bytes);
879
1.06k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
880
1.06k
            deltas.scan_bytes_from_local_storage);
881
1.06k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_remote_storage(
882
1.06k
            deltas.scan_bytes_from_remote_storage);
883
884
1.06k
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
885
1.06k
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
886
1.06k
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
887
888
1.06k
    DorisMetrics::instance()->query_scan_bytes->increment(deltas.scan_bytes);
889
1.06k
    DorisMetrics::instance()->query_scan_rows->increment(deltas.scan_rows);
890
1.06k
    DorisMetrics::instance()->query_scan_bytes_from_local->increment(
891
1.06k
            deltas.scan_bytes_from_local_storage);
892
1.06k
    DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
893
1.06k
            deltas.scan_bytes_from_remote_storage);
894
1.06k
}
895
896
FileScannerV2::RealtimeCounterDeltas FileScannerV2::_collect_realtime_counter_deltas(
897
        const io::FileReaderStats& file_reader_stats,
898
        const io::FileCacheStatistics& file_cache_statistics,
899
        UncachedReaderBytesStorage uncached_reader_bytes_storage, int64_t* last_read_bytes,
900
        int64_t* last_read_rows, int64_t* last_bytes_read_from_local,
901
1.07k
        int64_t* last_bytes_read_from_remote) {
902
1.07k
    DORIS_CHECK(last_read_bytes != nullptr);
903
1.07k
    DORIS_CHECK(last_read_rows != nullptr);
904
1.07k
    DORIS_CHECK(last_bytes_read_from_local != nullptr);
905
1.07k
    DORIS_CHECK(last_bytes_read_from_remote != nullptr);
906
907
1.07k
    const int64_t read_bytes = cast_set<int64_t>(file_reader_stats.read_bytes);
908
1.07k
    const int64_t read_rows = cast_set<int64_t>(file_reader_stats.read_rows);
909
1.07k
    const int64_t bytes_read_from_local = file_cache_statistics.bytes_read_from_local;
910
1.07k
    const int64_t bytes_read_from_remote = file_cache_statistics.bytes_read_from_remote;
911
1.07k
    DORIS_CHECK(read_bytes >= *last_read_bytes);
912
1.07k
    DORIS_CHECK(read_rows >= *last_read_rows);
913
1.07k
    DORIS_CHECK(bytes_read_from_local >= *last_bytes_read_from_local);
914
1.07k
    DORIS_CHECK(bytes_read_from_remote >= *last_bytes_read_from_remote);
915
916
1.07k
    RealtimeCounterDeltas deltas;
917
1.07k
    deltas.scan_rows = read_rows - *last_read_rows;
918
1.07k
    deltas.scan_bytes = read_bytes - *last_read_bytes;
919
    // Peer cache is a known cache source, but it is not remote object storage.
920
1.07k
    const bool has_cache_source_stats = file_cache_statistics.num_local_io_total != 0 ||
921
1.07k
                                        file_cache_statistics.num_remote_io_total != 0 ||
922
1.07k
                                        file_cache_statistics.num_peer_io_total != 0 ||
923
1.07k
                                        bytes_read_from_local != 0 || bytes_read_from_remote != 0 ||
924
1.07k
                                        file_cache_statistics.bytes_read_from_peer != 0;
925
1.07k
    if (!has_cache_source_stats) {
926
1.07k
        switch (uncached_reader_bytes_storage) {
927
31
        case UncachedReaderBytesStorage::LOCAL:
928
31
            deltas.scan_bytes_from_local_storage = deltas.scan_bytes;
929
31
            break;
930
778
        case UncachedReaderBytesStorage::REMOTE:
931
778
            deltas.scan_bytes_from_remote_storage = deltas.scan_bytes;
932
778
            break;
933
262
        case UncachedReaderBytesStorage::NONE:
934
262
            break;
935
1.07k
        }
936
1.07k
    } else {
937
3
        deltas.scan_bytes_from_local_storage = bytes_read_from_local - *last_bytes_read_from_local;
938
3
        deltas.scan_bytes_from_remote_storage =
939
3
                bytes_read_from_remote - *last_bytes_read_from_remote;
940
3
    }
941
942
1.07k
    *last_read_bytes = read_bytes;
943
1.07k
    *last_read_rows = read_rows;
944
1.07k
    *last_bytes_read_from_local = bytes_read_from_local;
945
1.07k
    *last_bytes_read_from_remote = bytes_read_from_remote;
946
1.07k
    return deltas;
947
1.07k
}
948
949
FileScannerV2::UncachedReaderBytesStorage FileScannerV2::_uncached_reader_bytes_storage(
950
1.06k
        TFileType::type file_type) {
951
1.06k
    switch (file_type) {
952
30
    case TFileType::FILE_LOCAL:
953
30
        return UncachedReaderBytesStorage::LOCAL;
954
262
    case TFileType::FILE_STREAM:
955
262
        return UncachedReaderBytesStorage::NONE;
956
0
    case TFileType::FILE_BROKER:
957
775
    case TFileType::FILE_S3:
958
775
    case TFileType::FILE_HDFS:
959
775
    case TFileType::FILE_NET:
960
775
    case TFileType::FILE_HTTP:
961
775
        return UncachedReaderBytesStorage::REMOTE;
962
1.06k
    }
963
0
    DORIS_CHECK(false) << "unknown file type: " << file_type;
964
0
    return UncachedReaderBytesStorage::NONE;
965
1.06k
}
966
967
564
void FileScannerV2::_collect_profile_before_close() {
968
564
    _report_file_reader_predicate_filtered_rows();
969
564
    Scanner::_collect_profile_before_close();
970
564
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
971
564
        _profile != nullptr) {
972
0
        _report_file_cache_profile(_profile, *_file_cache_statistics);
973
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
974
0
                _file_cache_statistics->bytes_write_into_cache);
975
0
    }
976
564
    if (_file_reader_stats != nullptr) {
977
564
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
978
564
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
979
564
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
980
564
    }
981
    // Query profiles can be collected before Scanner::close() runs. Publish condition-cache
982
    // counters here as well, using deltas so this method and close() cannot double count.
983
564
    _report_condition_cache_profile();
984
564
}
985
986
void FileScannerV2::_report_file_cache_profile(
987
1
        RuntimeProfile* profile, const io::FileCacheStatistics& file_cache_statistics) {
988
1
    io::FileCacheProfileReporter cache_profile(profile);
989
1
    cache_profile.update(&file_cache_statistics);
990
1
}
991
992
564
bool FileScannerV2::_should_update_load_counters() const {
993
564
    if (_is_load) {
994
0
        return true;
995
0
    }
996
    // TVF based loads (e.g. http_stream, group commit relay) plan the load source as a
997
    // tvf query scan without src tuple desc, so _is_load is false. But rows filtered by
998
    // the load's WHERE clause still need to be reported as unselected rows. FILE_STREAM
999
    // is only reachable from such load entries, never from normal queries, so use it to
1000
    // identify these scanners.
1001
564
    return (_params != nullptr && _params->__isset.file_type &&
1002
564
            _params->file_type == TFileType::FILE_STREAM) ||
1003
564
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
1004
564
}
1005
1006
564
void FileScannerV2::_report_file_reader_predicate_filtered_rows() {
1007
564
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->predicate_filtered_rows : 0;
1008
564
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
1009
564
    if (filtered_delta > 0) {
1010
        // File readers can evaluate localized conjuncts before a block reaches Scanner. Count
1011
        // those rows as scanner-level unselected rows so load statistics stay identical no matter
1012
        // whether a predicate is pushed down or evaluated by Scanner::_filter_output_block().
1013
9
        _counter.num_rows_unselected += filtered_delta;
1014
9
        _reported_predicate_filtered_rows = filtered_rows;
1015
9
    }
1016
564
}
1017
1018
1.12k
void FileScannerV2::_report_condition_cache_profile() {
1019
1.12k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1020
1.12k
    const int64_t hit_count =
1021
1.12k
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
1022
1.12k
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
1023
1.12k
    if (hit_delta > 0) {
1024
0
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
1025
0
        _reported_condition_cache_hit_count = hit_count;
1026
0
    }
1027
1.12k
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
1028
1.12k
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
1029
1.12k
    if (filtered_delta > 0) {
1030
0
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
1031
0
        _reported_condition_cache_filtered_rows = filtered_rows;
1032
0
    }
1033
1.12k
}
1034
1035
} // namespace doris