Coverage Report

Created: 2026-07-05 00:48

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
37
std::string table_format_name(const TFileRangeDesc& range) {
72
37
    return range.__isset.table_format_params ? range.table_format_params.table_format_type
73
37
                                             : "NotSet";
74
37
}
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
31
bool is_supported_table_format(const TFileRangeDesc& range) {
82
31
    const auto table_format = table_format_name(range);
83
31
    if (table_format == "hudi" && range.__isset.table_format_params &&
84
31
        range.table_format_params.__isset.hudi_params &&
85
31
        range.table_format_params.hudi_params.__isset.delta_logs &&
86
31
        !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
30
    return table_format == "NotSet" || table_format == "tvf" || table_format == "hive" ||
92
30
           table_format == "iceberg" || table_format == "paimon" || table_format == "hudi";
93
31
}
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
19
bool is_csv_format(TFileFormatType::type format_type) {
112
19
    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
9
    default:
124
9
        return false;
125
19
    }
126
19
}
127
128
9
bool is_text_format(TFileFormatType::type format_type) {
129
9
    return format_type == TFileFormatType::FORMAT_TEXT;
130
9
}
131
132
7
bool is_json_format(TFileFormatType::type format_type) {
133
7
    return format_type == TFileFormatType::FORMAT_JSON;
134
7
}
135
136
5
bool is_native_format(TFileFormatType::type format_type) {
137
5
    return format_type == TFileFormatType::FORMAT_NATIVE;
138
5
}
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
16
        return is_supported_table_format(range);
239
25
    } else if (format_type == TFileFormatType::FORMAT_ARROW) {
240
3
        return is_supported_arrow_table_format(range);
241
22
    } else if (format_type == TFileFormatType::FORMAT_JNI) {
242
3
        return is_supported_jni_table_format(range);
243
19
    } else if (is_csv_format(format_type) || is_text_format(format_type) ||
244
19
               is_json_format(format_type) || is_native_format(format_type)) {
245
15
        return is_supported_table_format(range);
246
15
    } else {
247
4
        LOG(WARNING) << "Unsupported file format type " << format_type << " for file scanner v2";
248
4
        return false;
249
4
    }
250
41
}
251
252
FileScannerV2::FileScannerV2(RuntimeState* state, FileScanLocalState* local_state, int64_t limit,
253
                             std::shared_ptr<SplitSourceConnector> split_source,
254
                             RuntimeProfile* profile, ShardedKVCache* kv_cache,
255
                             const std::unordered_map<std::string, int>* colname_to_slot_id)
256
0
        : Scanner(state, local_state, limit, profile),
257
0
          _split_source(std::move(split_source)),
258
0
          _kv_cache(kv_cache) {
259
0
    (void)colname_to_slot_id;
260
0
    if (state->get_query_ctx() != nullptr &&
261
0
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
262
0
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
263
0
    } else {
264
0
        _params = _split_source->get_params();
265
0
    }
266
0
}
267
268
0
Status FileScannerV2::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
269
0
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
270
0
    _get_block_timer =
271
0
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerV2GetBlockTime", 1);
272
0
    _file_counter =
273
0
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "FileNumber", TUnit::UNIT, 1);
274
0
    _file_read_bytes_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
275
0
                                                      "FileReadBytes", TUnit::BYTES, 1);
276
0
    _file_read_calls_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
277
0
                                                      "FileReadCalls", TUnit::UNIT, 1);
278
0
    _file_read_time_counter =
279
0
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileReadTime", 1);
280
0
    _adaptive_batch_predicted_rows_counter = ADD_COUNTER_WITH_LEVEL(
281
0
            _local_state->scanner_profile(), "AdaptiveBatchPredictedRows", TUnit::UNIT, 1);
282
0
    _adaptive_batch_actual_bytes_counter = ADD_COUNTER_WITH_LEVEL(
283
0
            _local_state->scanner_profile(), "AdaptiveBatchActualBytes", TUnit::BYTES, 1);
