Coverage Report

Created: 2026-07-19 16:21

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