Coverage Report

Created: 2026-07-15 13:51

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