284
0
    _adaptive_batch_probe_count_counter = ADD_COUNTER_WITH_LEVEL(
285
0
            _local_state->scanner_profile(), "AdaptiveBatchProbeCount", TUnit::UNIT, 1);
286
0
    _file_cache_statistics = std::make_unique<io::FileCacheStatistics>();
287
0
    _file_reader_stats = std::make_unique<io::FileReaderStats>();
288
0
    RETURN_IF_ERROR(_init_io_ctx());
289
0
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
290
0
    _io_ctx->file_reader_stats = _file_reader_stats.get();
291
0
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
292
0
    return Status::OK();
293
0
}
294
295
0
Status FileScannerV2::_open_impl(RuntimeState* state) {
296
0
    RETURN_IF_CANCELLED(state);
297
0
    RETURN_IF_ERROR(Scanner::_open_impl(state));
298
0
    RETURN_IF_ERROR(_split_source->get_next(&_first_scan_range, &_current_range));
299
0
    if (_first_scan_range) {
300
0
        RETURN_IF_ERROR(_create_table_reader_for_format(_current_range, &_table_reader));
301
0
        DORIS_CHECK(_table_reader != nullptr);
302
0
        RETURN_IF_ERROR(_init_expr_ctxes());
303
0
        RETURN_IF_ERROR(_init_table_reader(_current_range));
304
0
    }
305
0
    return Status::OK();
306
0
}
307
308
0
Status FileScannerV2::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
309
0
    while (true) {
310
0
        RETURN_IF_CANCELLED(state);
311
0
        if (!_has_prepared_split) {
312
0
            RETURN_IF_ERROR(_prepare_next_split(eof));
313
0
            if (*eof) {
314
0
                return Status::OK();
315
0
            }
316
0
        }
317
318
0
        {
319
0
            SCOPED_TIMER(_get_block_timer);
320
0
            if (_should_run_adaptive_batch_size()) {
321
0
                _table_reader->set_batch_size(_predict_reader_batch_rows());
322
0
            }
323
0
            RETURN_IF_ERROR(_table_reader->get_block(block, eof));
324
0
        }
325
0
        if (*eof) {
326
0
            _state->update_num_finished_scan_range(1);
327
0
            _has_prepared_split = false;
328
0
            *eof = false;
329
0
            continue;
330
0
        }
331
0
        _update_adaptive_batch_size(*block);
332
0
        return Status::OK();
333
0
    }
