Coverage Report

Created: 2026-07-07 01:02

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/status.h"
34
#include "core/assert_cast.h"
35
#include "core/block/column_with_type_and_name.h"
36
#include "core/column/column.h"
37
#include "core/data_type/data_type.h"
38
#include "core/data_type/data_type_nullable.h"
39
#include "core/data_type_serde/data_type_serde.h"
40
#include "core/string_ref.h"
41
#include "exec/common/util.hpp"
42
#include "exec/operator/scan_operator.h"
43
#include "exec/scan/access_path_parser.h"
44
#include "exprs/runtime_filter_expr.h"
45
#include "exprs/vexpr.h"
46
#include "exprs/vexpr_context.h"
47
#include "exprs/vslot_ref.h"
48
#include "format/format_common.h"
49
#include "format_v2/column_mapper.h"
50
#include "format_v2/jni/iceberg_sys_table_reader.h"
51
#include "format_v2/jni/jdbc_reader.h"
52
#include "format_v2/jni/max_compute_jni_reader.h"
53
#include "format_v2/jni/trino_connector_jni_reader.h"
54
#include "format_v2/table/hive_reader.h"
55
#include "format_v2/table/hudi_reader.h"
56
#include "format_v2/table/iceberg_reader.h"
57
#include "format_v2/table/paimon_reader.h"
58
#include "format_v2/table/remote_doris_reader.h"
59
#include "format_v2/table_reader.h"
60
#include "io/fs/file_meta_cache.h"
61
#include "io/io_common.h"
62
#include "runtime/descriptors.h"
63
#include "runtime/exec_env.h"
64
#include "runtime/runtime_state.h"
65
#include "service/backend_options.h"
66
#include "storage/id_manager.h"
67
68
namespace doris {
69
namespace {
70
71
39
std::string table_format_name(const TFileRangeDesc& range) {
72
39
    return range.__isset.table_format_params ? range.table_format_params.table_format_type
73
39
                                             : "NotSet";
74
39
}
75
76
TFileFormatType::type get_range_format_type(const TFileScanRangeParams& params,
77
41
                                            const TFileRangeDesc& range) {
78
41
    return range.__isset.format_type ? range.format_type : params.format_type;
79
41
}
80
81
33
bool is_supported_table_format(const TFileRangeDesc& range) {
82
33
    const auto table_format = table_format_name(range);
83
33
    if (table_format == "hudi" && range.__isset.table_format_params &&
84
33
        range.table_format_params.__isset.hudi_params &&
85
33
        range.table_format_params.hudi_params.__isset.delta_logs &&
86
33
        !range.table_format_params.hudi_params.delta_logs.empty()) {
87
        // Hudi MOR splits need log-file merge semantics and must stay on the existing JNI path.
88
        // FileScannerV2 currently supports native Parquet data files only.
89
1
        return false;
90
1
    }
91
32
    return table_format == "NotSet" || table_format == "tvf" || table_format == "hive" ||
92
32
           table_format == "iceberg" || table_format == "paimon" || table_format == "hudi";
93
33
}
94
95
3
bool is_supported_arrow_table_format(const TFileRangeDesc& range) {
96
3
    return table_format_name(range) == "remote_doris";
97
3
}
98
99
3
bool is_supported_jni_table_format(const TFileRangeDesc& range) {
100
3
    const auto table_format = table_format_name(range);
101
3
    if (table_format == "paimon") {
102
0
        return range.__isset.table_format_params &&
103
0
               range.table_format_params.__isset.paimon_params &&
104
0
               range.table_format_params.paimon_params.__isset.reader_type &&
105
0
               range.table_format_params.paimon_params.reader_type == TPaimonReaderType::PAIMON_JNI;
106
0
    }
107
3
    return table_format == "jdbc" || table_format == "iceberg" || table_format == "hudi" ||
108
3
           table_format == "max_compute" || table_format == "trino_connector";
109
3
}
110
111
17
bool is_csv_format(TFileFormatType::type format_type) {
112
17
    switch (format_type) {
113
2
    case TFileFormatType::FORMAT_CSV_PLAIN:
114
3
    case TFileFormatType::FORMAT_CSV_GZ:
115
4
    case TFileFormatType::FORMAT_CSV_BZ2:
116
5
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
117
6
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
118
7
    case TFileFormatType::FORMAT_CSV_LZOP:
119
8
    case TFileFormatType::FORMAT_CSV_DEFLATE:
120
9
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
121
10
    case TFileFormatType::FORMAT_PROTO:
122
10
        return true;
123
7
    default:
124
7
        return false;
125
17
    }
126
17
}
127
128
7
bool is_text_format(TFileFormatType::type format_type) {
129
7
    return format_type == TFileFormatType::FORMAT_TEXT;
130
7
}
131
132
5
bool is_json_format(TFileFormatType::type format_type) {
133
5
    return format_type == TFileFormatType::FORMAT_JSON;
134
5
}
135
136
3
bool is_native_format(TFileFormatType::type format_type) {
137
3
    return format_type == TFileFormatType::FORMAT_NATIVE;
138
3
}
139
140
6
bool is_partition_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
141
6
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
142
6
        column_name == BeConsts::ICEBERG_ROWID_COL) {
143
2
        return false;
144
2
    }
145
4
    return slot_info.__isset.category ? slot_info.category == TColumnCategory::PARTITION_KEY
146
4
                                      : !slot_info.is_file_slot;
147
6
}
148
149
8
bool is_data_file_slot(const TFileScanSlotInfo& slot_info, const std::string& column_name) {
150
8
    if (column_name.starts_with(BeConsts::GLOBAL_ROWID_COL) ||
151
8
        column_name == BeConsts::ICEBERG_ROWID_COL) {
152
2
        return false;
153
2
    }
154
    // CSV and other non-self-describing formats need FE slot descriptors for only the columns that
155
    // are physically read from the file. Partition/default/virtual columns stay in TableReader's
156
    // mapping layer and are materialized after the file-local block is read. New FE provides an
157
    // explicit category; old FE falls back to `is_file_slot`.
158
6
    if (slot_info.__isset.category) {
159
4
        return slot_info.category == TColumnCategory::REGULAR ||
160
4
               slot_info.category == TColumnCategory::GENERATED;
161
4
    }
162
2
    return slot_info.is_file_slot;
163
6
}
164
165
Status rewrite_slot_refs_to_global_index(
166
        VExprSPtr* expr,
167
7
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
168
7
    DORIS_CHECK(expr != nullptr);
169
7
    if (*expr == nullptr) {
170
0
        return Status::OK();
171
0
    }
172
7
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr->get());
173
7
        runtime_filter != nullptr) {
174
1
        auto impl = runtime_filter->get_impl();
175
1
        DORIS_CHECK(impl != nullptr);
176
1
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&impl, slot_id_to_global_index));
177
1
        runtime_filter->set_impl(std::move(impl));
