Coverage Report

Created: 2026-07-21 13:38

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
102k
std::string table_format_name(const TFileRangeDesc& range) {
79
102k
    return range.__isset.table_format_params ? range.table_format_params.table_format_type
80
102k
                                             : "NotSet";
81
102k
}
82
83
TFileFormatType::type get_range_format_type(const TFileScanRangeParams& params,
84
244k
                                            const TFileRangeDesc& range) {
85
244k
    return range.__isset.format_type ? range.format_type : params.format_type;
86
244k
}
87
88
61.8k
bool is_supported_table_format(const TFileRangeDesc& range) {
89
61.8k
    const auto table_format = table_format_name(range);
90
61.8k
    if (table_format == "hudi" && range.__isset.table_format_params &&
91
61.8k
        range.table_format_params.__isset.hudi_params &&
92
61.8k
        range.table_format_params.hudi_params.__isset.delta_logs &&
93
61.8k
        !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
61.8k
    return table_format == "NotSet" || table_format == "tvf" || table_format == "hive" ||
99
61.8k
           table_format == "iceberg" || table_format == "paimon" || table_format == "hudi";
100
61.8k
}
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.7k
bool is_iceberg_position_deletes_sys_table(const TFileRangeDesc& range) {
119
17.7k
    return range.__isset.table_format_params &&
120
17.7k
           range.table_format_params.table_format_type == "iceberg" &&
121
17.7k
           range.table_format_params.__isset.iceberg_params &&
122
17.7k
           range.table_format_params.iceberg_params.__isset.content &&
123
17.7k
           (range.table_format_params.iceberg_params.content == kIcebergPositionDeleteContent ||
124
1.13k
            range.table_format_params.iceberg_params.content == kIcebergDeletionVectorContent);
125
17.7k
}
126
127
6.00k
bool is_csv_format(TFileFormatType::type format_type) {
128
6.00k
    switch (format_type) {
129
756
    case TFileFormatType::FORMAT_CSV_PLAIN:
130
757
    case TFileFormatType::FORMAT_CSV_GZ:
131
758
    case TFileFormatType::FORMAT_CSV_BZ2:
132
759
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
133
760
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
134
761
    case TFileFormatType::FORMAT_CSV_LZOP:
135
762
    case TFileFormatType::FORMAT_CSV_DEFLATE:
136
763
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
137
764
    case TFileFormatType::FORMAT_PROTO:
138
764
        return true;
139
5.24k
    default:
140
5.24k
        return false;
141
6.00k
    }
142
6.00k
}
143
144
5.24k
bool is_text_format(TFileFormatType::type format_type) {
145
5.24k
    return format_type == TFileFormatType::FORMAT_TEXT;
146
5.24k
}
147
148
589
bool is_json_format(TFileFormatType::type format_type) {
149
589
    return format_type == TFileFormatType::FORMAT_JSON;
150
589
}
151
152
6
bool is_native_format(TFileFormatType::type format_type) {
153
6
    return format_type == TFileFormatType::FORMAT_NATIVE;
154
6
}
155
156
238k
bool is_partition_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
157
238k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
158
238k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
159
4.69k
        return false;
160
4.69k
    }
161
234k
    return slot_info.__isset.category ? slot_info.category == TColumnCategory::PARTITION_KEY
162
18.4E
                                      : !slot_info.is_file_slot;
163
238k
}
164
165
226k
bool is_data_file_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
166
226k
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
167
226k
        column_name == BeConsts::ICEBERG_ROWID_COL) {
168
4.70k
        return false;
169
4.70k
    }
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
221k
    if (slot_info.__isset.category) {
175
221k
        return slot_info.category == TColumnCategory::REGULAR ||
176
221k
               slot_info.category == TColumnCategory::GENERATED;
177
221k
    }
178
6
    return slot_info.is_file_slot;
179
221k
}
180
181
Status rewrite_slot_refs_to_global_index(
182
        VExprSPtr* expr,
183
368k
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
184
368k
    DORIS_CHECK(expr != nullptr);
185
368k
    if (*expr == nullptr) {
186
0
        return Status::OK();
187
0
    }
188
368k
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr->get());
189
368k
        runtime_filter != nullptr) {
190
15.1k
        auto impl = runtime_filter->get_impl();
191
15.1k
        DORIS_CHECK(impl != nullptr);
192
15.1k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&impl, slot_id_to_global_index));
193
15.1k
        runtime_filter->set_impl(std::move(impl));
194
15.1k
        return Status::OK();
195
15.1k
    }
196
353k
    if ((*expr)->is_slot_ref()) {
197
112k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr->get());
198
112k
        const auto global_index_it = slot_id_to_global_index.find(slot_ref->slot_id());
199
112k
        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
