Coverage Report

Created: 2026-07-16 15:25

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