178
1
        return Status::OK();
179
1
    }
180
6
    if ((*expr)->is_slot_ref()) {
181
4
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr->get());
182
4
        const auto global_index_it = slot_id_to_global_index.find(slot_ref->slot_id());
183
4
        if (global_index_it == slot_id_to_global_index.end()) {
184
1
            DORIS_CHECK(slot_ref->slot_id() >= 0);
185
1
            const auto global_index = format::GlobalIndex(cast_set<size_t>(slot_ref->slot_id()));
186
1
            *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
187
1
                                            cast_set<int>(global_index.value()), -1,
188
1
                                            slot_ref->data_type(), slot_ref->column_name());
189
1
            RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
190
1
            return Status::OK();
191
1
        }
192
3
        const auto global_index = global_index_it->second;
193
3
        *expr = VSlotRef::create_shared(cast_set<int>(global_index.value()),
194
3
                                        cast_set<int>(global_index.value()), -1,
195
3
                                        slot_ref->data_type(), slot_ref->column_name());
196
3
        RETURN_IF_ERROR(expr->get()->prepare(nullptr, RowDescriptor(), nullptr));
197
3
        return Status::OK();
198
3
    }
199
2
    auto children = (*expr)->children();
200
2
    for (auto& child : children) {
201
2
        if (child == nullptr) {
202
0
            continue;
203
0
        }
204
2
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&child, slot_id_to_global_index));
205
2
    }
206
2
    (*expr)->set_children(std::move(children));
207
2
    return Status::OK();