112k
        const auto global_index = global_index_it->second;
205
112k
        *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
206
112k
                                        cast_set<int>(global_index.value()), -1,
207
112k
                                        slot_ref->data_type(), slot_ref->column_name());
208
112k
        RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
209
112k
        return Status::OK();
210
112k
    }
211
241k
    auto children = (*expr)->children();
212
245k
    for (auto& child : children) {
213
245k
        if (child == nullptr) {
214
0
            continue;
215
0
        }
216
245k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&child, slot_id_to_global_index));
217
245k
    }
218
241k
    (*expr)->set_children(std::move(children));
219
241k
    return Status::OK();
220
241k
}
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
61.9k
bool FileScannerV2::is_supported(const TFileScanRangeParams& params, const TFileRangeDesc& range) {
282
61.9k
    const auto format_type = get_range_format_type(params, range);
283
61.9k
    if (format_type == TFileFormatType::FORMAT_PARQUET ||
284
61.9k
        format_type == TFileFormatType::FORMAT_ORC) {
285
55.8k
        return is_supported_table_format(range);
286
55.8k
    } else if (format_type == TFileFormatType::FORMAT_ARROW) {
287
101
        return is_supported_arrow_table_format(range);
288
6.02k
    } else if (format_type == TFileFormatType::FORMAT_JNI) {
289
5
        return is_supported_jni_table_format(range);
290
6.01k
    } else if (is_csv_format(format_type) || is_text_format(format_type) ||
291
6.01k
               is_json_format(format_type) || is_native_format(format_type)) {
292
6.00k
        return is_supported_table_format(range);
293
6.00k
    } else {
294
10
        LOG(WARNING) << "Unsupported file format type " << format_type << " for file scanner v2";
295
10
        return false;
296
10
    }
297
61.9k
}
298
299
Status FileScannerV2::_validate_scan_range(const TFileScanRangeParams& params,
300
61.9k
                                           const TFileRangeDesc& range) {
301
61.9k
    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
61.9k
    return Status::OK();
307
61.9k
}
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
75.5k
        : Scanner(state, local_state, limit, profile),
314
75.5k
          _split_source(std::move(split_source)),
315
75.5k
          _kv_cache(kv_cache) {
316
75.5k
    (void)colname_to_slot_id;
317
75.5k
    if (state->get_query_ctx() != nullptr &&
318
75.5k
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
319
75.4k
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
320
75.4k
    } else {
321
14
        _params = _split_source->get_params();
322
14
    }
323
75.5k
}
324
325
75.2k
Status FileScannerV2::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
326
75.2k
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
327
75.2k
    _get_block_timer =
328
75.2k
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerV2GetBlockTime", 1);
329
75.2k
    _empty_file_counter =
330
75.2k
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "EmptyFileNum", TUnit::UNIT, 1);
331
75.2k
    _not_found_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
332
75.2k
                                                     "NotFoundFileNum", TUnit::UNIT, 1);
333
75.2k
    _file_counter =
334
75.2k
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "FileNumber", TUnit::UNIT, 1);
335
75.2k
    _file_read_bytes_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
336
75.2k
                                                      "FileReadBytes", TUnit::BYTES, 1);
337
75.2k
    _file_read_calls_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
338
75.2k
                                                      "FileReadCalls", TUnit::UNIT, 1);
339
75.2k
    _file_read_time_counter =
340
75.2k
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileReadTime", 1);
341
75.2k
    _adaptive_batch_predicted_rows_counter = ADD_COUNTER_WITH_LEVEL(
342
75.2k
            _local_state->scanner_profile(), "AdaptiveBatchPredictedRows", TUnit::UNIT, 1);
343
75.2k
    _adaptive_batch_actual_bytes_counter = ADD_COUNTER_WITH_LEVEL(
344
75.2k
            _local_state->scanner_profile(), "AdaptiveBatchActualBytes", TUnit::BYTES, 1);
345
75.2k
    _adaptive_batch_probe_count_counter = ADD_COUNTER_WITH_LEVEL(
346
75.2k
            _local_state->scanner_profile(), "AdaptiveBatchProbeCount", TUnit::UNIT, 1);
347
75.2k
    _file_cache_statistics = std::make_unique<io::FileCacheStatistics>();
348
75.2k
    _file_reader_stats = std::make_unique<io::FileReaderStats>();
349
75.2k
    RETURN_IF_ERROR(_init_io_ctx());
350
75.2k
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
351
75.2k
    _io_ctx->file_reader_stats = _file_reader_stats.get();
352
75.2k
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
353
75.2k
    return Status::OK();
