Coverage Report

Created: 2026-07-14 18:57

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