208
2
}
209
210
} // namespace
211
212
#ifdef BE_TEST
213
Status FileScannerV2::TEST_to_file_format(TFileFormatType::type format_type,
214
16
                                          format::FileFormat* file_format) {
215
16
    return _to_file_format(format_type, file_format);
216
16
}
217
218
bool FileScannerV2::TEST_is_partition_slot(const TFileScanSlotInfo& slot_info,
219
6
                                           const std::string& column_name) {
220
6
    return is_partition_slot(slot_info, column_name);
221
6
}
222
223
bool FileScannerV2::TEST_is_data_file_slot(const TFileScanSlotInfo& slot_info,
224
8
                                           const std::string& column_name) {
225
8
    return is_data_file_slot(slot_info, column_name);
226
8
}
227
228
Status FileScannerV2::TEST_rewrite_slot_refs_to_global_index(
229
        VExprSPtr* expr,
230
4
        const std::unordered_map<int32_t, format::GlobalIndex>& slot_id_to_global_index) {
231
4
    return rewrite_slot_refs_to_global_index(expr, slot_id_to_global_index);
232
4
}
233
#endif
234
235
41
bool FileScannerV2::is_supported(const TFileScanRangeParams& params, const TFileRangeDesc& range) {
236
41
    const auto format_type = get_range_format_type(params, range);
237
41
    if (format_type == TFileFormatType::FORMAT_PARQUET ||
238
41
        format_type == TFileFormatType::FORMAT_ORC) {
239
18
        return is_supported_table_format(range);
240
23
    } else if (format_type == TFileFormatType::FORMAT_ARROW) {
241
3
        return is_supported_arrow_table_format(range);
242
20
    } else if (format_type == TFileFormatType::FORMAT_JNI) {
243
3
        return is_supported_jni_table_format(range);
244
17
    } else if (is_csv_format(format_type) || is_text_format(format_type) ||
245
17
               is_json_format(format_type) || is_native_format(format_type)) {
246
15
        return is_supported_table_format(range);
247
15
    } else {
248
2
        LOG(WARNING) << "Unsupported file format type " << format_type << " for file scanner v2";
249
2
        return false;
250
2
    }
251
41
}
252
253
FileScannerV2::FileScannerV2(RuntimeState* state, FileScanLocalState* local_state, int64_t limit,
254
                             std::shared_ptr<SplitSourceConnector> split_source,
255
                             RuntimeProfile* profile, ShardedKVCache* kv_cache,
256
                             const std::unordered_map<std::string, int>* colname_to_slot_id)
257
0
        : Scanner(state, local_state, limit, profile),
258
0
          _split_source(std::move(split_source)),
259
0
          _kv_cache(kv_cache) {
260
0
    (void)colname_to_slot_id;
261
0
    if (state->get_query_ctx() != nullptr &&
262
0
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
263
0
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
264
0
    } else {
265
0
        _params = _split_source->get_params();
266
0
    }
267
0
}
268
269
0
Status FileScannerV2::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
270
0
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
271
0
    _get_block_timer =
272
0
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerV2GetBlockTime", 1);
273
0
    _file_counter =
274
0
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "FileNumber", TUnit::UNIT, 1);
275
0
    _file_read_bytes_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
276
0
                                                      "FileReadBytes", TUnit::BYTES, 1);
277
0
    _file_read_calls_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
278
0
                                                      "FileReadCalls", TUnit::UNIT, 1);
279
0
    _file_read_time_counter =
280
0
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileReadTime", 1);
281
0
    _adaptive_batch_predicted_rows_counter = ADD_COUNTER_WITH_LEVEL(
282
0
            _local_state->scanner_profile(), "AdaptiveBatchPredictedRows", TUnit::UNIT, 1);
283
0
    _adaptive_batch_actual_bytes_counter = ADD_COUNTER_WITH_LEVEL(
284
0
            _local_state->scanner_profile(), "AdaptiveBatchActualBytes", TUnit::BYTES, 1);
285
0
    _adaptive_batch_probe_count_counter = ADD_COUNTER_WITH_LEVEL(
286
0
            _local_state->scanner_profile(), "AdaptiveBatchProbeCount", TUnit::UNIT, 1);
287
0
    _file_cache_statistics = std::make_unique<io::FileCacheStatistics>();
288
0
    _file_reader_stats = std::make_unique<io::FileReaderStats>();
289
0
    RETURN_IF_ERROR(_init_io_ctx());
290
0
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
291
0
    _io_ctx->file_reader_stats = _file_reader_stats.get();