354
75.2k
}
355
356
75.6k
Status FileScannerV2::_open_impl(RuntimeState* state) {
357
75.6k
    RETURN_IF_CANCELLED(state);
358
75.6k
    RETURN_IF_ERROR(Scanner::_open_impl(state));
359
75.6k
    RETURN_IF_ERROR(_get_next_scan_range(&_first_scan_range));
360
75.6k
    if (_first_scan_range) {
361
40.5k
        RETURN_IF_ERROR(_create_table_reader_for_format(_current_range, &_table_reader));
362
40.5k
        DORIS_CHECK(_table_reader != nullptr);
363
40.5k
        RETURN_IF_ERROR(_init_expr_ctxes());
364
40.5k
        RETURN_IF_ERROR(_init_table_reader(_current_range));
365
40.5k
    }
366
75.6k
    return Status::OK();
367
75.6k
}
368
369
171k
Status FileScannerV2::_get_next_scan_range(bool* has_next) {
370
171k
    DORIS_CHECK(has_next != nullptr);
371
171k
    RETURN_IF_ERROR(_split_source->get_next(has_next, &_current_range));
372
171k
    if (*has_next) {
373
61.9k
        RETURN_IF_ERROR(_validate_scan_range(*_params, _current_range));
374
61.9k
    }
375
171k
    return Status::OK();
376
171k
}
377
378
195k
Status FileScannerV2::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
379
256k
    while (true) {
380
256k
        RETURN_IF_CANCELLED(state);
381
256k
        if (!_has_prepared_split) {
382
136k
            RETURN_IF_ERROR(_prepare_next_split(eof));
383
136k
            if (*eof) {
384
75.0k
                return Status::OK();
385
75.0k
            }
386
136k
        }
387
388
181k
        {
389
181k
            SCOPED_TIMER(_get_block_timer);
390
181k
            if (_should_run_adaptive_batch_size()) {
391
179k
                _table_reader->set_batch_size(_predict_reader_batch_rows());
392
179k
            }
393
181k
            const auto status = _table_reader->get_block(block, eof);
394
181k
            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
181k
            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
181k
            RETURN_IF_ERROR(status);
418
181k
        }
419
181k
        if (*eof) {
420
61.0k
            _state->update_num_finished_scan_range(1);
421
61.0k
            _has_prepared_split = false;
422
61.0k
            *eof = false;
423
61.0k
            continue;
424
61.0k
        }
425
120k
        _update_adaptive_batch_size(*block);
426
120k
        return Status::OK();
427
181k
    }
428
195k
}
429
430
136k
Status FileScannerV2::_prepare_next_split(bool* eos) {
431
136k
    while (true) {
432
136k
        bool has_next = _first_scan_range;
433
136k
        if (!_first_scan_range) {
434
96.3k
            RETURN_IF_ERROR(_get_next_scan_range(&has_next));
435
96.3k
        }
436
136k
        _first_scan_range = false;
437
136k
        if (!has_next || _should_stop) {
438
75.0k
            *eos = true;
439
75.0k
            return Status::OK();
440
75.0k
        }
441
61.9k
        DORIS_CHECK(_table_reader != nullptr);
442
61.9k
        _current_range_path = _current_range.path;
443
444
61.9k
        const auto format_type = get_range_format_type(*_params, _current_range);
445
61.9k
        _init_adaptive_batch_size_state(format_type);
446
61.9k
        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
61.8k
            _table_reader->set_batch_size(_predict_reader_batch_rows());
453
61.8k
        }
454
61.9k
        std::map<std::string, Field> partition_values;
455
61.9k
        RETURN_IF_ERROR(_generate_partition_values(_current_range, &partition_values));
456
61.9k
        const auto status =
457
61.9k
                _prepare_table_reader_split(_current_range, std::move(partition_values));
458
61.9k
        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
61.9k
        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
61.9k
        RETURN_IF_ERROR(status);
475
61.9k
        if (_table_reader->current_split_pruned()) {
476
288
            _state->update_num_finished_scan_range(1);
477
288
            continue;
478
288
        }
479
61.6k
        COUNTER_UPDATE(_file_counter, 1);
480
61.6k
        _has_prepared_split = true;
481
61.6k
        *eos = false;
482
61.6k
        return Status::OK();
483
61.9k
    }
