Coverage Report

Created: 2026-07-11 20:10

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