292
0
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
293
0
    return Status::OK();
294
0
}
295
296
0
Status FileScannerV2::_open_impl(RuntimeState* state) {
297
0
    RETURN_IF_CANCELLED(state);
298
0
    RETURN_IF_ERROR(Scanner::_open_impl(state));
299
0
    RETURN_IF_ERROR(_split_source->get_next(&_first_scan_range, &_current_range));
300
0
    if (_first_scan_range) {
301
0
        RETURN_IF_ERROR(_create_table_reader_for_format(_current_range, &_table_reader));
302
0
        DORIS_CHECK(_table_reader != nullptr);
303
0
        RETURN_IF_ERROR(_init_expr_ctxes());
304
0
        RETURN_IF_ERROR(_init_table_reader(_current_range));
305
0
    }
306
0
    return Status::OK();
307
0
}
308
309
0
Status FileScannerV2::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
310
0
    while (true) {
311
0
        RETURN_IF_CANCELLED(state);
312
0
        if (!_has_prepared_split) {
313
0
            RETURN_IF_ERROR(_prepare_next_split(eof));
314
0
            if (*eof) {
315
0
                return Status::OK();
316
0
            }
317
0
        }
318
319
0
        {
320
0
            SCOPED_TIMER(_get_block_timer);
321
0
            if (_should_run_adaptive_batch_size()) {
322
0
                _table_reader->set_batch_size(_predict_reader_batch_rows());
323
0
            }
324
0
            RETURN_IF_ERROR(_table_reader->get_block(block, eof));
325
0
        }
326
0
        if (*eof) {
327
0
            _state->update_num_finished_scan_range(1);
328
0
            _has_prepared_split = false;
329
0
            *eof = false;
330
0
            continue;
331
0
        }
332
0
        _update_adaptive_batch_size(*block);
333
0
        return Status::OK();
334
0
    }
335
0
}
336
337
0
Status FileScannerV2::_prepare_next_split(bool* eos) {
338
0
    bool has_next = _first_scan_range;
339
0
    if (!_first_scan_range) {
340
0
        RETURN_IF_ERROR(_split_source->get_next(&has_next, &_current_range));
341
0
    }
342
0
    _first_scan_range = false;
343
0
    if (!has_next || _should_stop) {
344
0
        *eos = true;
345
0
        return Status::OK();
346
0
    }
347
0
    DORIS_CHECK(_table_reader != nullptr);
348
0
    _current_range_path = _current_range.path;
349
0
    _init_adaptive_batch_size_state(get_range_format_type(*_params, _current_range));
350
0
    RETURN_IF_ERROR(_prepare_table_reader_split(_current_range));
351
0
    COUNTER_UPDATE(_file_counter, 1);
352
0
    _has_prepared_split = true;
353
0
    *eos = false;
354
0
    return Status::OK();
355
0
}
356
357
0
Status FileScannerV2::_init_table_reader(const TFileRangeDesc& range) {
358
0
    const auto format_type = get_range_format_type(*_params, range);
359
0
    format::FileFormat file_format;
360
0
    RETURN_IF_ERROR(_to_file_format(format_type, &file_format));
361
0
    DORIS_CHECK(_table_reader != nullptr);
362
363
0
    VExprContextSPtrs table_conjuncts;
364
0
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
365
0
    RETURN_IF_ERROR(_table_reader->init({
366
0
            .projected_columns = _projected_columns,
367
0
            .conjuncts = std::move(table_conjuncts),
368
0
            .format = file_format,
369
0
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
370
0
            .io_ctx = _io_ctx,
371
0
            .runtime_state = _state,
372
0
            .scanner_profile = _local_state->scanner_profile(),
373
0
            .file_slot_descs = &_file_slot_descs,
374
0
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
375
0
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
376
0
    }));
377
0
    return Status::OK();
378
0
}
379
380
Status FileScannerV2::_create_table_reader_for_format(
381
0
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
382
0
    DORIS_CHECK(reader != nullptr);
383
0
    const auto table_format = table_format_name(range);
384
0
    if (table_format == "NotSet" || table_format == "tvf") {
385
0
        *reader = std::make_unique<format::TableReader>();
386
0
    } else if (table_format == "hive") {
387
0
        *reader = format::hive::HiveReader::create_unique();
388
0
    } else if (table_format == "iceberg") {
389
0
        if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
390
0
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
391
0
        } else {
392
0
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
393
0
        }
394
0
    } else if (table_format == "paimon") {
395
0
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
396
0
    } else if (table_format == "hudi") {
397
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
398
0
    } else if (table_format == "jdbc") {
399
0
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
400
0
    } else if (table_format == "max_compute") {
401
0
        const auto* mc_desc =
402
0
                static_cast<const MaxComputeTableDescriptor*>(_output_tuple_desc->table_desc());
403
0
        RETURN_IF_ERROR(mc_desc->init_status());
404
0
        *reader = std::make_unique<format::max_compute::MaxComputeJniReader>(mc_desc);
405
0
    } else if (table_format == "trino_connector") {
406
0
        *reader = std::make_unique<format::trino_connector::TrinoConnectorJniReader>();
407
0
    } else if (table_format == "remote_doris") {
408
0
        *reader = std::make_unique<format::remote_doris::RemoteDorisReader>();
409
0
    } else {
410
0
        return Status::NotSupported("FileScannerV2 does not support table format {}", table_format);
411
0
    }