484
136k
}
485
486
40.5k
Status FileScannerV2::_init_table_reader(const TFileRangeDesc& range) {
487
40.5k
    const auto format_type = get_range_format_type(*_params, range);
488
40.5k
    format::FileFormat file_format;
489
40.5k
    RETURN_IF_ERROR(_to_file_format(format_type, &file_format));
490
40.5k
    DORIS_CHECK(_table_reader != nullptr);
491
492
40.5k
    VExprContextSPtrs table_conjuncts;
493
40.5k
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
494
40.5k
    std::optional<std::vector<format::GlobalIndex>> push_down_count_columns;
495
40.5k
    const auto& push_down_count_slot_ids = _local_state->get_push_down_count_slot_ids();
496
40.5k
    if (push_down_count_slot_ids.has_value()) {
497
40.5k
        push_down_count_columns.emplace();
498
40.5k
        push_down_count_columns->reserve(push_down_count_slot_ids->size());
499
40.5k
        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.5k
    }
509
40.5k
    RETURN_IF_ERROR(_table_reader->init({
510
40.5k
            .projected_columns = _projected_columns,
511
40.5k
            .conjuncts = std::move(table_conjuncts),
512
40.5k
            .format = file_format,
513
40.5k
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
514
40.5k
            .io_ctx = _io_ctx,
515
40.5k
            .runtime_state = _state,
516
40.5k
            .scanner_profile = _local_state->scanner_profile(),
517
40.5k
            .file_slot_descs = &_file_slot_descs,
518
40.5k
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
519
40.5k
            .push_down_count_columns = std::move(push_down_count_columns),
520
40.5k
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
521
40.5k
    }));
522
40.5k
    return Status::OK();
523
40.5k
}
524
525
Status FileScannerV2::_create_table_reader_for_format(
526
40.5k
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
527
40.5k
    DORIS_CHECK(reader != nullptr);
528
40.5k
    const auto table_format = table_format_name(range);
529
40.5k
    if (table_format == "NotSet" || table_format == "tvf") {
530
4.02k
        *reader = std::make_unique<format::TableReader>();
531
36.5k
    } else if (table_format == "hive") {
532
18.6k
        *reader = format::hive::HiveReader::create_unique();
533
18.6k
    } else if (table_format == "iceberg") {
534
17.8k
        if (is_iceberg_position_deletes_sys_table(range)) {
535
0
            *reader = std::make_unique<format::iceberg::IcebergPositionDeleteSysTableV2Reader>();
536
17.8k
        } else if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
537
0
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
538
17.8k
        } else {
539
17.8k
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
540
17.8k
        }
541
17.8k
    } else if (table_format == "paimon") {
542
0
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
543
88
    } else if (table_format == "hudi") {
544
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
545
88
    } else if (table_format == "jdbc") {
546
0
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
547
88
    } 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
88
    } 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.5k
    return Status::OK();
560
40.5k
}
561
562
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range,
563
61.9k
                                                  std::map<std::string, Field> partition_values) {
564
61.9k
    format::FileFormat current_split_format;
565
61.9k
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
566
61.9k
    VExprContextSPtrs conjuncts;
567
61.9k
    RETURN_IF_ERROR(_build_table_conjuncts(&conjuncts));
568
61.9k
    VExprContextSPtrs partition_prune_conjuncts;
569
61.9k
    if (_state->query_options().enable_runtime_filter_partition_prune) {
570
60.5k
        RETURN_IF_ERROR(_build_table_conjuncts(&partition_prune_conjuncts));
571
60.5k
    }
572
61.9k
    RETURN_IF_ERROR(_table_reader->prepare_split({
573
61.9k
            .partition_values = std::move(partition_values),
574
61.9k
            .conjuncts = std::move(conjuncts),
575
61.9k
            .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
61.9k
            .all_runtime_filters_applied = _applied_rf_num == _total_rf_num,
579
61.9k
            .condition_cache_digest = _current_condition_cache_digest(),
580
61.9k
            .cache = _kv_cache,
581
61.9k
            .current_range = range,
582
61.9k
            .current_split_format = current_split_format,
583
61.9k
            .global_rowid_context = _create_global_rowid_context(range),
584
61.9k
    }));
585
61.9k
    return Status::OK();
586
61.9k
}
587
588
243k
bool FileScannerV2::_should_skip_not_found(const Status& status, bool ignore_not_found) {
589
243k
    return ignore_not_found && status.is<ErrorCode::NOT_FOUND>();
590
243k
}
591
592
243k
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
243k
    return !stopped && status.is<ErrorCode::END_OF_FILE>();
598
243k
}
599
600
7.54k
bool FileScannerV2::_should_enable_file_meta_cache() const {
601
7.54k
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
602
7.54k
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
603
7.54k
}
604
605
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
606
61.9k
        const TFileRangeDesc& range) const {
607
61.9k
    if (!_need_global_rowid_column) {
608
54.3k
        return std::nullopt;
609
54.3k
    }
610
7.54k
    auto& id_file_map = _state->get_id_file_map();
611
7.54k
    DORIS_CHECK(id_file_map != nullptr);
612
7.54k
    const auto file_id = id_file_map->get_file_mapping_id(
613
7.54k
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
614
7.54k
                                          range, _should_enable_file_meta_cache()));
