Coverage Report

Created: 2026-07-13 02:04

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