412
0
    return Status::OK();
413
0
}
414
415
0
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range) {
416
0
    std::map<std::string, Field> partition_values;
417
0
    RETURN_IF_ERROR(_generate_partition_values(range, &partition_values));
418
0
    format::FileFormat current_split_format;
419
0
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
420
0
    RETURN_IF_ERROR(_table_reader->prepare_split({
421
0
            .partition_values = std::move(partition_values),
422
0
            .cache = _kv_cache,
423
0
            .current_range = range,
424
0
            .current_split_format = current_split_format,
425
0
            .global_rowid_context = _create_global_rowid_context(range),
426
0
    }));
427
0
    return Status::OK();
428
0
}
429
430
0
bool FileScannerV2::_should_enable_file_meta_cache() const {
431
0
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
432
0
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
433
0
}
434
435
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
436
0
        const TFileRangeDesc& range) const {
437
0
    if (!_need_global_rowid_column) {
438
0
        return std::nullopt;
439
0
    }
440
0
    auto& id_file_map = _state->get_id_file_map();
441
0
    DORIS_CHECK(id_file_map != nullptr);
442
0
    const auto file_id = id_file_map->get_file_mapping_id(
443
0
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
444
0
                                          range, _should_enable_file_meta_cache()));
445
0
    return format::GlobalRowIdContext {
446
0
            .version = IdManager::ID_VERSION,
447
0
            .backend_id = BackendOptions::get_backend_id(),
448
0
            .file_id = file_id,
449
0
    };
450
0
}
451
452
Status FileScannerV2::_generate_partition_values(
453
0
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
454
0
    DORIS_CHECK(partition_values != nullptr);
455
0
    partition_values->clear();
456
0
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
457
0
        return Status::OK();
458
0
    }
459
0
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
460
0
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
461
0
        const auto& key = range.columns_from_path_keys[idx];
462
0
        const auto it = _partition_slot_descs.find(key);
463
0
        if (it == _partition_slot_descs.end()) {
464
0
            continue;
465
0
        }
466
0
        const auto& value = range.columns_from_path[idx];
467
0
        const bool is_null = range.__isset.columns_from_path_is_null &&
468
0
                             idx < range.columns_from_path_is_null.size() &&
469
0
                             range.columns_from_path_is_null[idx];
470
0
        Field field;
471
0
        DORIS_CHECK(it->second.slot_desc != nullptr);
472
0
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
473
0
        partition_values->emplace(it->second.canonical_name, std::move(field));
474
0
    }
475
0
    return Status::OK();
476
0
}
477
478
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
479
                                             const std::string& value, bool is_null,