615
7.54k
    return format::GlobalRowIdContext {
616
7.54k
            .version = IdManager::ID_VERSION,
617
7.54k
            .backend_id = BackendOptions::get_backend_id(),
618
7.54k
            .file_id = file_id,
619
7.54k
    };
620
61.9k
}
621
622
Status FileScannerV2::_generate_partition_values(
623
61.9k
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
624
61.9k
    DORIS_CHECK(partition_values != nullptr);
625
61.9k
    partition_values->clear();
626
61.9k
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
627
46.2k
        return Status::OK();
628
46.2k
    }
629
15.7k
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
630
42.7k
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
631
27.0k
        const auto& key = range.columns_from_path_keys[idx];
632
27.0k
        const auto it = _partition_slot_descs.find(key);
633
27.0k
        if (it == _partition_slot_descs.end()) {
634
13.8k
            continue;
635
13.8k
        }
636
13.1k
        const auto& value = range.columns_from_path[idx];
637
13.1k
        const bool is_null = range.__isset.columns_from_path_is_null &&
638
13.1k
                             idx < range.columns_from_path_is_null.size() &&
639
13.1k
                             range.columns_from_path_is_null[idx];
640
13.1k
        Field field;
641
13.1k
        DORIS_CHECK(it->second.slot_desc != nullptr);
642
13.1k
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
643
13.1k
        partition_values->emplace(it->second.canonical_name, std::move(field));
644
13.1k
    }
645
15.7k
    return Status::OK();
646
15.7k
}
647
648
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
649
                                             const std::string& value, bool is_null,
650
13.1k
                                             Field* field) const {
651
13.1k
    DORIS_CHECK(slot_desc != nullptr);
652
13.1k
    DORIS_CHECK(field != nullptr);
653
13.1k
    if (is_null) {
654
866
        *field = Field::create_field<TYPE_NULL>(Null());
655
866
        return Status::OK();
656
866
    }
657
12.2k
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
658
12.2k
    auto column = data_type->create_column();
659
12.2k
    auto serde = data_type->get_serde();
660
12.2k
    DataTypeSerDe::FormatOptions options;
661
12.2k
    options.converted_from_string = true;
662
12.2k
    StringRef ref(value.data(), value.size());
663
12.2k
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
664
12.2k
    DORIS_CHECK(column->size() == 1);
665
12.2k
    *field = (*column)[0];
666
12.2k
    return Status::OK();
667
12.2k
}
668
669
40.5k
Status FileScannerV2::_init_expr_ctxes() {
670
40.5k
    _slot_id_to_desc.clear();
671
40.5k
    _slot_id_to_global_index.clear();
672
40.5k
    _partition_slot_descs.clear();
673
40.5k
    _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.5k
    DORIS_CHECK(_table_reader != nullptr);
678
40.5k
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
679
40.5k
    return Status::OK();
680
40.5k
}
681
682
40.5k
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
683
40.5k
    _projected_columns.clear();
684
40.5k
    _projected_columns.reserve(_params->required_slots.size());
685
40.5k
    _need_global_rowid_column = false;
686
40.5k
    format::ProjectedColumnBuildContext build_context {
687
40.5k
            .scan_params = _params,
688
40.5k
            .range = &_current_range,
689
40.5k
            .runtime_state = _state,
690
40.5k
    };
691
692
279k
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
693
238k
        const auto& slot_info = _params->required_slots[slot_idx];
694
238k
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
695
238k
        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
238k
        auto column = _build_table_column(it->second);
700
238k
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
701
4.26k
            _need_global_rowid_column = true;
702
4.26k
        }
703
238k
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
704
238k
        build_context.schema_column.reset();
705
238k
        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
238k
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
710
238k
                &column, it->second,
711
238k
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr));
712
238k
        if (is_partition_slot(slot_info, column.name)) {
713
12.2k
            column.is_partition_key = true;
714
12.2k
            _partition_slot_descs.emplace(
715
12.2k
                    column.name,
716
12.2k
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
717
12.2k
            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
226k
        } else if (is_data_file_slot(slot_info, column.name)) {
723
221k
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
724
221k
        }
725
238k
        const auto global_index = format::GlobalIndex(slot_idx);
726
238k
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
727
238k
        _projected_columns.push_back(std::move(column));
728
238k
    }
729
40.5k
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
730
40.5k
    return Status::OK();
731
40.5k
}
732
733
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
734
238k
                                          VExprContextSPtr* ctx) const {
735
238k
    DORIS_CHECK(ctx != nullptr);
736
238k
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
737
233k
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
738
233k
    }
739
740
5.28k
    if (_params->__isset.default_value_of_src_slot) {
741
5.27k
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
742
5.27k
        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.27k
    }
746
5.28k
    return Status::OK();
