Coverage Report

Created: 2026-07-12 19:37

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