480
0
                                             Field* field) const {
481
0
    DORIS_CHECK(slot_desc != nullptr);
482
0
    DORIS_CHECK(field != nullptr);
483
0
    if (is_null) {
484
0
        *field = Field::create_field<TYPE_NULL>(Null());
485
0
        return Status::OK();
486
0
    }
487
0
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
488
0
    auto column = data_type->create_column();
489
0
    auto serde = data_type->get_serde();
490
0
    DataTypeSerDe::FormatOptions options;
491
0
    options.converted_from_string = true;
492
0
    StringRef ref(value.data(), value.size());
493
0
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
494
0
    DORIS_CHECK(column->size() == 1);
495
0
    *field = (*column)[0];
496
0
    return Status::OK();
497
0
}
498
499
0
Status FileScannerV2::_init_expr_ctxes() {
500
0
    _slot_id_to_desc.clear();
501
0
    _slot_id_to_global_index.clear();
502
0
    _partition_slot_descs.clear();
503
0
    _file_slot_descs.clear();
504
0
    for (const auto* slot_desc : _output_tuple_desc->slots()) {
505
0
        _slot_id_to_desc.emplace(slot_desc->id(), slot_desc);
506
0
    }
507
0
    DORIS_CHECK(_table_reader != nullptr);
508
0
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
509
0
    return Status::OK();
510
0
}
511
512
0
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
513
0
    _projected_columns.clear();
514
0
    _projected_columns.reserve(_params->required_slots.size());
515
0
    _need_global_rowid_column = false;
516
0
    format::ProjectedColumnBuildContext build_context {
517
0
            .scan_params = _params,
518
0
            .range = &_current_range,
519
0
            .runtime_state = _state,
520
0
    };
521
522
0
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
523
0
        const auto& slot_info = _params->required_slots[slot_idx];
524
0
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
525
0
        if (it == _slot_id_to_desc.end()) {
526
0
            return Status::InternalError("Unknown source slot descriptor, slot_id={}",
527
0
                                         slot_info.slot_id);
528
0
        }
529
0
        auto column = _build_table_column(it->second);
530
0
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
531
0
            _need_global_rowid_column = true;
532
0
        }
533
0
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
534
0
        build_context.schema_column.reset();
535
0
        RETURN_IF_ERROR(table_reader.annotate_projected_column(slot_info, &build_context, &column));
536
        // Build nested children from access paths generated by the slot's access-path
537
        // expressions. A projected column can therefore contain only a subset of the schema
538
        // column's nested children.
539
0
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
540
0
                &column, it->second,
541
0
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr));
542
0
        if (is_partition_slot(slot_info, column.name)) {
543
0
            column.is_partition_key = true;
544
0
            _partition_slot_descs.emplace(
545
0
                    column.name,
546
0
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
547
0
            for (const auto& alias : column.name_mapping) {
548
0
                _partition_slot_descs.emplace(
549
0
                        alias,
550
0
                        PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
551
0
            }
552
0
        } else if (is_data_file_slot(slot_info, column.name)) {
553
0
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
554
0
        }
555
0
        const auto global_index = format::GlobalIndex(slot_idx);
556
0
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
557
0
        _projected_columns.push_back(std::move(column));
558
0
    }
559
0
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
560
0
    return Status::OK();
561
0
}
562
563
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
564
0
                                          VExprContextSPtr* ctx) const {
565
0
    DORIS_CHECK(ctx != nullptr);
566
0
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
567
0
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
568
0
    }
569
570
0
    if (_params->__isset.default_value_of_src_slot) {
571
0
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
572
0
        if (it != _params->default_value_of_src_slot.end() && !it->second.nodes.empty()) {
573
0
            return VExpr::create_expr_tree(it->second, *ctx);
574
0
        }
575
0
    }
576
0
    return Status::OK();
577
0
}
578
579
0
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
580
0
    DORIS_CHECK(slot_desc != nullptr);
581
0
    format::ColumnDefinition column;
582
    // TODO(gabriel): why always BY_NAME here?
583
0
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
584
0
    column.name = slot_desc->col_name();
585
0
    column.type = slot_desc->get_data_type_ptr();
586
0
    return column;
587
0
}
588
589
0
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
590
0
    DORIS_CHECK(conjuncts != nullptr);
591
0
    conjuncts->clear();
592
0
    conjuncts->reserve(_conjuncts.size());
593
0
    for (const auto& conjunct : _conjuncts) {
594
0
        VExprSPtr root;
595
0
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
596
0
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
597
0
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
598
0
    }
599
0
    return Status::OK();