747
5.28k
}
748
749
238k
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
750
238k
    DORIS_CHECK(slot_desc != nullptr);
751
238k
    format::ColumnDefinition column;
752
    // TODO(gabriel): why always BY_NAME here?
753
238k
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
754
238k
    column.name = slot_desc->col_name();
755
238k
    column.type = slot_desc->get_data_type_ptr();
756
238k
    return column;
757
238k
}
758
759
162k
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
760
162k
    DORIS_CHECK(conjuncts != nullptr);
761
162k
    conjuncts->clear();
762
162k
    conjuncts->reserve(_conjuncts.size());
763
162k
    for (const auto& conjunct : _conjuncts) {
764
107k
        VExprSPtr root;
765
107k
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
766
107k
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
767
107k
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
768
107k
    }
769
162k
    return Status::OK();
770
162k
}
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
102k
                                      format::FileFormat* file_format) {
778
102k
    DORIS_CHECK(file_format != nullptr);
779
102k
    switch (format_type) {
780
54.3k
    case TFileFormatType::FORMAT_PARQUET:
781
54.3k
        *file_format = format::FileFormat::PARQUET;
782
54.3k
        return Status::OK();
783
38.3k
    case TFileFormatType::FORMAT_ORC:
784
38.3k
        *file_format = format::FileFormat::ORC;
785
38.3k
        return Status::OK();
786
1
    case TFileFormatType::FORMAT_JNI:
787
1
        *file_format = format::FileFormat::JNI;
788
1
        return Status::OK();
789
1.40k
    case TFileFormatType::FORMAT_CSV_PLAIN:
790
1.40k
    case TFileFormatType::FORMAT_CSV_GZ:
791
1.40k
    case TFileFormatType::FORMAT_CSV_BZ2:
792
1.40k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
793
1.40k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
794
1.40k
    case TFileFormatType::FORMAT_CSV_LZOP:
795
1.40k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
796
1.41k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
797
1.41k
    case TFileFormatType::FORMAT_PROTO:
798
1.41k
        *file_format = format::FileFormat::CSV;
799
1.41k
        return Status::OK();
800
7.01k
    case TFileFormatType::FORMAT_TEXT:
801
7.01k
        *file_format = format::FileFormat::TEXT;
802
7.01k
        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
3
    case TFileFormatType::FORMAT_NATIVE:
807
3
        *file_format = format::FileFormat::NATIVE;
808
3
        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
102k
    }
816
102k
}
817
818
75.4k
Status FileScannerV2::_init_io_ctx() {
819
75.4k
    _io_ctx = create_file_scan_io_context(_state);
820
75.4k
    return Status::OK();
821
75.4k
}
822
823
61.9k
void FileScannerV2::_reset_adaptive_batch_size_state() {
824
61.9k
    _block_size_predictor.reset();
825
61.9k
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
826
61.9k
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
827
61.9k
}
828
829
61.9k
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
830
61.9k
    _reset_adaptive_batch_size_state();
831
61.9k
    if (!_should_enable_adaptive_batch_size(format_type)) {
832
99
        return;
833
99
    }
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
61.8k
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
839
61.8k
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
840
61.8k
            _state->batch_size());
841
61.8k
}
842
843
61.9k
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
844
61.9k
    if (!config::enable_adaptive_batch_size) {
845
0
        return false;
846
0
    }
847
61.9k
    switch (format_type) {
848
31.9k
    case TFileFormatType::FORMAT_PARQUET:
849
55.8k
    case TFileFormatType::FORMAT_ORC:
850
56.5k
    case TFileFormatType::FORMAT_CSV_PLAIN:
851
56.5k
    case TFileFormatType::FORMAT_CSV_GZ:
852
56.5k
    case TFileFormatType::FORMAT_CSV_BZ2:
853
56.5k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
854
56.5k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
855
56.5k
    case TFileFormatType::FORMAT_CSV_LZOP:
856
56.5k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
857
56.5k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
858
56.5k
    case TFileFormatType::FORMAT_PROTO:
859
61.2k
    case TFileFormatType::FORMAT_TEXT:
860
61.8k
    case TFileFormatType::FORMAT_JSON:
861
61.8k
    case TFileFormatType::FORMAT_JNI:
862
61.8k
        return true;
863
99
    default:
864
99
        return false;
865
61.9k
    }