334
0
}
335
336
0
Status FileScannerV2::_prepare_next_split(bool* eos) {
337
0
    bool has_next = _first_scan_range;
338
0
    if (!_first_scan_range) {
339
0
        RETURN_IF_ERROR(_split_source->get_next(&has_next, &_current_range));
340
0
    }
341
0
    _first_scan_range = false;
342
0
    if (!has_next || _should_stop) {
343
0
        *eos = true;
344
0
        return Status::OK();
345
0
    }
346
0
    DORIS_CHECK(_table_reader != nullptr);
347
0
    _current_range_path = _current_range.path;
348
0
    _init_adaptive_batch_size_state(get_range_format_type(*_params, _current_range));
349
0
    RETURN_IF_ERROR(_prepare_table_reader_split(_current_range));
350
0
    COUNTER_UPDATE(_file_counter, 1);
351
0
    _has_prepared_split = true;
352
0
    *eos = false;
353
0
    return Status::OK();
354
0
}
355
356
0
Status FileScannerV2::_init_table_reader(const TFileRangeDesc& range) {
357
0
    const auto format_type = get_range_format_type(*_params, range);
358
0
    format::FileFormat file_format;
359
0
    RETURN_IF_ERROR(_to_file_format(format_type, &file_format));
360
0
    DORIS_CHECK(_table_reader != nullptr);
361
362
0
    VExprContextSPtrs table_conjuncts;
363
0
    RETURN_IF_ERROR(_build_table_conjuncts(&table_conjuncts));
364
0
    RETURN_IF_ERROR(_table_reader->init({
365
0
            .projected_columns = _projected_columns,
366
0
            .conjuncts = std::move(table_conjuncts),
367
0
            .format = file_format,
368
0
            .scan_params = const_cast<TFileScanRangeParams*>(_params),
369
0
            .io_ctx = _io_ctx,
370
0
            .runtime_state = _state,
371
0
            .scanner_profile = _local_state->scanner_profile(),
372
0
            .file_slot_descs = &_file_slot_descs,
373
0
            .push_down_agg_type = _local_state->get_push_down_agg_type(),
374
0
            .condition_cache_digest = _local_state->get_condition_cache_digest(),
375
0
    }));
376
0
    return Status::OK();
377
0
}
378
379
Status FileScannerV2::_create_table_reader_for_format(
380
0
        const TFileRangeDesc& range, std::unique_ptr<format::TableReader>* reader) const {
381
0
    DORIS_CHECK(reader != nullptr);
382
0
    const auto table_format = table_format_name(range);
383
0
    if (table_format == "NotSet" || table_format == "tvf") {
384
0
        *reader = std::make_unique<format::TableReader>();
385
0
    } else if (table_format == "hive") {
386
0
        *reader = format::hive::HiveReader::create_unique();
387
0
    } else if (table_format == "iceberg") {
388
0
        if (get_range_format_type(*_params, range) == TFileFormatType::FORMAT_JNI) {
389
0
            *reader = std::make_unique<format::iceberg::IcebergSysTableJniReader>();
390
0
        } else {
391
0
            *reader = std::make_unique<format::iceberg::IcebergTableReader>();
392
0
        }
393
0
    } else if (table_format == "paimon") {
394
0
        *reader = std::make_unique<format::paimon::PaimonHybridReader>();
395
0
    } else if (table_format == "hudi") {
396
0
        *reader = std::make_unique<format::hudi::HudiHybridReader>();
397
0
    } else if (table_format == "jdbc") {
398
0
        *reader = std::make_unique<format::jdbc::JdbcJniReader>();
399
0
    } else if (table_format == "max_compute") {
400
0
        const auto* mc_desc =
401
0
                static_cast<const MaxComputeTableDescriptor*>(_output_tuple_desc->table_desc());
402
0
        RETURN_IF_ERROR(mc_desc->init_status());
403
0
        *reader = std::make_unique<format::max_compute::MaxComputeJniReader>(mc_desc);
404
0
    } else if (table_format == "trino_connector") {
405
0
        *reader = std::make_unique<format::trino_connector::TrinoConnectorJniReader>();
406
0
    } else if (table_format == "remote_doris") {
407
0
        *reader = std::make_unique<format::remote_doris::RemoteDorisReader>();
408
0
    } else {
409
0
        return Status::NotSupported("FileScannerV2 does not support table format {}", table_format);
410
0
    }
411
0
    return Status::OK();
412
0
}
413
414
0
Status FileScannerV2::_prepare_table_reader_split(const TFileRangeDesc& range) {
415
0
    std::map<std::string, Field> partition_values;
416
0
    RETURN_IF_ERROR(_generate_partition_values(range, &partition_values));
417
0
    format::FileFormat current_split_format;
418
0
    RETURN_IF_ERROR(_to_file_format(get_range_format_type(*_params, range), &current_split_format));
419
0
    RETURN_IF_ERROR(_table_reader->prepare_split({
420
0
            .partition_values = std::move(partition_values),
421
0
            .cache = _kv_cache,
422
0
            .current_range = range,
423
0
            .current_split_format = current_split_format,
424
0
            .global_rowid_context = _create_global_rowid_context(range),
425
0
    }));
426
0
    return Status::OK();
427
0
}
428
429
0
bool FileScannerV2::_should_enable_file_meta_cache() const {
430
0
    return ExecEnv::GetInstance()->file_meta_cache()->enabled() &&
431
0
           _split_source->num_scan_ranges() < config::max_external_file_meta_cache_num / 3;
432
0
}
433
434
std::optional<format::GlobalRowIdContext> FileScannerV2::_create_global_rowid_context(
435
0
        const TFileRangeDesc& range) const {
436
0
    if (!_need_global_rowid_column) {
437
0
        return std::nullopt;
438
0
    }
439
0
    auto& id_file_map = _state->get_id_file_map();
440
0
    DORIS_CHECK(id_file_map != nullptr);
441
0
    const auto file_id = id_file_map->get_file_mapping_id(
442
0
            std::make_shared<FileMapping>(_local_state->cast<FileScanLocalState>().parent_id(),
443
0
                                          range, _should_enable_file_meta_cache()));
444
0
    return format::GlobalRowIdContext {
445
0
            .version = IdManager::ID_VERSION,
446
0
            .backend_id = BackendOptions::get_backend_id(),
447
0
            .file_id = file_id,
448
0
    };
449
0
}
450
451
Status FileScannerV2::_generate_partition_values(
452
0
        const TFileRangeDesc& range, std::map<std::string, Field>* partition_values) const {
453
0
    DORIS_CHECK(partition_values != nullptr);
454
0
    partition_values->clear();
455
0
    if (!range.__isset.columns_from_path_keys || !range.__isset.columns_from_path) {
456
0
        return Status::OK();
457
0
    }
458
0
    DORIS_CHECK(range.columns_from_path_keys.size() == range.columns_from_path.size());
459
0
    for (size_t idx = 0; idx < range.columns_from_path_keys.size(); ++idx) {
460
0
        const auto& key = range.columns_from_path_keys[idx];
461
0
        const auto it = _partition_slot_descs.find(key);
462
0
        if (it == _partition_slot_descs.end()) {
463
0
            continue;
464
0
        }
465
0
        const auto& value = range.columns_from_path[idx];
466
0
        const bool is_null = range.__isset.columns_from_path_is_null &&
467
0
                             idx < range.columns_from_path_is_null.size() &&
468
0
                             range.columns_from_path_is_null[idx];
469
0
        Field field;
470
0
        DORIS_CHECK(it->second.slot_desc != nullptr);
471
0
        RETURN_IF_ERROR(_parse_partition_value(it->second.slot_desc, value, is_null, &field));
472
0
        partition_values->emplace(it->second.canonical_name, std::move(field));
473
0
    }
474
0
    return Status::OK();
475
0
}
476
477
Status FileScannerV2::_parse_partition_value(const SlotDescriptor* slot_desc,
478
                                             const std::string& value, bool is_null,
479
0
                                             Field* field) const {
480
0
    DORIS_CHECK(slot_desc != nullptr);
481
0
    DORIS_CHECK(field != nullptr);
482
0
    if (is_null) {
483
0
        *field = Field::create_field<TYPE_NULL>(Null());
484
0
        return Status::OK();
485
0
    }
486
0
    const auto data_type = remove_nullable(slot_desc->get_data_type_ptr());
487
0
    auto column = data_type->create_column();
488
0
    auto serde = data_type->get_serde();
489
0
    DataTypeSerDe::FormatOptions options;
490
0
    options.converted_from_string = true;
491
0
    StringRef ref(value.data(), value.size());
492
0
    RETURN_IF_ERROR(serde->from_string(ref, *column, options));
493
0
    DORIS_CHECK(column->size() == 1);
494
0
    *field = (*column)[0];
495
0
    return Status::OK();
496
0
}
497
498
0
Status FileScannerV2::_init_expr_ctxes() {
499
0
    _slot_id_to_desc.clear();
500
0
    _slot_id_to_global_index.clear();
501
0
    _partition_slot_descs.clear();
502
0
    _file_slot_descs.clear();
503
0
    for (const auto* slot_desc : _output_tuple_desc->slots()) {
504
0
        _slot_id_to_desc.emplace(slot_desc->id(), slot_desc);
505
0
    }
506
0
    DORIS_CHECK(_table_reader != nullptr);
507
0
    RETURN_IF_ERROR(_build_projected_columns(*_table_reader));
508
0
    return Status::OK();
509
0
}
510
511
0
Status FileScannerV2::_build_projected_columns(const format::TableReader& table_reader) {
512
0
    _projected_columns.clear();
513
0
    _projected_columns.reserve(_params->required_slots.size());
514
0
    _need_global_rowid_column = false;
515
0
    format::ProjectedColumnBuildContext build_context {
516
0
            .scan_params = _params,
517
0
            .range = &_current_range,
518
0
            .runtime_state = _state,
519
0
    };
520
521
0
    for (size_t slot_idx = 0; slot_idx < _params->required_slots.size(); ++slot_idx) {
522
0
        const auto& slot_info = _params->required_slots[slot_idx];
523
0
        const auto it = _slot_id_to_desc.find(slot_info.slot_id);
524
0
        if (it == _slot_id_to_desc.end()) {
525
0
            return Status::InternalError("Unknown source slot descriptor, slot_id={}",
526
0
                                         slot_info.slot_id);
527
0
        }
528
0
        auto column = _build_table_column(it->second);
529
0
        if (column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
530
0
            _need_global_rowid_column = true;
531
0
        }
532
0
        RETURN_IF_ERROR(_build_default_expr(slot_info, &column.default_expr));
533
0
        build_context.schema_column.reset();
534
0
        RETURN_IF_ERROR(table_reader.annotate_projected_column(slot_info, &build_context, &column));
535
        // Build nested children from access paths generated by the slot's access-path
536
        // expressions. A projected column can therefore contain only a subset of the schema
537
        // column's nested children.
538
0
        RETURN_IF_ERROR(AccessPathParser::build_nested_children(
539
0
                &column, it->second,
540
0
                build_context.schema_column.has_value() ? &*build_context.schema_column : nullptr));
541
0
        if (is_partition_slot(slot_info, column.name)) {
542
0
            column.is_partition_key = true;
543
0
            _partition_slot_descs.emplace(
544
0
                    column.name,
545
0
                    PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
546
0
            for (const auto& alias : column.name_mapping) {
547
0
                _partition_slot_descs.emplace(
548
0
                        alias,
549
0
                        PartitionSlotInfo {.slot_desc = it->second, .canonical_name = column.name});
550
0
            }
551
0
        } else if (is_data_file_slot(slot_info, column.name)) {
552
0
            _file_slot_descs.push_back(const_cast<SlotDescriptor*>(it->second));
553
0
        }
554
0
        const auto global_index = format::GlobalIndex(slot_idx);
555
0
        _slot_id_to_global_index.emplace(slot_info.slot_id, global_index);
556
0
        _projected_columns.push_back(std::move(column));
557
0
    }
558
0
    RETURN_IF_ERROR(table_reader.validate_projected_columns(build_context));
559
0
    return Status::OK();
560
0
}
561
562
Status FileScannerV2::_build_default_expr(const TFileScanSlotInfo& slot_info,
563
0
                                          VExprContextSPtr* ctx) const {
564
0
    DORIS_CHECK(ctx != nullptr);
565
0
    if (slot_info.__isset.default_value_expr && !slot_info.default_value_expr.nodes.empty()) {
566
0
        return VExpr::create_expr_tree(slot_info.default_value_expr, *ctx);
567
0
    }
568
569
0
    if (_params->__isset.default_value_of_src_slot) {
570
0
        const auto it = _params->default_value_of_src_slot.find(slot_info.slot_id);
571
0
        if (it != _params->default_value_of_src_slot.end() && !it->second.nodes.empty()) {
572
0
            return VExpr::create_expr_tree(it->second, *ctx);
573
0
        }
574
0
    }
575
0
    return Status::OK();
576
0
}
577
578
0
format::ColumnDefinition FileScannerV2::_build_table_column(const SlotDescriptor* slot_desc) {
579
0
    DORIS_CHECK(slot_desc != nullptr);
580
0
    format::ColumnDefinition column;
581
    // TODO(gabriel): why always BY_NAME here?
582
0
    column.identifier = Field::create_field<TYPE_STRING>(slot_desc->col_name());
583
0
    column.name = slot_desc->col_name();
584
0
    column.type = slot_desc->get_data_type_ptr();
585
0
    return column;
586
0
}
587
588
0
Status FileScannerV2::_build_table_conjuncts(VExprContextSPtrs* conjuncts) const {
589
0
    DORIS_CHECK(conjuncts != nullptr);
590
0
    conjuncts->clear();
591
0
    conjuncts->reserve(_conjuncts.size());
592
0
    for (const auto& conjunct : _conjuncts) {
593
0
        VExprSPtr root;
594
0
        RETURN_IF_ERROR(format::clone_table_expr_tree(conjunct->root(), &root));
595
0
        RETURN_IF_ERROR(rewrite_slot_refs_to_global_index(&root, _slot_id_to_global_index));
596
0
        conjuncts->push_back(VExprContext::create_shared(std::move(root)));
597
0
    }
598
0
    return Status::OK();
599
0
}
600
601
0
TFileFormatType::type FileScannerV2::_get_current_format_type() const {
602
0
    return get_range_format_type(*_params, _current_range);
603
0
}
604
605
Status FileScannerV2::_to_file_format(TFileFormatType::type format_type,
606
16
                                      format::FileFormat* file_format) {
607
16
    DORIS_CHECK(file_format != nullptr);
608
16
    switch (format_type) {
609
1
    case TFileFormatType::FORMAT_PARQUET:
610
1
        *file_format = format::FileFormat::PARQUET;
611
1
        return Status::OK();
612
1
    case TFileFormatType::FORMAT_JNI:
613
1
        *file_format = format::FileFormat::JNI;
614
1
        return Status::OK();
615
1
    case TFileFormatType::FORMAT_CSV_PLAIN:
616
2
    case TFileFormatType::FORMAT_CSV_GZ:
617
3
    case TFileFormatType::FORMAT_CSV_BZ2:
618
4
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
619
5
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
620
6
    case TFileFormatType::FORMAT_CSV_LZOP:
621
7
    case TFileFormatType::FORMAT_CSV_DEFLATE:
622
8
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
623
9
    case TFileFormatType::FORMAT_PROTO:
624
9
        *file_format = format::FileFormat::CSV;
625
9
        return Status::OK();
626
1
    case TFileFormatType::FORMAT_TEXT:
627
1
        *file_format = format::FileFormat::TEXT;
628
1
        return Status::OK();
629
1
    case TFileFormatType::FORMAT_JSON:
630
1
        *file_format = format::FileFormat::JSON;
631
1
        return Status::OK();
632
1
    case TFileFormatType::FORMAT_NATIVE:
633
1
        *file_format = format::FileFormat::NATIVE;
634
1
        return Status::OK();
635
1
    case TFileFormatType::FORMAT_ARROW:
636
1
        *file_format = format::FileFormat::ARROW;
637
1
        return Status::OK();
638
1
    default:
639
1
        return Status::NotSupported("FileScannerV2 does not support file format {}",
640
1
                                    to_string(format_type));
641
16
    }
642
16
}
643
644
0
Status FileScannerV2::_init_io_ctx() {
645
0
    _io_ctx = std::make_shared<io::IOContext>();
646
0
    _io_ctx->query_id = &_state->query_id();
647
0
    return Status::OK();
648
0
}
649
650
0
void FileScannerV2::_reset_adaptive_batch_size_state() {
651
0
    _block_size_predictor.reset();
652
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, int64_t(0));
653
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, int64_t(0));
654
0
}
655
656
0
void FileScannerV2::_init_adaptive_batch_size_state(TFileFormatType::type format_type) {
657
0
    _reset_adaptive_batch_size_state();
658
0
    if (!_should_enable_adaptive_batch_size(format_type)) {
659
0
        return;
660
0
    }
661
662
    // V2 native file readers do not have reliable row-width hints before the first batch. Start
663
    // every split with a small probe, then learn bytes-per-row from the materialized table block
664
    // and keep later batches close to RuntimeState::preferred_block_size_bytes().
665
0
    _block_size_predictor = std::make_unique<AdaptiveBlockSizePredictor>(
666
0
            _state->preferred_block_size_bytes(), 0.0, ADAPTIVE_BATCH_INITIAL_PROBE_ROWS,
667
0
            _state->batch_size());
668
0
}
669
670
0
bool FileScannerV2::_should_enable_adaptive_batch_size(TFileFormatType::type format_type) const {
671
0
    if (!config::enable_adaptive_batch_size) {
672
0
        return false;
673
0
    }
674
0
    switch (format_type) {
675
0
    case TFileFormatType::FORMAT_PARQUET:
676
0
    case TFileFormatType::FORMAT_ORC:
677
0
    case TFileFormatType::FORMAT_CSV_PLAIN:
678
0
    case TFileFormatType::FORMAT_CSV_GZ:
679
0
    case TFileFormatType::FORMAT_CSV_BZ2:
680
0
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
681
0
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
682
0
    case TFileFormatType::FORMAT_CSV_LZOP:
683
0
    case TFileFormatType::FORMAT_CSV_DEFLATE:
684
0
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
685
0
    case TFileFormatType::FORMAT_PROTO:
686
0
    case TFileFormatType::FORMAT_TEXT:
687
0
    case TFileFormatType::FORMAT_JSON:
688
0
    case TFileFormatType::FORMAT_JNI:
689
0
        return true;
690
0
    default:
691
0
        return false;
692
0
    }
693
0
}
694
695
0
bool FileScannerV2::_should_run_adaptive_batch_size() const {
696
    // COUNT pushdown emits synthetic rows from file metadata and does not materialize file columns,
697
    // so there is no useful row-width sample to learn from.
698
0
    return _block_size_predictor != nullptr &&
699
0
           _local_state->get_push_down_agg_type() != TPushAggOp::type::COUNT;
700
0
}
701
702
0
size_t FileScannerV2::_predict_reader_batch_rows() {
703
0
    DORIS_CHECK(_block_size_predictor != nullptr);
704
    // Before history exists this returns the probe row count; after update(), it returns roughly
705
    // preferred_block_size_bytes / EWMA(bytes_per_row), capped by RuntimeState::batch_size().
706
0
    const size_t predicted_rows = _block_size_predictor->predict_next_rows();
707
0
    COUNTER_SET(_adaptive_batch_predicted_rows_counter, static_cast<int64_t>(predicted_rows));
708
0
    return predicted_rows;
709
0
}
710
711
0
void FileScannerV2::_update_adaptive_batch_size(const Block& block) {
712
0
    if (!_should_run_adaptive_batch_size()) {
713
0
        return;
714
0
    }
715
0
    COUNTER_SET(_adaptive_batch_actual_bytes_counter, static_cast<int64_t>(block.bytes()));
716
0
    if (block.rows() == 0) {
717
0
        return;
718
0
    }
719
    // The sample is taken after TableReader has finalized file-local columns to table columns.
720
    // This matches the memory shape seen by upstream operators and catches very wide nested
721
    // columns, such as map/string payloads, after the first probe batch.
722
0
    if (!_block_size_predictor->has_history()) {
723
0
        COUNTER_UPDATE(_adaptive_batch_probe_count_counter, 1);
724
0
    }
725
0
    _block_size_predictor->update(block);
726
0
}
727
728
0
Status FileScannerV2::close(RuntimeState* state) {
729
0
    if (!_try_close()) {
730
0
        return Status::OK();
731
0
    }
732
0
    if (_table_reader != nullptr) {
733
0
        RETURN_IF_ERROR(_table_reader->close());
734
0
        _report_condition_cache_profile();
735
0
        _table_reader.reset();
736
0
    }
737
0
    return Scanner::close(state);
738
0
}
739
740
0
void FileScannerV2::try_stop() {
741
0
    Scanner::try_stop();
742
0
    if (_io_ctx) {
743
0
        _io_ctx->should_stop = true;
744
0
    }
745
0
}
746
747
0
void FileScannerV2::update_realtime_counters() {
748
0
    if (_file_reader_stats == nullptr) {
749
0
        return;
750
0
    }
751
0
    const int64_t bytes_read = _file_reader_stats->read_bytes;
752
0
    COUNTER_SET(_file_read_bytes_counter, bytes_read);
753
0
    COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
754
0
    COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
755
0
}
756
757
0
void FileScannerV2::_collect_profile_before_close() {
758
0
    _report_file_reader_predicate_filtered_rows();
759
0
    Scanner::_collect_profile_before_close();
760
0
    if (_file_reader_stats != nullptr) {
761
0
        COUNTER_SET(_file_read_bytes_counter, cast_set<int64_t>(_file_reader_stats->read_bytes));
762
0
        COUNTER_SET(_file_read_calls_counter, cast_set<int64_t>(_file_reader_stats->read_calls));
763
0
        COUNTER_SET(_file_read_time_counter, cast_set<int64_t>(_file_reader_stats->read_time_ns));
764
0
    }
765
    // Query profiles can be collected before Scanner::close() runs. Publish condition-cache
766
    // counters here as well, using deltas so this method and close() cannot double count.
767
0
    _report_condition_cache_profile();
768
0
}
769
770
0
bool FileScannerV2::_should_update_load_counters() const {
771
0
    if (_is_load) {
772
0
        return true;
773
0
    }
774
    // TVF based loads (e.g. http_stream, group commit relay) plan the load source as a
775
    // tvf query scan without src tuple desc, so _is_load is false. But rows filtered by
776
    // the load's WHERE clause still need to be reported as unselected rows. FILE_STREAM
777
    // is only reachable from such load entries, never from normal queries, so use it to
778
    // identify these scanners.
779
0
    return (_params != nullptr && _params->__isset.file_type &&
780
0
            _params->file_type == TFileType::FILE_STREAM) ||
781
0
           (_current_range.__isset.file_type && _current_range.file_type == TFileType::FILE_STREAM);
782
0
}
783
784
0
void FileScannerV2::_report_file_reader_predicate_filtered_rows() {
785
0
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->predicate_filtered_rows : 0;
786
0
    const int64_t filtered_delta = filtered_rows - _reported_predicate_filtered_rows;
787
0
    if (filtered_delta > 0) {
788
        // File readers can evaluate localized conjuncts before a block reaches Scanner. Count
789
        // those rows as scanner-level unselected rows so load statistics stay identical no matter
790
        // whether a predicate is pushed down or evaluated by Scanner::_filter_output_block().
791
0
        _counter.num_rows_unselected += filtered_delta;
792
0
        _reported_predicate_filtered_rows = filtered_rows;
793
0
    }
794
0
}
795
796
0
void FileScannerV2::_report_condition_cache_profile() {
797
0
    auto* local_state = static_cast<FileScanLocalState*>(_local_state);
798
0
    const int64_t hit_count =
799
0
            _table_reader != nullptr ? _table_reader->condition_cache_hit_count() : 0;
800
0
    const int64_t hit_delta = hit_count - _reported_condition_cache_hit_count;
801
0
    if (hit_delta > 0) {
802
0
        COUNTER_UPDATE(local_state->_condition_cache_hit_counter, hit_delta);
803
0
        _reported_condition_cache_hit_count = hit_count;
804
0
    }
805
0
    const int64_t filtered_rows = _io_ctx != nullptr ? _io_ctx->condition_cache_filtered_rows : 0;
806
0
    const int64_t filtered_delta = filtered_rows - _reported_condition_cache_filtered_rows;
807
0
    if (filtered_delta > 0) {
808
0
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter, filtered_delta);
809
0
        _reported_condition_cache_filtered_rows = filtered_rows;
810
0
    }
811
0
}
812
813
} // namespace doris