600
0
}
601
602
0
TFileFormatType::type FileScannerV2::_get_current_format_type() const {
603
0
    return get_range_format_type(*_params, _current_range);
604
0
}
605
606
Status FileScannerV2::_to_file_format(TFileFormatType::type format_type,
607
16
                                      format::FileFormat* file_format) {
608
16
    DORIS_CHECK(file_format != nullptr);
609
16
    switch (format_type) {
610
1
    case TFileFormatType::FORMAT_PARQUET:
611
1
        *file_format = format::FileFormat::PARQUET;
612
1
        return Status::OK();
613
1
    case TFileFormatType::FORMAT_ORC:
614
1
        *file_format = format::FileFormat::ORC;
615
1
        return Status::OK();
616
1
    case TFileFormatType::FORMAT_JNI:
617
1
        *file_format = format::FileFormat::JNI;
618
1
        return Status::OK();
619
1
    case TFileFormatType::FORMAT_CSV_PLAIN:
620
2
    case TFileFormatType::FORMAT_CSV_GZ:
621
3
    case TFileFormatType::FORMAT_CSV_BZ2:
622
4
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
623
5
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
624
6
    case TFileFormatType::FORMAT_CSV_LZOP:
625
7
    case TFileFormatType::FORMAT_CSV_DEFLATE:
626
8
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
627
9
    case TFileFormatType::FORMAT_PROTO:
628
9
        *file_format = format::FileFormat::CSV;
629
9
        return Status::OK();
630
1
    case TFileFormatType::FORMAT_TEXT:
631
1
        *file_format = format::FileFormat::TEXT;
632
1
        return Status::OK();
633
1
    case TFileFormatType::FORMAT_JSON:
634
1
        *file_format = format::FileFormat::JSON;
635
1
        return Status::OK();
636
1
    case TFileFormatType::FORMAT_NATIVE:
637
1
        *file_format = format::FileFormat::NATIVE;
638
1
        return Status::OK();
639
1
    case TFileFormatType::FORMAT_ARROW:
640
1
        *file_format = format::FileFormat::ARROW;
641
1
        return Status::OK();
642
0
    default:
643
0
        return Status::NotSupported("FileScannerV2 does not support file format {}",
644
0
                                    to_string(format_type));
645
16
    }
646
16
}
647
648
0
Status FileScannerV2::_init_io_ctx() {
649
0
    _io_ctx = std::make_shared<io::IOContext>();
650
0
    _io_ctx->query_id = &_state->query_id();
651
0
    return Status::OK();
652
0
}
653
654
0
void FileScannerV2::_reset_adaptive_batch_size_state() {
655
0
    _block_size_predictor.reset();
656
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
657
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
658
0
}
659
660
0
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
661
0
    _reset_adaptive_batch_size_state();
662
0
    if (!_should_enable_adaptive_batch_size(format_type)) {
663
0
        return;
664
0
    }
665
666
    // V2 native file readers do not have reliable row-width hints before the first batch. Start
667
    // every split with a small probe, then learn bytes-per-row from the materialized table block
668
    // and keep later batches close to RuntimeState::preferred_block_size_bytes().
669
0
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
670
0
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
671
0
            _state->batch_size());
672
0
}
673
674
0
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
675
0
    if (!config::enable_adaptive_batch_size) {
676
0
        return false;
677
0
    }
678
0
    switch (format_type) {
679
0
    case TFileFormatType::FORMAT_PARQUET:
680
0
    case TFileFormatType::FORMAT_ORC:
681
0
    case TFileFormatType::FORMAT_CSV_PLAIN:
682
0
    case TFileFormatType::FORMAT_CSV_GZ:
683
0
    case TFileFormatType::FORMAT_CSV_BZ2:
684
0
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
685
0
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
686
0
    case TFileFormatType::FORMAT_CSV_LZOP:
687
0
    case TFileFormatType::FORMAT_CSV_DEFLATE:
688
0
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
689
0
    case TFileFormatType::FORMAT_PROTO:
690
0
    case TFileFormatType::FORMAT_TEXT:
691
0
    case TFileFormatType::FORMAT_JSON:
692
0
    case TFileFormatType::FORMAT_JNI:
693
0
        return true;
694
0
    default:
695
0
        return false;
696
0
    }