866
61.9k
}
867
868
301k
bool FileScannerV2::_should_run_adaptive_batch_size() const {
869
301k
    DORIS_CHECK(_table_reader != nullptr);
870
301k
    return _should_run_adaptive_batch_size(_block_size_predictor != nullptr,
871
301k
                                           _table_reader->current_split_uses_metadata_count());
872
301k
}
873
874
bool FileScannerV2::_should_run_adaptive_batch_size(bool predictor_initialized,
875
301k
                                                    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
301k
    return predictor_initialized && !current_split_uses_metadata_count;
880
301k
}
881
882
241k
size_t FileScannerV2::_predict_reader_batch_rows() {
883
241k
    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
241k
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
887
241k
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
888
241k
    return predicted_rows;
889
241k
}
890
891
120k
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
892
120k
    if (!_should_run_adaptive_batch_size()) {
893
1.47k
        return;
894
1.47k
    }
895
118k
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(block.bytes()));
896
118k
    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
118k
    if (!_block_size_predictor->has_history()) {
903
47.3k
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
904
47.3k
    }
905
118k
    _block_size_predictor->update(block);
906
118k
}
907
908
75.7k
Status FileScannerV2::close(RuntimeState* state) {
909
75.7k
    if (!_try_close()) {
910
1
        return Status::OK();
911
1
    }
912
75.7k
    if (_table_reader != nullptr) {
913
40.5k
        const auto close_status = _table_reader->close();
914
40.5k
        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.5k
        _report_condition_cache_profile();
921
40.5k
        _table_reader.reset();
922
40.5k
    }
923
75.6k
    return Scanner::close(state);
924
75.7k
}
925
926
75.6k
void FileScannerV2::try_stop() {
927
75.6k
    Scanner::try_stop();
928
75.6k
    if (_io_ctx) {
929
75.6k
        _io_ctx->should_stop = true;
930
75.6k
    }
931
75.6k
}
932
933
127k
void FileScannerV2::update_realtime_counters() {
934
127k
    if (_file_reader_stats == nullptr) {
935
0
        return;
936
0
    }
937
127k
    DORIS_CHECK(_file_cache_statistics != nullptr);
938
127k
    const int64_t bytes_read = cast_set<int64_t>(_file_reader_stats->read_bytes);
939
127k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
940
127k
    const auto file_type =
941
127k
            _current_range.__isset.file_type
942
127k
                    ? _current_range.file_type
943
127k
                    : (_params != nullptr && _params->__isset.file_type ? _params->file_type
944
36.0k
                                                                        : TFileType::FILE_LOCAL);
945
127k
    const auto deltas = _collect_realtime_counter_deltas(
946
127k
            *_file_reader_stats, *_file_cache_statistics, _uncached_reader_bytes_storage(file_type),
947
127k
            &_last_read_bytes, &_last_read_rows, &_last_bytes_read_from_local,
948
127k
            &_last_bytes_read_from_remote);
949
950
127k
    COUNTER_UPDATE(local_state->_scan_bytes, deltas.scan_bytes);
951
127k
    COUNTER_UPDATE(local_state->_scan_rows, deltas.scan_rows);
952
953
127k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(deltas.scan_rows);
954
127k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(deltas.scan_bytes);
955
127k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
956
127k
            deltas.scan_bytes_from_local_storage);
957
127k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_remote_storage(
958
127k
            deltas.scan_bytes_from_remote_storage);
959
960
127k
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
961
127k
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
962
127k
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
963
964
127k
    DorisMetrics::instance()->query_scan_bytes->increment(deltas.scan_bytes);
965
127k
    DorisMetrics::instance()->query_scan_rows->increment(deltas.scan_rows);
966
127k
    DorisMetrics::instance()->query_scan_bytes_from_local->increment(
967
127k
            deltas.scan_bytes_from_local_storage);
968
127k
    DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
969
127k
            deltas.scan_bytes_from_remote_storage);
