Coverage Report

Created: 2026-07-21 18:06

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