697
0
}
698
699
0
bool FileScannerV2::_should_run_adaptive_batch_size() const {
700
    // COUNT pushdown emits synthetic rows from file metadata and does not materialize file columns,
701
    // so there is no useful row-width sample to learn from.
702
0
    return _block_size_predictor != nullptr &&
703
0
           _local_state->get_push_down_agg_type() != TPushAggOp::type::COUNT;
704
0
}
705
706
0
size_t FileScannerV2::_predict_reader_batch_rows() {
707
0
    DORIS_CHECK(_block_size_predictor != nullptr);
708
    // Before history exists this returns the probe row count; after update(), it returns roughly
709
    // preferred_block_size_bytes / EWMA(bytes_per_row), capped by RuntimeState::batch_size().
710
0
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
711
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
712
0
    return predicted_rows;
713
0
}
714
715
0
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
716
0
    if (!_should_run_adaptive_batch_size()) {
717
0
        return;
718
0
    }
719
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(block.bytes()));
720
0
    if (block.rows() == 0) {
721
0
        return;
722
0
    }
723
    // The sample is taken after TableReader has finalized file-local columns to table columns.
724
    // This matches the memory shape seen by upstream operators and catches very wide nested
725
    // columns, such as map/string payloads, after the first probe batch.
726
0
    if (!_block_size_predictor->has_history()) {
727
0
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
728
0
    }
729
0
    _block_size_predictor->update(block);
730
0
}
731
732
0
Status FileScannerV2::close(RuntimeState* state) {
733
0
    if (!_try_close()) {
734
0
        return Status::OK();
735
0
    }
736
0
    if (_table_reader != nullptr) {
737
0
        RETURN_IF_ERROR(_table_reader->close());
738
0
        _report_condition_cache_profile();
739
0
        _table_reader.reset();
740
0
    }
741
0
    return Scanner::close(state);
742
0
}
743
744
0
void FileScannerV2::try_stop() {
745
0
    Scanner::try_stop();
746
0
    if (_io_ctx) {
747
0
        _io_ctx->should_stop = true;
748
0
    }
749
0
}
750
751
0
void FileScannerV2::update_realtime_counters() {
752
0
    if (_file_reader_stats == nullptr) {
753
0
        return;
754
0
    }
755
0
    const int64_t bytes_read = _file_reader_stats->read_bytes;
756
0
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
757
0
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
758
0
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
759
0
}
760
761
0
void FileScannerV2::_collect_profile_before_close() {
762
0
    _report_file_reader_predicate_filtered_rows();
763
0
    Scanner::_collect_profile_before_close();
764
0
    if (_file_reader_stats != nullptr) {
765
0
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
766
0
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
767
0
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
768
0
    }
769
    // Query profiles can be collected before Scanner::close() runs. Publish condition-cache
770
    // counters here as well, using deltas so this method and close() cannot double count.
771
0
    _report_condition_cache_profile();
772
0
}
773
774
0
bool FileScannerV2::_should_update_load_counters() const {
775
0
    if (_is_load) {
776
0
        return true;
777
0
    }
778
    // TVF based loads (e.g. http_stream, group commit relay) plan the load source as a
779
    // tvf query scan without src tuple desc, so _is_load is false. But rows filtered by
780
    // the load's WHERE clause still need to be reported as unselected rows. FILE_STREAM
781
    // is only reachable from such load entries, never from normal queries, so use it to
782
    // identify these scanners.
783
0
    return (_params != nullptr && _params->__isset.file_type &&
784
0
            _params->file_type == TFileType::FILE_STREAM) ||
785
0
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
786
0
}
787
788
0
void FileScannerV2::_report_file_reader_predicate_filtered_rows() {
789
0
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->predicate_filtered_rows : 0;
790
0
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
791
0
    if (filtered_delta > 0) {
792
        // File readers can evaluate localized conjuncts before a block reaches Scanner. Count
793
        // those rows as scanner-level unselected rows so load statistics stay identical no matter
794
        // whether a predicate is pushed down or evaluated by Scanner::_filter_output_block().
795
0
        _counter.num_rows_unselected += filtered_delta;
796
0
        _reported_predicate_filtered_rows = filtered_rows;
797
0
    }
798
0
}
799
800
0
void FileScannerV2::_report_condition_cache_profile() {
801
0
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
802
0
    const int64_t hit_count =
803
0
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
804
0
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
805
0
    if (hit_delta > 0) {
806
0
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
807
0
        _reported_condition_cache_hit_count = hit_count;
808
0
    }
809
0
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
810
0
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
811
0
    if (filtered_delta > 0) {
812
0
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
813
0
        _reported_condition_cache_filtered_rows = filtered_rows;
814
0
    }
815
0
}
816
817
} // namespace doris