970
127k
}
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
127k
        int64_t* last_bytes_read_from_remote) {
978
127k
    DORIS_CHECK(last_read_bytes != nullptr);
979
127k
    DORIS_CHECK(last_read_rows != nullptr);
980
127k
    DORIS_CHECK(last_bytes_read_from_local != nullptr);
981
127k
    DORIS_CHECK(last_bytes_read_from_remote != nullptr);
982
983
127k
    const int64_t read_bytes = cast_set<int64_t>(file_reader_stats.read_bytes);
984
127k
    const int64_t read_rows = cast_set<int64_t>(file_reader_stats.read_rows);
985
127k
    const int64_t bytes_read_from_local = file_cache_statistics.bytes_read_from_local;
986
127k
    const int64_t bytes_read_from_remote = file_cache_statistics.bytes_read_from_remote;
987
127k
    DORIS_CHECK(read_bytes >= *last_read_bytes);
988
127k
    DORIS_CHECK(read_rows >= *last_read_rows);
989
127k
    DORIS_CHECK(bytes_read_from_local >= *last_bytes_read_from_local);
990
127k
    DORIS_CHECK(bytes_read_from_remote >= *last_bytes_read_from_remote);
991
992
127k
    RealtimeCounterDeltas deltas;
993
127k
    deltas.scan_rows = read_rows - *last_read_rows;
994
127k
    deltas.scan_bytes = read_bytes - *last_read_bytes;
995
    // Peer cache is a known cache source, but it is not remote object storage.
996
127k
    const bool has_cache_source_stats = file_cache_statistics.num_local_io_total != 0 ||
997
127k
                                        file_cache_statistics.num_remote_io_total != 0 ||
998
127k
                                        file_cache_statistics.num_peer_io_total != 0 ||
999
127k
                                        bytes_read_from_local != 0 || bytes_read_from_remote != 0 ||
1000
127k
                                        file_cache_statistics.bytes_read_from_peer != 0;
1001
127k
    if (!has_cache_source_stats) {
1002
114k
        switch (uncached_reader_bytes_storage) {
1003
851
        case UncachedReaderBytesStorage::LOCAL:
1004
851
            deltas.scan_bytes_from_local_storage = deltas.scan_bytes;
1005
851
            break;
1006
113k
        case UncachedReaderBytesStorage::REMOTE:
1007
113k
            deltas.scan_bytes_from_remote_storage = deltas.scan_bytes;
1008
113k
            break;
1009
209
        case UncachedReaderBytesStorage::NONE:
1010
209
            break;
1011
114k
        }
1012
114k
    } else {
1013
13.4k
        deltas.scan_bytes_from_local_storage = bytes_read_from_local - *last_bytes_read_from_local;
1014
13.4k
        deltas.scan_bytes_from_remote_storage =
1015
13.4k
                bytes_read_from_remote - *last_bytes_read_from_remote;
1016
13.4k
    }
1017
1018
127k
    *last_read_bytes = read_bytes;
1019
127k
    *last_read_rows = read_rows;
1020
127k
    *last_bytes_read_from_local = bytes_read_from_local;
1021
127k
    *last_bytes_read_from_remote = bytes_read_from_remote;
1022
127k
    return deltas;
1023
127k
}
1024
1025
FileScannerV2::UncachedReaderBytesStorage FileScannerV2::_uncached_reader_bytes_storage(
1026
127k
        TFileType::type file_type) {
1027
127k
    switch (file_type) {
1028
850
    case TFileType::FILE_LOCAL:
1029
850
        return UncachedReaderBytesStorage::LOCAL;
1030
209
    case TFileType::FILE_STREAM:
1031
209
        return UncachedReaderBytesStorage::NONE;
1032
0
    case TFileType::FILE_BROKER:
1033
52.2k
    case TFileType::FILE_S3:
1034
126k
    case TFileType::FILE_HDFS:
1035
126k
    case TFileType::FILE_NET:
1036
126k
    case TFileType::FILE_HTTP:
1037
126k
        return UncachedReaderBytesStorage::REMOTE;
1038
127k
    }
1039
0
    DORIS_CHECK(false) << "unknown file type: " << file_type;
1040
0
    return UncachedReaderBytesStorage::NONE;
1041
127k
}
1042
1043
75.5k
void FileScannerV2::_collect_profile_before_close() {
1044
75.5k
    _report_file_reader_predicate_filtered_rows();
1045
75.5k
    Scanner::_collect_profile_before_close();
1046
75.5k
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1047
75.5k
        _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
75.5k
    if (_file_reader_stats != nullptr) {
1053
75.5k
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
1054
75.5k
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
1055
75.5k
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
1056
75.5k
    }
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
75.5k
    _report_condition_cache_profile();
1060
75.5k
}
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
75.5k
bool FileScannerV2::_should_update_load_counters() const {
1069
75.5k
    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
75.5k
    return (_params != nullptr && _params->__isset.file_type &&
1078
75.5k
            _params->file_type == TFileType::FILE_STREAM) ||
1079
75.5k
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
1080
75.5k
}
1081
1082
75.5k
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
75.5k
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
1085
75.5k
    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.78k
        _counter.num_rows_unselected += filtered_delta;
1090
2.78k
        _reported_predicate_filtered_rows = filtered_rows;
1091
2.78k
    }
1092
75.5k
}
1093
1094
116k
void FileScannerV2::_report_condition_cache_profile() {
1095
116k
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
1096
116k
    const int64_t hit_count =
1097
116k
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
1098
116k
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
1099
116k
    if (hit_delta > 0) {
1100
2.55k
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
1101
2.55k
        _reported_condition_cache_hit_count = hit_count;
1102
2.55k
    }
1103
116k
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
1104
116k
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
1105
116k
    if (filtered_delta > 0) {
1106
450
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
1107
450
        _reported_condition_cache_filtered_rows = filtered_rows;
1108
450
    }
1109
116k
}
1110
1111
} // namespace doris