Coverage Report

Created: 2026-08-04 06:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/table_reader.h
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
#pragma once
19
20
#include <bvar/status.h>
21
22
#include <algorithm>
23
#include <exception>
24
#include <map>
25
#include <memory>
26
#include <optional>
27
#include <string>
28
#include <string_view>
29
#include <utility>
30
#include <vector>
31
32
#include "common/cast_set.h"
33
#include "common/exception.h"
34
#include "common/logging.h"
35
#include "common/status.h"
36
#include "core/assert_cast.h"
37
#include "core/block/block.h"
38
#include "core/column/column_array.h"
39
#include "core/column/column_const.h"
40
#include "core/column/column_map.h"
41
#include "core/column/column_nullable.h"
42
#include "core/column/column_struct.h"
43
#include "core/column/column_vector.h"
44
#include "core/data_type/data_type.h"
45
#include "core/data_type/data_type_array.h"
46
#include "core/data_type/data_type_map.h"
47
#include "core/data_type/data_type_nullable.h"
48
#include "core/data_type/data_type_number.h"
49
#include "core/data_type/data_type_string.h"
50
#include "core/data_type/data_type_struct.h"
51
#include "core/field.h"
52
#include "exec/common/stringop_substring.h"
53
#include "exprs/vexpr.h"
54
#include "exprs/vexpr_context.h"
55
#include "exprs/vexpr_fwd.h"
56
#include "exprs/vslot_ref.h"
57
#include "format/table/deletion_vector.h"
58
#include "format_v2/column_data.h"
59
#include "format_v2/column_mapper.h"
60
#include "format_v2/expr/cast.h"
61
#include "format_v2/expr/delete_predicate.h"
62
#include "format_v2/file_reader.h"
63
#include "format_v2/parquet/reader/column_reader.h"
64
#include "format_v2/schema_projection.h"
65
#include "gen_cpp/PlanNodes_types.h"
66
#include "io/io_common.h"
67
#include "runtime/descriptors.h"
68
#include "storage/segment/condition_cache.h"
69
70
namespace doris {
71
class Block;
72
struct DeleteFileDesc;
73
class RuntimeState;
74
} // namespace doris
75
76
namespace doris::format {
77
78
using DeleteRows = std::vector<int64_t>;
79
80
// Row-level predicates on table/global schema. They are rewritten to file-local expressions when
81
// possible, and remain the source of row-level filtering after localization.
82
struct TableFilter {
83
    VExprContextSPtr conjunct;
84
    std::vector<GlobalIndex> global_indices;
85
};
86
87
struct ScanTask {
88
127k
    virtual ~ScanTask() = default;
89
90
    std::unique_ptr<io::FileDescription> data_file;
91
};
92
93
struct ProjectedColumnBuildContext {
94
    const TFileScanRangeParams* scan_params = nullptr;
95
    const TFileRangeDesc* range = nullptr;
96
    RuntimeState* runtime_state = nullptr;
97
    const SlotDescriptor* slot_desc = nullptr;
98
    std::optional<ColumnDefinition> schema_column = std::nullopt;
99
    size_t next_file_column_idx = 0;
100
};
101
102
struct ReadProfile {
103
    RuntimeProfile::Counter* total_timer = nullptr;
104
    RuntimeProfile::Counter* init_timer = nullptr;
105
    RuntimeProfile::Counter* num_delete_files = nullptr;
106
    RuntimeProfile::Counter* num_delete_rows = nullptr;
107
    RuntimeProfile::Counter* parse_delete_file_time = nullptr;
108
    RuntimeProfile::Counter* decoded_dv_cache_hit_count = nullptr;
109
    RuntimeProfile::Counter* decoded_dv_cache_miss_count = nullptr;
110
    RuntimeProfile::Counter* dv_file_cache_hit_count = nullptr;
111
    RuntimeProfile::Counter* dv_file_cache_miss_count = nullptr;
112
    RuntimeProfile::Counter* dv_file_cache_peer_read_count = nullptr;
113
    RuntimeProfile::Counter* exec_timer = nullptr;
114
    RuntimeProfile::Counter* prepare_split_timer = nullptr;
115
    RuntimeProfile::Counter* finalize_timer = nullptr;
116
    RuntimeProfile::Counter* create_reader_timer = nullptr;
117
    RuntimeProfile::Counter* pushdown_agg_timer = nullptr;
118
    RuntimeProfile::Counter* open_reader_timer = nullptr;
119
    RuntimeProfile::Counter* refresh_conjuncts_timer = nullptr;
120
    RuntimeProfile::Counter* runtime_filter_partition_prune_timer = nullptr;
121
    RuntimeProfile::Counter* runtime_filter_partition_pruned_range_counter = nullptr;
122
    RuntimeProfile::Counter* close_timer = nullptr;
123
    RuntimeProfile::Counter* file_reader_total_timer = nullptr;
124
    RuntimeProfile::Counter* file_reader_init_timer = nullptr;
125
    RuntimeProfile::Counter* file_reader_schema_timer = nullptr;
126
    RuntimeProfile::Counter* file_reader_mapper_timer = nullptr;
127
    RuntimeProfile::Counter* file_reader_open_timer = nullptr;
128
    RuntimeProfile::Counter* file_reader_refresh_timer = nullptr;
129
    RuntimeProfile::Counter* file_reader_get_block_timer = nullptr;
130
    RuntimeProfile::Counter* file_reader_aggregate_timer = nullptr;
131
    RuntimeProfile::Counter* file_reader_close_timer = nullptr;
132
};
133
134
struct TableReadOptions {
135
    // Columns need to be read from file and output by table reader. They are all in table/global
136
    // schema semantics.
137
    const std::vector<ColumnDefinition> projected_columns;
138
    // All complex conjuncts from scan operator
139
    const VExprContextSPtrs conjuncts;
140
    // File format of the underlying data files, needed for reader initialization and reader-level
141
    // filter pushdown.
142
    const FileFormat format;
143
    TFileScanRangeParams* scan_params;
144
    std::shared_ptr<io::IOContext> io_ctx;
145
    RuntimeState* runtime_state;
146
    RuntimeProfile* scanner_profile;
147
    // File formats without complete self-describing metadata, such as CSV, Text, and JSON, need
148
    // the FE-planned physical file slots to build their file-local schema and deserialize values.
149
    const std::vector<SlotDescriptor*>* file_slot_descs = nullptr;
150
    // Push-down aggregate type.
151
    const TPushAggOp::type push_down_agg_type = TPushAggOp::type::NONE;
152
    // Table/global indices of explicit COUNT arguments. nullopt means an old FE did not send the
153
    // semantic argument field, while an explicit empty vector means COUNT(*)/COUNT(1). Keeping
154
    // those states separate prevents a rolling-upgrade plan from being reinterpreted by a new BE.
155
    const std::optional<std::vector<GlobalIndex>> push_down_count_columns = std::nullopt;
156
    // Initial digest of predicates available during scanner open. Scanner-driven splits override it
157
    // with SplitReadOptions::condition_cache_digest after collecting late-arrival runtime filters.
158
    // A zero digest disables condition cache.
159
    uint64_t condition_cache_digest = 0;
160
};
161
162
struct SplitReadOptions {
163
    // Split-level information for reader initialization, which may include file path, partition values, delete file info, etc. The content is table format specific and opaque to table reader base class; it's the responsibility of the concrete table reader implementation to parse necessary information for reader initialization and filter pushdown.
164
    std::map<std::string, Field> partition_values;
165
    // Latest scanner conjuncts rewritten to table/global column indices. Runtime filters may
166
    // arrive after TableReader::init(), so scanner-driven splits replace the initial snapshot.
167
    // nullopt preserves the initial snapshot for standalone TableReader callers.
168
    std::optional<VExprContextSPtrs> conjuncts = std::nullopt;
169
    // Independent clones used for partition pruning because evaluation prepares and opens them
170
    // against a synthetic partition block before the file reader opens its row-level conjuncts.
171
    VExprContextSPtrs partition_prune_conjuncts;
172
    // Table-level COUNT may emit one metadata-derived batch and resume on a later scheduler turn.
173
    // It is safe only after every runtime filter assigned to the scanner has arrived; otherwise a
174
    // filter could arrive after synthetic rows have already been returned and those rows cannot be
175
    // retracted. Standalone TableReader callers have no scanner runtime-filter lifecycle.
176
    bool all_runtime_filters_applied = true;
177
    // Digest for the exact scanner conjunct snapshot attached to this split. FileScannerV2 rebuilds
178
    // it after collecting late-arrival RFs, so different RF payloads cannot share a cache entry. A
179
    // zero value explicitly disables condition cache for this split.
180
    std::optional<uint64_t> condition_cache_digest;
181
    ShardedKVCache* cache = nullptr;
182
    TFileRangeDesc current_range;
183
    FileFormat current_split_format = FileFormat::PARQUET;
184
    std::optional<GlobalRowIdContext> global_rowid_context;
185
};
186
187
// Base class for table-level readers.
188
// This layer owns common table-level orchestration, such as split iteration, dynamic partition
189
// pruning, delete handling and conversion from file-local blocks to table-schema blocks. Concrete
190
// table-format readers only need to provide format-specific hooks for opening readers and parsing
191
// split metadata.
192
class TableReader {
193
public:
194
60.2k
    virtual ~TableReader() = default;
195
196
    // Initialize common runtime options for the table reader. Subclasses may call this from their
197
    // own init(options); table-format schema and split metadata are provided later per split.
198
    virtual Status init(TableReadOptions&& options);
199
200
    // FileScannerV2 adjusts this before each get_block() using an adaptive bytes-per-row estimate.
201
    // Store it here as well as forwarding to the current reader so newly opened split readers start
202
    // with the latest predicted batch size.
203
493k
    virtual void set_batch_size(size_t batch_size) {
204
493k
        _batch_size = std::max<size_t>(1, batch_size);
205
493k
        if (_data_reader.reader != nullptr) {
206
108k
            _data_reader.reader->set_batch_size(_batch_size);
207
108k
        }
208
493k
    }
209
210
#ifdef BE_TEST
211
    size_t TEST_batch_size() const { return _batch_size; }
212
    void TEST_set_condition_cache_hit_count(int64_t hits) { _condition_cache_hit_count = hits; }
213
    bool TEST_current_data_file_is_immutable() const {
214
        DORIS_CHECK(_current_task != nullptr);
215
        DORIS_CHECK(_current_task->data_file != nullptr);
216
        DORIS_CHECK(_current_file_description.has_value());
217
        DORIS_CHECK(_current_task->data_file->is_immutable ==
218
                    _current_file_description->is_immutable);
219
        return _current_task->data_file->is_immutable;
220
    }
221
#endif
222
223
    // Prepare for reading a new split/task.
224
    // 1. Pass a new split/task to reader, which will be used in subsequent open_reader() to initialize the underlying file reader.
225
    // 2. Parse delete predicates from split/task information, which will be used for later dynamic filtering and delete handling.
226
    virtual Status prepare_split(const SplitReadOptions& options);
227
228
    // Refresh row-level predicates for an already prepared split. Physical readers that support
229
    // this operation decide the safe boundary at which the new immutable request becomes active.
230
    virtual Status refresh_conjuncts(VExprContextSPtrs conjuncts);
231
232
223k
    virtual bool current_split_pruned() const { return _current_split_pruned; }
233
364k
    virtual bool current_split_uses_metadata_count() const {
234
364k
        return _current_split_uses_metadata_count;
235
364k
    }
236
237
    // Discard the active split after the caller decides an error is ignorable, for example a
238
    // stale external-table file listing that returns NOT_FOUND. The next prepare_split() must start
239
    // with no concrete reader or split-local state left from the failed split.
240
1
    virtual Status abort_split() {
241
        // Ignored open failures still spend time closing partially initialized readers. Include
242
        // that recovery path in the common lifecycle profile so NOT_FOUND cannot become invisible.
243
1
        SCOPED_TIMER(_profile.total_timer);
244
1
        SCOPED_TIMER(_profile.close_timer);
245
1
        if (_data_reader.reader != nullptr) {
246
1
            RETURN_IF_ERROR(close_current_reader());
247
1
        } else {
248
0
            _current_task.reset();
249
0
            _current_file_description.reset();
250
0
        }
251
1
        _delete_rows = nullptr;
252
1
        _remaining_table_level_count = -1;
253
1
        _remaining_file_level_count = -1;
254
1
        _current_split_uses_metadata_count = false;
255
1
        _current_split_pruned = false;
256
1
        return Status::OK();
257
1
    }
258
259
    // Public entry point for reading a table-schema block. The base class opens the current reader,
260
    // advances across EOF, and closes exhausted readers. Subclasses provide protected hooks for
261
    // table-format-specific behavior.
262
232k
    virtual Status get_block(Block* block, bool* eos) {
263
232k
        SCOPED_TIMER(_profile.total_timer);
264
232k
        SCOPED_TIMER(_profile.exec_timer);
265
232k
        DORIS_CHECK(block->columns() == _projected_columns.size());
266
232k
        block->clear_column_data(_projected_columns.size());
267
268
362k
        while (true) {
269
362k
            if (*eos) {
270
0
                return Status::OK();
271
0
            }
272
362k
            if (_io_ctx != nullptr && _io_ctx->should_stop) {
273
8
                *eos = true;
274
8
                return Status::OK();
275
8
            }
276
362k
            if (!_data_reader.reader) {
277
242k
                if (_is_table_level_count_active()) {
278
314
                    RETURN_IF_ERROR(_read_table_level_count(block, eos));
279
314
                    return Status::OK();
280
314
                }
281
242k
                if (_is_file_level_count_active()) {
282
2.97k
                    RETURN_IF_ERROR(_read_file_level_count(block, eos));
283
2.97k
                    return Status::OK();
284
2.97k
                }
285
239k
                RETURN_IF_ERROR(create_next_reader(eos));
286
239k
                if (!_data_reader.reader) {
287
118k
                    DCHECK(*eos);
288
118k
                    return Status::OK();
289
118k
                }
290
239k
            }
291
292
            // Materialize a reduced row set for upper aggregate operators when aggregate
293
            // pushdown can be applied. This is not the final aggregate result: COUNT emits
294
            // `count` default rows for the upper COUNT(*), and MIN/MAX emits two rows containing
295
            // file-level min/max values for the upper MIN/MAX.
296
240k
            if (!_aggregate_pushdown_tried) {
297
120k
                SCOPED_TIMER(_profile.pushdown_agg_timer);
298
120k
                bool pushed_down = false;
299
120k
                const auto status = _try_materialize_aggregate_pushdown_rows(block, &pushed_down);
300
120k
                if (!status.ok()) {
301
1
                    if (_io_ctx != nullptr && _io_ctx->should_stop &&
302
1
                        status.is<ErrorCode::END_OF_FILE>()) {
303
1
                        *eos = true;
304
1
                        return Status::OK();
305
1
                    }
306
0
                    return status;
307
1
                }
308
120k
                if (pushed_down) {
309
1.52k
                    return Status::OK();
310
1.52k
                }
311
120k
            }
312
313
238k
            bool current_eof = false;
314
238k
            _data_reader.block_template.clear_column_data(
315
238k
                    cast_set<int64_t>(_data_reader.file_block_layout.size()));
316
238k
            size_t current_rows = 0;
317
238k
            {
318
238k
                SCOPED_TIMER(_profile.file_reader_total_timer);
319
238k
                SCOPED_TIMER(_profile.file_reader_get_block_timer);
320
238k
                RETURN_IF_ERROR(_data_reader.reader->get_block(&_data_reader.block_template,
321
238k
                                                               &current_rows, &current_eof));
322
238k
            }
323
239k
            const bool stopped_during_read = _io_ctx != nullptr && _io_ctx->should_stop;
324
238k
            if (current_rows == 0) {
325
130k
                if (current_eof) {
326
118k
                    _current_reader_reached_eof = !stopped_during_read;
327
118k
                    RETURN_IF_ERROR(close_current_reader());
328
118k
                }
329
130k
                continue;
330
130k
            }
331
238k
            DCHECK_EQ(_data_reader.block_template.columns(), _data_reader.file_block_layout.size())
332
0
                    << _data_reader.block_template.dump_structure();
333
108k
#ifndef NDEBUG
334
108k
            RETURN_IF_ERROR(_check_file_block_columns("after file reader get_block", current_rows));
335
108k
#endif
336
108k
            DORIS_CHECK(block->columns() == _data_reader.column_mapper->mappings().size());
337
108k
            RETURN_IF_ERROR(finalize_chunk(block, current_rows));
338
108k
#ifndef NDEBUG
339
108k
            RETURN_IF_ERROR(
340
108k
                    _check_table_block_columns("after finalize_chunk", block, current_rows));
341
108k
#endif
342
108k
            if (current_eof) {
343
19
                _current_reader_reached_eof = !stopped_during_read;
344
19
                RETURN_IF_ERROR(close_current_reader());
345
19
            }
346
108k
            return Status::OK();
347
108k
        }
348
232k
    }
349
350
    // Close the table reader and the currently active file reader. Subclasses that hold additional
351
    // table-format resources should override this and call TableReader::close() first.
352
53.8k
    virtual Status close() {
353
53.8k
        SCOPED_TIMER(_profile.total_timer);
354
53.8k
        SCOPED_TIMER(_profile.close_timer);
355
53.8k
        if (_data_reader.reader) {
356
654
            RETURN_IF_ERROR(close_current_reader());
357
654
        }
358
53.8k
        _current_task.reset();
359
53.8k
        _current_file_description.reset();
360
53.8k
        _remaining_table_level_count = -1;
361
53.8k
        _remaining_file_level_count = -1;
362
53.8k
        _current_split_uses_metadata_count = false;
363
53.8k
        return Status::OK();
364
53.8k
    }
365
366
106k
    virtual int64_t condition_cache_hit_count() const { return _condition_cache_hit_count; }
367
368
    virtual std::string debug_string() const;
369
370
    virtual Status annotate_projected_column(const TFileScanSlotInfo& slot_info,
371
                                             ProjectedColumnBuildContext* context,
372
                                             ColumnDefinition* column) const;
373
374
34.3k
    virtual Status validate_projected_columns(const ProjectedColumnBuildContext& context) const {
375
34.3k
        (void)context;
376
34.3k
        return Status::OK();
377
34.3k
    }
378
379
protected:
380
    // TableReader keeps the active file description both in the scan task and separately for
381
    // creating the physical reader. Table-format readers must update both copies when their
382
    // snapshot protocol guarantees that a file path is never overwritten with different bytes.
383
    // This guarantee lets readers safely build cache keys without mtime; it must not be used for
384
    // ordinary Hive/TVF files whose paths may be overwritten in place.
385
89.0k
    void mark_current_data_file_immutable() {
386
89.0k
        DORIS_CHECK(_current_task != nullptr);
387
89.0k
        DORIS_CHECK(_current_task->data_file != nullptr);
388
89.0k
        DORIS_CHECK(_current_file_description.has_value());
389
89.0k
        _current_task->data_file->is_immutable = true;
390
89.0k
        _current_file_description->is_immutable = true;
391
89.0k
    }
392
393
    std::optional<ColumnDefinition> _find_current_table_column_by_field_id(int32_t field_id,
394
                                                                           DataTypePtr type) const;
395
396
    // Parse deletion vector information from table format specific file description.
397
    virtual Status _parse_deletion_vector_file(const TTableFormatFileDesc& t_desc,
398
37.5k
                                               DeleteFileDesc* desc, bool* has_delete_file) {
399
37.5k
        *has_delete_file = false;
400
37.5k
        return Status::OK();
401
37.5k
    }
402
403
    // Advance to the next reader. This closes the current reader first and then opens the next
404
    // concrete reader. Subclasses should not duplicate this loop.
405
    Status create_next_reader(bool* eos);
406
    virtual Status create_file_reader(std::unique_ptr<FileReader>* reader);
407
6.50k
    virtual TableColumnMappingMode mapping_mode() const { return TableColumnMappingMode::BY_NAME; }
408
89.7k
    virtual void configure_mapper_options(TableColumnMapperOptions*) const {}
409
38.0k
    virtual Status annotate_file_schema(std::vector<ColumnDefinition>* file_schema) {
410
38.0k
        DORIS_CHECK(file_schema != nullptr);
411
38.0k
        return Status::OK();
412
38.0k
    }
413
414
    // Open the concrete reader for the current split/task and build the file-local scan request.
415
121k
    virtual Status open_reader() {
416
121k
        SCOPED_TIMER(_profile.open_reader_timer);
417
        // 1. Get file schema and create column mapping.
418
121k
        std::vector<ColumnDefinition> file_schema;
419
121k
        {
420
121k
            SCOPED_TIMER(_profile.file_reader_total_timer);
421
121k
            SCOPED_TIMER(_profile.file_reader_schema_timer);
422
121k
            RETURN_IF_ERROR(_data_reader.reader->get_schema(&file_schema));
423
121k
        }
424
        // For Paimon/Hudi, FE can provide field ids through `history_schema_info`. Annotate the
425
        // file schema before column mapping when the table format maps columns by field id.
426
121k
        RETURN_IF_ERROR(annotate_file_schema(&file_schema));
427
121k
        _data_reader.file_schema = file_schema;
428
121k
        _mapper_options.mode = mapping_mode();
429
121k
        configure_mapper_options(&_mapper_options);
430
431
121k
        {
432
121k
            SCOPED_TIMER(_profile.file_reader_total_timer);
433
121k
            SCOPED_TIMER(_profile.file_reader_mapper_timer);
434
121k
            _data_reader.column_mapper = _data_reader.reader->create_column_mapper(_mapper_options);
435
121k
        }
436
121k
        DORIS_CHECK(_data_reader.column_mapper != nullptr);
437
121k
        RETURN_IF_ERROR(_data_reader.column_mapper->create_mapping(_projected_columns,
438
121k
                                                                   _partition_values, file_schema));
439
121k
        DORIS_CHECK(_data_reader.column_mapper->mappings().size() == _projected_columns.size());
440
441
        // 2. Build table filters based on conjuncts and column predicates.
442
121k
        RETURN_IF_ERROR(_build_table_filters_from_conjuncts());
443
444
        // 3. Create file scan request based on column mapping and table filters, then open file
445
        // reader with the request. File scan request carries row-level expression filters and
446
        // file-level pruning hints. Only expression filters decide returned rows.
447
121k
        auto file_request = std::make_shared<FileScanRequest>();
448
121k
        RETURN_IF_ERROR(_data_reader.column_mapper->create_scan_request(
449
121k
                _table_filters, _projected_columns, file_request.get(), _runtime_state));
450
121k
        bool constant_filter_pruned_split = false;
451
121k
        RETURN_IF_ERROR(_evaluate_constant_filters(&constant_filter_pruned_split));
452
121k
        if (constant_filter_pruned_split) {
453
623
            RETURN_IF_ERROR(close_current_reader());
454
623
            return Status::OK();
455
623
        }
456
        // COUNT(*) has no semantic column argument, but Nereids retains a minimum-width scan slot
457
        // so the scan node still has an output tuple. Record only the current non-predicate file
458
        // columns before table-format hooks add row-position or equality-delete dependencies. This
459
        // marker is independent of aggregate eligibility: with position deletes, for example,
460
        // metadata COUNT must fall back to reading rows, but an arbitrary unsupported TIME_MILLIS
461
        // placeholder still must not be validated or decoded merely to carry the surviving count.
462
        // Pending runtime filters may later target this retained slot, so placeholder values are
463
        // safe only after every filter for the split has arrived.
464
120k
        if (_push_down_agg_type == TPushAggOp::type::COUNT &&
465
120k
            _push_down_count_columns.has_value() && _push_down_count_columns->empty() &&
466
120k
            _all_runtime_filters_applied_for_split) {
467
2.00k
            file_request->count_star_placeholder_columns.reserve(
468
2.00k
                    file_request->non_predicate_columns.size());
469
2.00k
            for (const auto& column : file_request->non_predicate_columns) {
470
1.96k
                file_request->count_star_placeholder_columns.push_back(column.column_id());
471
1.96k
            }
472
2.00k
        }
473
120k
        RETURN_IF_ERROR(customize_file_scan_request(file_request.get()));
474
120k
        RETURN_IF_ERROR(_open_local_filter_exprs(*file_request));
475
120k
        _data_reader.file_block_layout.clear();
476
120k
        _data_reader.block_template.clear();
477
120k
        _file_scan_request.reset();
478
120k
        _data_reader.file_block_layout.resize(file_request->local_positions.size());
479
480
        // 4. Build file block layout from file schema and column mapping. The layout describes
481
        // the block returned by file reader before table-column materialization.
482
531k
        for (const auto& [file_column_id, block_position] : file_request->local_positions) {
483
531k
            DORIS_CHECK(block_position.value() < _data_reader.file_block_layout.size());
484
531k
            const auto* field = _find_column_definition(_data_reader.file_schema, file_column_id);
485
531k
            DORIS_CHECK(field != nullptr);
486
487
531k
            ColumnDefinition projected_field;
488
531k
            {
489
531k
                auto it = std::find_if(
490
531k
                        file_request->non_predicate_columns.begin(),
491
531k
                        file_request->non_predicate_columns.end(),
492
8.98M
                        [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
493
531k
                if (it != file_request->non_predicate_columns.end()) {
494
442k
                    RETURN_IF_ERROR(project_column_definition(*field, *it, &projected_field));
495
442k
                }
496
531k
            }
497
531k
            {
498
531k
                auto it = std::find_if(
499
531k
                        file_request->predicate_columns.begin(),
500
531k
                        file_request->predicate_columns.end(),
501
531k
                        [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
502
531k
                if (it != file_request->predicate_columns.end()) {
503
90.0k
                    RETURN_IF_ERROR(project_column_definition(*field, *it, &projected_field));
504
90.0k
                }
505
531k
            }
506
531k
            _data_reader.file_block_layout[block_position.value()] = {
507
531k
                    .file_column_id = file_column_id,
508
531k
                    .name = projected_field.name,
509
531k
                    .type = projected_field.type,
510
531k
            };
511
531k
            DORIS_CHECK(_data_reader.file_block_layout[block_position.value()].type != nullptr);
512
531k
        }
513
514
        // 5. Prepare block template from file block layout. The block template stores the block
515
        // returned by file reader before table-column materialization.
516
120k
        _data_reader.block_template.reserve(_data_reader.file_block_layout.size());
517
531k
        for (const auto& column : _data_reader.file_block_layout) {
518
531k
            _data_reader.block_template.insert(
519
531k
                    {column.type->create_column(), column.type, column.name});
520
531k
        }
521
120k
        if (VLOG_DEBUG_IS_ON) {
522
0
            VLOG_DEBUG << "TableReader debug: " << debug_string();
523
0
        }
524
120k
        RETURN_IF_ERROR(_open_mapping_exprs());
525
120k
        {
526
120k
            SCOPED_TIMER(_profile.file_reader_total_timer);
527
120k
            SCOPED_TIMER(_profile.file_reader_open_timer);
528
120k
            RETURN_IF_ERROR(_data_reader.reader->open(file_request));
529
120k
        }
530
120k
        _file_scan_request = std::move(file_request);
531
120k
        RETURN_IF_ERROR(_init_reader_condition_cache(*_file_scan_request));
532
120k
        return Status::OK();
533
120k
    }
534
535
    Status _build_table_filters_from_conjuncts();
536
    Status _evaluate_partition_prune_conjuncts(const VExprContextSPtrs& conjuncts,
537
                                               bool* can_filter_all);
538
    static bool _is_safe_to_pre_execute(const VExprContextSPtr& conjunct);
539
    Status _build_partition_prune_block(Block* block) const;
540
    Status _open_local_filter_exprs(const FileScanRequest& file_request);
541
    Status _init_reader_condition_cache(const FileScanRequest& file_request);
542
    void _finalize_reader_condition_cache();
543
    bool _should_enable_condition_cache(const FileScanRequest& file_request) const;
544
545
121k
    Status _evaluate_constant_filters(bool* can_filter_all) {
546
121k
        DORIS_CHECK(can_filter_all != nullptr);
547
121k
        DORIS_CHECK_LE(_constant_pruning_safe_filter_count, _table_filters.size());
548
121k
        *can_filter_all = false;
549
        // The bound was derived from the original `_conjuncts` order, which includes slotless
550
        // expressions omitted from `_table_filters`. Iterating only this prefix therefore cannot
551
        // skip an unsafe row-level predicate and pre-execute a later constant predicate.
552
187k
        for (size_t i = 0; i < _constant_pruning_safe_filter_count; ++i) {
553
67.2k
            const auto& table_filter = _table_filters[i];
554
67.2k
            if (table_filter.conjunct == nullptr) {
555
0
                continue;
556
0
            }
557
67.2k
            DORIS_CHECK(_is_safe_to_pre_execute(table_filter.conjunct));
558
            // RuntimeFilterExpr does not implement execute_column_impl(); it is evaluated by the
559
            // row-level filter path through execute_filter(). Constant split pruning uses
560
            // VExprContext::execute() on a one-row synthetic block, so runtime filters must not be
561
            // pre-executed here even when their referenced slot maps to a constant value.
562
67.2k
            if (table_filter.conjunct->root()->is_rf_wrapper() ||
563
67.2k
                !_table_filter_has_only_constant_entries(table_filter)) {
564
63.4k
                continue;
565
63.4k
            }
566
3.78k
            Block eval_block;
567
3.78k
            RETURN_IF_ERROR(_build_constant_filter_block(table_filter, &eval_block));
568
3.78k
            RowDescriptor row_desc;
569
3.78k
            RETURN_IF_ERROR(table_filter.conjunct->prepare(_runtime_state, row_desc));
570
3.78k
            RETURN_IF_ERROR(table_filter.conjunct->open(_runtime_state));
571
3.78k
            int result_column_id = -1;
572
3.78k
            RETURN_IF_ERROR(table_filter.conjunct->execute(&eval_block, &result_column_id));
573
3.78k
            DORIS_CHECK(result_column_id >= 0);
574
3.78k
            if (_filter_result_filters_all(eval_block.get_by_position(result_column_id).column)) {
575
623
                *can_filter_all = true;
576
623
                return Status::OK();
577
623
            }
578
3.78k
        }
579
120k
        return Status::OK();
580
121k
    }
581
582
61.0k
    bool _table_filter_has_only_constant_entries(const TableFilter& table_filter) const {
583
61.0k
        const auto& filter_entries = _data_reader.column_mapper->filter_entries();
584
61.1k
        for (const auto global_index : table_filter.global_indices) {
585
61.1k
            const auto entry_it = filter_entries.find(global_index);
586
61.4k
            if (entry_it == filter_entries.end() || !entry_it->second.is_constant()) {
587
57.5k
                return false;
588
57.5k
            }
589
61.1k
        }
590
3.55k
        return !table_filter.global_indices.empty();
591
61.0k
    }
592
593
3.79k
    Status _build_constant_filter_block(const TableFilter& table_filter, Block* eval_block) {
594
3.79k
        DORIS_CHECK(eval_block != nullptr);
595
3.79k
        eval_block->clear();
596
3.79k
        const auto& mappings = _data_reader.column_mapper->mappings();
597
3.79k
        const auto& filter_entries = _data_reader.column_mapper->filter_entries();
598
3.79k
        DORIS_CHECK(mappings.size() == _projected_columns.size());
599
15.0k
        for (size_t column_idx = 0; column_idx < mappings.size(); ++column_idx) {
600
11.2k
            const auto global_index = GlobalIndex(column_idx);
601
11.2k
            const auto& mapping = mappings[column_idx];
602
11.2k
            const auto entry_it = filter_entries.find(global_index);
603
11.2k
            const bool referenced_by_filter =
604
11.2k
                    std::find(table_filter.global_indices.begin(),
605
11.2k
                              table_filter.global_indices.end(),
606
11.2k
                              global_index) != table_filter.global_indices.end();
607
11.2k
            if (referenced_by_filter && entry_it != filter_entries.end() &&
608
11.2k
                entry_it->second.is_constant()) {
609
3.85k
                ColumnPtr constant_column;
610
3.85k
                RETURN_IF_ERROR(_materialize_constant_filter_column(
611
3.85k
                        entry_it->second.constant_index(), &constant_column));
612
3.85k
                eval_block->insert({std::move(constant_column), mapping.table_type,
613
3.85k
                                    mapping.table_column_name});
614
7.42k
            } else {
615
7.42k
                eval_block->insert({mapping.table_type->create_column_const_with_default_value(1),
616
7.42k
                                    mapping.table_type, mapping.table_column_name});
617
7.42k
            }
618
11.2k
        }
619
3.79k
        return Status::OK();
620
3.79k
    }
621
622
3.86k
    Status _materialize_constant_filter_column(ConstantIndex constant_index, ColumnPtr* column) {
623
3.86k
        DORIS_CHECK(column != nullptr);
624
3.86k
        const auto& constant_entry = _data_reader.column_mapper->constant_map().get(constant_index);
625
3.86k
        DORIS_CHECK(constant_entry.expr != nullptr);
626
3.86k
        DORIS_CHECK(constant_entry.type != nullptr);
627
3.86k
        RowDescriptor row_desc;
628
3.86k
        RETURN_IF_ERROR(constant_entry.expr->prepare(_runtime_state, row_desc));
629
3.86k
        RETURN_IF_ERROR(constant_entry.expr->open(_runtime_state));
630
3.86k
        Block eval_block;
631
3.86k
        eval_block.insert({constant_entry.type->create_column_const_with_default_value(1),
632
3.86k
                           constant_entry.type, "__table_reader_constant_filter"});
633
3.86k
        int result_column_id = -1;
634
3.86k
        RETURN_IF_ERROR(constant_entry.expr->execute(&eval_block, &result_column_id));
635
3.86k
        DORIS_CHECK(result_column_id >= 0);
636
3.86k
        *column = eval_block.get_by_position(result_column_id).column;
637
3.86k
        DORIS_CHECK((*column)->size() == 1);
638
3.86k
        return Status::OK();
639
3.86k
    }
640
641
3.81k
    static bool _filter_result_filters_all(const ColumnPtr& filter_column) {
642
3.81k
        DORIS_CHECK(filter_column.get() != nullptr);
643
3.81k
        DORIS_CHECK(filter_column->size() == 1);
644
3.81k
        return !filter_column->get_bool(0);
645
3.81k
    }
646
647
120k
    virtual Status customize_file_scan_request(FileScanRequest* file_request) {
648
120k
        return _append_delete_predicate(file_request);
649
120k
    }
650
651
422k
    bool _is_table_level_count_active() const { return _remaining_table_level_count >= 0; }
652
653
242k
    bool _is_file_level_count_active() const { return _remaining_file_level_count >= 0; }
654
655
3.21k
    Status _materialize_count_rows(size_t rows, Block* block) const {
656
3.21k
        DORIS_CHECK(block != nullptr);
657
3.21k
        DORIS_CHECK(block->columns() > 0 || rows == 0);
658
6.42k
        for (size_t column_idx = 0; column_idx < block->columns(); ++column_idx) {
659
3.21k
            auto column = block->get_by_position(column_idx).type->create_column();
660
3.21k
            if (auto* nullable = check_and_get_column<ColumnNullable>(*column)) {
661
                // Metadata COUNT emits synthetic input rows for the unchanged upper aggregate.
662
                // They must be non-NULL for COUNT(nullable_col), and constructing them explicitly
663
                // also keeps every nullable null map boolean-valid in debug/ASAN block checks.
664
3.20k
                nullable->get_nested_column().insert_many_defaults(rows);
665
3.20k
                nullable->get_null_map_data().resize_fill(rows, 0);
666
3.20k
            } else {
667
4
                column->insert_many_defaults(rows);
668
4
            }
669
3.21k
            block->replace_by_position(column_idx, std::move(column));
670
3.21k
        }
671
3.21k
        return Status::OK();
672
3.21k
    }
673
674
3.20k
    Status _materialize_next_count_batch(int64_t* remaining_rows, Block* block) const {
675
3.20k
        DORIS_CHECK(remaining_rows != nullptr);
676
3.20k
        DORIS_CHECK(*remaining_rows > 0);
677
3.20k
        const int64_t batch_size = _runtime_state == nullptr
678
3.20k
                                           ? *remaining_rows
679
3.20k
                                           : static_cast<int64_t>(_runtime_state->batch_size());
680
3.20k
        const auto rows = std::min(*remaining_rows, batch_size);
681
3.20k
        RETURN_IF_ERROR(_materialize_count_rows(cast_set<size_t>(rows), block));
682
3.20k
        *remaining_rows -= rows;
683
3.20k
        return Status::OK();
684
3.20k
    }
685
686
3.42k
    Status _read_count_batch(int64_t* remaining_rows, Block* block, bool* eos) {
687
3.42k
        DORIS_CHECK(block != nullptr);
688
3.42k
        DORIS_CHECK(eos != nullptr);
689
3.42k
        DORIS_CHECK(_push_down_agg_type == TPushAggOp::type::COUNT);
690
3.42k
        DORIS_CHECK(remaining_rows != nullptr);
691
3.42k
        DORIS_CHECK(*remaining_rows >= 0);
692
3.42k
        if (*remaining_rows == 0) {
693
1.72k
            *remaining_rows = -1;
694
1.72k
            _current_task.reset();
695
1.72k
            *eos = true;
696
1.72k
            return Status::OK();
697
1.72k
        }
698
1.69k
        RETURN_IF_ERROR(_materialize_next_count_batch(remaining_rows, block));
699
1.69k
        *eos = false;
700
1.69k
        return Status::OK();
701
1.69k
    }
702
703
458
    Status _read_table_level_count(Block* block, bool* eos) {
704
458
        return _read_count_batch(&_remaining_table_level_count, block, eos);
705
458
    }
706
707
2.97k
    Status _read_file_level_count(Block* block, bool* eos) {
708
2.97k
        return _read_count_batch(&_remaining_file_level_count, block, eos);
709
2.97k
    }
710
711
    void _append_file_scan_column(FileScanRequest* request, LocalColumnId column_id,
712
34.8k
                                  std::vector<LocalColumnIndex>* scan_columns) {
713
34.8k
        DORIS_CHECK(request != nullptr);
714
34.8k
        DORIS_CHECK(scan_columns != nullptr);
715
34.8k
        FileScanRequestBuilder builder(request);
716
34.8k
        Status status;
717
34.8k
        if (scan_columns == &request->predicate_columns) {
718
32.6k
            status = builder.add_predicate_column(column_id);
719
32.6k
        } else {
720
2.21k
            DORIS_CHECK(scan_columns == &request->non_predicate_columns);
721
2.21k
            status = builder.add_non_predicate_column(column_id);
722
2.21k
        }
723
34.8k
        DORIS_CHECK(status.ok()) << status.to_string();
724
34.8k
        if (column_id == LocalColumnId(ROW_POSITION_COLUMN_ID) &&
725
34.8k
            _find_column_definition(_data_reader.file_schema, column_id) == nullptr) {
726
29.3k
            _data_reader.file_schema.push_back(row_position_column_definition());
727
29.3k
        }
728
34.8k
    }
729
730
    // Append DeletePredicate to file scan request if there are deletes. The predicate will be evaluated in file reader level and filter out deleted rows before returning data to table reader.
731
119k
    Status _append_delete_predicate(FileScanRequest* request) {
732
119k
        DORIS_CHECK(request != nullptr);
733
119k
        if ((_delete_rows == nullptr || _delete_rows->empty()) &&
734
119k
            (_deletion_vector == nullptr || _deletion_vector->isEmpty())) {
735
92.5k
            return Status::OK();
736
92.5k
        }
737
27.3k
        const auto row_position_column_id = LocalColumnId(ROW_POSITION_COLUMN_ID);
738
27.3k
        _append_file_scan_column(request, row_position_column_id, &request->predicate_columns);
739
740
27.3k
        const auto block_position = request->local_positions.at(row_position_column_id);
741
27.5k
        auto append_predicate = [&](auto& deleted_rows) {
742
27.5k
            auto delete_predicate = std::make_shared<DeletePredicate>(deleted_rows);
743
27.5k
            delete_predicate->add_child(VSlotRef::create_shared(
744
27.5k
                    cast_set<int>(block_position.value()), cast_set<int>(block_position.value()),
745
27.5k
                    -1, std::make_shared<DataTypeInt64>(), ROW_POSITION_COLUMN_NAME));
746
27.5k
            request->delete_conjuncts.push_back(
747
27.5k
                    VExprContext::create_shared(std::move(delete_predicate)));
748
27.5k
        };
_ZZN5doris6format11TableReader24_append_delete_predicateEPNS0_15FileScanRequestEENKUlRT_E_clISt6vectorIlSaIlEEEEDaS5_
Line
Count
Source
741
1.81k
        auto append_predicate = [&](auto& deleted_rows) {
742
1.81k
            auto delete_predicate = std::make_shared<DeletePredicate>(deleted_rows);
743
1.81k
            delete_predicate->add_child(VSlotRef::create_shared(
744
1.81k
                    cast_set<int>(block_position.value()), cast_set<int>(block_position.value()),
745
1.81k
                    -1, std::make_shared<DataTypeInt64>(), ROW_POSITION_COLUMN_NAME));
746
1.81k
            request->delete_conjuncts.push_back(
747
1.81k
                    VExprContext::create_shared(std::move(delete_predicate)));
748
1.81k
        };
_ZZN5doris6format11TableReader24_append_delete_predicateEPNS0_15FileScanRequestEENKUlRT_E_clIN7roaring12Roaring64MapEEEDaS5_
Line
Count
Source
741
25.7k
        auto append_predicate = [&](auto& deleted_rows) {
742
25.7k
            auto delete_predicate = std::make_shared<DeletePredicate>(deleted_rows);
743
25.7k
            delete_predicate->add_child(VSlotRef::create_shared(
744
25.7k
                    cast_set<int>(block_position.value()), cast_set<int>(block_position.value()),
745
25.7k
                    -1, std::make_shared<DataTypeInt64>(), ROW_POSITION_COLUMN_NAME));
746
25.7k
            request->delete_conjuncts.push_back(
747
25.7k
                    VExprContext::create_shared(std::move(delete_predicate)));
748
25.7k
        };
749
27.3k
        if (_delete_rows != nullptr && !_delete_rows->empty()) {
750
1.81k
            append_predicate(*_delete_rows);
751
1.81k
        }
752
27.3k
        if (_deletion_vector != nullptr && !_deletion_vector->isEmpty()) {
753
25.8k
            append_predicate(*_deletion_vector);
754
25.8k
        }
755
27.3k
        return Status::OK();
756
119k
    }
757
758
    // Close the current concrete reader. This hook is called by both create_next_reader() and
759
    // close(), so it should remain idempotent.
760
121k
    virtual Status close_current_reader() {
761
121k
        _finalize_reader_condition_cache();
762
121k
        {
763
121k
            SCOPED_TIMER(_profile.file_reader_total_timer);
764
121k
            SCOPED_TIMER(_profile.file_reader_close_timer);
765
121k
            RETURN_IF_ERROR(_data_reader.reader->close());
766
121k
        }
767
121k
        _data_reader.reader.reset();
768
121k
        if (_data_reader.column_mapper != nullptr) {
769
120k
            _data_reader.column_mapper->clear();
770
120k
            _data_reader.column_mapper.reset();
771
120k
        }
772
121k
        _table_filters.clear();
773
121k
        _constant_pruning_safe_filter_count = 0;
774
121k
        _data_reader.file_schema.clear();
775
121k
        _data_reader.file_block_layout.clear();
776
121k
        _data_reader.block_template.clear();
777
121k
        _file_scan_request.reset();
778
121k
        _current_task.reset();
779
121k
        _current_file_description.reset();
780
121k
        _current_reader_reached_eof = false;
781
121k
        return Status::OK();
782
121k
    }
783
784
7.13k
    void _record_scan_rows(size_t rows) {
785
7.13k
        if (_io_ctx != nullptr && _io_ctx->file_reader_stats != nullptr) {
786
7.13k
            _io_ctx->file_reader_stats->read_rows += rows;
787
7.13k
        }
788
7.13k
    }
789
790
    // Finalize file-local block to table/global schema block.
791
109k
    Status finalize_chunk(Block* block, const size_t rows) {
792
109k
        SCOPED_TIMER(_profile.finalize_timer);
793
109k
        size_t idx = 0;
794
109k
        const auto& mappings = _data_reader.column_mapper->mappings();
795
589k
        for (const auto& mapping : mappings) {
796
589k
            ColumnPtr column;
797
589k
            RETURN_IF_ERROR(_materialize_mapping_column(mapping, &_data_reader.block_template, rows,
798
589k
                                                        &column, idx + 1 == mappings.size()));
799
589k
            block->replace_by_position(idx, IColumn::mutate(std::move(column)));
800
589k
            idx++;
801
589k
        }
802
109k
        RETURN_IF_ERROR(materialize_virtual_columns(block));
803
        // Enforce CHAR/VARCHAR length declared by the table schema after all file-to-table
804
        // materialization has finished.
805
109k
        RETURN_IF_ERROR(_truncate_char_or_varchar_columns(block));
806
109k
        return Status::OK();
807
109k
    }
808
809
    // Materialize virtual columns in the table block, such as Iceberg _row_id and
810
    // _last_updated_sequence_number. This runs after normal column materialization so finalize
811
    // expressions can reference those virtual columns.
812
79.0k
    virtual Status materialize_virtual_columns(Block* table_block) { return Status::OK(); }
813
814
#ifndef NDEBUG
815
109k
    Status _check_file_block_columns(std::string_view stage, size_t rows) {
816
109k
        DORIS_CHECK(_data_reader.block_template.columns() == _data_reader.file_block_layout.size());
817
682k
        for (size_t idx = 0; idx < _data_reader.block_template.columns(); ++idx) {
818
573k
            const auto& file_block_column = _data_reader.file_block_layout[idx];
819
573k
            const auto& column_with_type = _data_reader.block_template.get_by_position(idx);
820
573k
            const auto* column = column_with_type.column.get();
821
573k
            try {
822
573k
                if (column == nullptr) {
823
0
                    auto st = Status::InternalError(
824
0
                            "Invalid file block column {} at {}: file_column_id={}, name='{}', "
825
0
                            "type={}, column=null, expected_rows={}, reader={}",
826
0
                            idx, stage, file_block_column.file_column_id.value(),
827
0
                            file_block_column.name,
828
0
                            file_block_column.type == nullptr ? "null"
829
0
                                                              : file_block_column.type->get_name(),
830
0
                            rows, debug_string());
831
0
                    LOG(WARNING) << st;
832
0
                    return st;
833
0
                }
834
573k
                column->sanity_check();
835
573k
                auto st = column_with_type.check_type_and_column_match();
836
573k
                if (!st.ok()) {
837
0
                    auto contextual_status = Status::InternalError(
838
0
                            "Invalid file block column {} at {}: file_column_id={}, name='{}', "
839
0
                            "type={}, column={}, column_size={}, expected_rows={}, error={}, "
840
0
                            "reader={}",
841
0
                            idx, stage, file_block_column.file_column_id.value(),
842
0
                            file_block_column.name,
843
0
                            file_block_column.type == nullptr ? "null"
844
0
                                                              : file_block_column.type->get_name(),
845
0
                            column->get_name(), column->size(), rows, st.to_string(),
846
0
                            debug_string());
847
0
                    LOG(WARNING) << contextual_status;
848
0
                    return contextual_status;
849
0
                }
850
573k
            } catch (const Exception& e) {
851
0
                auto st = Status::InternalError(
852
0
                        "Invalid file block column {} at {}: file_column_id={}, name='{}', "
853
0
                        "type={}, column={}, column_size={}, expected_rows={}, error={}, "
854
0
                        "reader={}",
855
0
                        idx, stage, file_block_column.file_column_id.value(),
856
0
                        file_block_column.name,
857
0
                        file_block_column.type == nullptr ? "null"
858
0
                                                          : file_block_column.type->get_name(),
859
0
                        column == nullptr ? "null" : column->get_name(),
860
0
                        column == nullptr ? 0 : column->size(), rows, e.to_string(),
861
0
                        debug_string());
862
0
                LOG(WARNING) << st;
863
0
                return st;
864
0
            } catch (const std::exception& e) {
865
0
                auto st = Status::InternalError(
866
0
                        "Invalid file block column {} at {}: file_column_id={}, name='{}', "
867
0
                        "type={}, column={}, column_size={}, expected_rows={}, error={}, "
868
0
                        "reader={}",
869
0
                        idx, stage, file_block_column.file_column_id.value(),
870
0
                        file_block_column.name,
871
0
                        file_block_column.type == nullptr ? "null"
872
0
                                                          : file_block_column.type->get_name(),
873
0
                        column == nullptr ? "null" : column->get_name(),
874
0
                        column == nullptr ? 0 : column->size(), rows, e.what(), debug_string());
875
0
                LOG(WARNING) << st;
876
0
                return st;
877
0
            }
878
573k
        }
879
109k
        return Status::OK();
880
109k
    }
881
882
109k
    Status _check_table_block_columns(std::string_view stage, const Block* block, size_t rows) {
883
109k
        DORIS_CHECK(block != nullptr);
884
109k
        DORIS_CHECK(block->columns() == _data_reader.column_mapper->mappings().size());
885
698k
        for (size_t idx = 0; idx < block->columns(); ++idx) {
886
588k
            const auto& mapping = _data_reader.column_mapper->mappings()[idx];
887
588k
            const auto& column_with_type = block->get_by_position(idx);
888
588k
            const auto* column = column_with_type.column.get();
889
588k
            try {
890
588k
                if (column == nullptr) {
891
0
                    auto st = Status::InternalError(
892
0
                            "Invalid table block column {} at {}: table_column='{}', "
893
0
                            "global_index={}, type={}, column=null, expected_rows={}, mapping={}",
894
0
                            idx, stage, mapping.table_column_name, mapping.global_index.value(),
895
0
                            mapping.table_type == nullptr ? "null" : mapping.table_type->get_name(),
896
0
                            rows, mapping.debug_string());
897
0
                    LOG(WARNING) << st;
898
0
                    return st;
899
0
                }
900
588k
                column->sanity_check();
901
588k
                auto st = column_with_type.check_type_and_column_match();
902
588k
                if (!st.ok()) {
903
0
                    auto contextual_status = Status::InternalError(
904
0
                            "Invalid table block column {} at {}: table_column='{}', "
905
0
                            "global_index={}, type={}, column={}, column_size={}, "
906
0
                            "expected_rows={}, error={}, mapping={}",
907
0
                            idx, stage, mapping.table_column_name, mapping.global_index.value(),
908
0
                            mapping.table_type == nullptr ? "null" : mapping.table_type->get_name(),
909
0
                            column->get_name(), column->size(), rows, st.to_string(),
910
0
                            mapping.debug_string());
911
0
                    LOG(WARNING) << contextual_status;
912
0
                    return contextual_status;
913
0
                }
914
588k
            } catch (const Exception& e) {
915
0
                auto st = Status::InternalError(
916
0
                        "Invalid table block column {} at {}: table_column='{}', global_index={}, "
917
0
                        "type={}, column={}, column_size={}, expected_rows={}, error={}, "
918
0
                        "mapping={}",
919
0
                        idx, stage, mapping.table_column_name, mapping.global_index.value(),
920
0
                        mapping.table_type == nullptr ? "null" : mapping.table_type->get_name(),
921
0
                        column == nullptr ? "null" : column->get_name(),
922
0
                        column == nullptr ? 0 : column->size(), rows, e.to_string(),
923
0
                        mapping.debug_string());
924
0
                LOG(WARNING) << st;
925
0
                return st;
926
0
            } catch (const std::exception& e) {
927
0
                auto st = Status::InternalError(
928
0
                        "Invalid table block column {} at {}: table_column='{}', global_index={}, "
929
0
                        "type={}, column={}, column_size={}, expected_rows={}, error={}, "
930
0
                        "mapping={}",
931
0
                        idx, stage, mapping.table_column_name, mapping.global_index.value(),
932
0
                        mapping.table_type == nullptr ? "null" : mapping.table_type->get_name(),
933
0
                        column == nullptr ? "null" : column->get_name(),
934
0
                        column == nullptr ? 0 : column->size(), rows, e.what(),
935
0
                        mapping.debug_string());
936
0
                LOG(WARNING) << st;
937
0
                return st;
938
0
            }
939
588k
        }
940
109k
        return Status::OK();
941
109k
    }
942
#endif
943
944
109k
    Status _truncate_char_or_varchar_columns(Block* block) {
945
109k
        DORIS_CHECK(block != nullptr);
946
109k
        if (_runtime_state == nullptr ||
947
109k
            !_runtime_state->query_options().truncate_char_or_varchar_columns) {
948
109k
            return Status::OK();
949
109k
        }
950
6
        DORIS_CHECK(block->columns() == _data_reader.column_mapper->mappings().size());
951
42
        for (size_t idx = 0; idx < _data_reader.column_mapper->mappings().size(); ++idx) {
952
36
            const auto& mapping = _data_reader.column_mapper->mappings()[idx];
953
36
            if (!_should_truncate_char_or_varchar_column(mapping)) {
954
12
                continue;
955
12
            }
956
24
            const auto target_len =
957
24
                    assert_cast<const DataTypeString*>(remove_nullable(mapping.table_type).get())
958
24
                            ->len();
959
24
            _truncate_char_or_varchar_column(block, idx, target_len);
960
24
        }
961
6
        return Status::OK();
962
109k
    }
963
964
    // Return true when the table schema has a bounded CHAR/VARCHAR length that is stricter than
965
    // the file-side type. Examples:
966
    // - table VARCHAR(10), file VARCHAR(20): truncate to 10;
967
    // - table VARCHAR(10), file STRING: truncate to 10 because STRING has no declared bound;
968
    // - table STRING, any file type: no truncation because the target has no bound.
969
41
    static bool _should_truncate_char_or_varchar_column(const ColumnMapping& mapping) {
970
41
        if (mapping.table_type == nullptr) {
971
0
            return false;
972
0
        }
973
41
        const auto table_type = remove_nullable(mapping.table_type);
974
41
        const auto primitive_type = table_type->get_primitive_type();
975
41
        if (primitive_type != TYPE_VARCHAR && primitive_type != TYPE_CHAR) {
976
13
            return false;
977
13
        }
978
28
        const auto target_len = assert_cast<const DataTypeString*>(table_type.get())->len();
979
28
        if (target_len <= 0) {
980
0
            return false;
981
0
        }
982
28
        if (mapping.file_type == nullptr) {
983
0
            return true;
984
0
        }
985
28
        const auto file_type = remove_nullable(mapping.file_type);
986
28
        DORIS_CHECK(file_type != nullptr);
987
28
        int file_len = -1;
988
28
        if (file_type->get_primitive_type() == TYPE_VARCHAR ||
989
28
            file_type->get_primitive_type() == TYPE_CHAR ||
990
28
            file_type->get_primitive_type() == TYPE_STRING) {
991
27
            file_len = assert_cast<const DataTypeString*>(file_type.get())->len();
992
27
        }
993
994
28
        return file_len < 0 || target_len < file_len;
995
28
    }
996
997
    // Truncate a materialized CHAR/VARCHAR column in place by reusing the vectorized substring
998
    // implementation: substring(column, 1, len). Nullable columns are unwrapped before substring
999
    // execution and wrapped back with the original null map afterward, because substring operates
1000
    // on the nested string payload only.
1001
25
    static void _truncate_char_or_varchar_column(Block* block, size_t idx, int len) {
1002
25
        DORIS_CHECK(block != nullptr);
1003
25
        auto int_type = std::make_shared<DataTypeInt32>();
1004
25
        const auto num_columns_without_result = cast_set<uint32_t>(block->columns());
1005
25
        auto& target = block->get_by_position(idx);
1006
25
        const bool is_nullable = target.type->is_nullable();
1007
25
        ColumnPtr input_column = target.column;
1008
25
        ColumnPtr null_map_column;
1009
25
        if (is_nullable) {
1010
25
            const auto* nullable_column = assert_cast<const ColumnNullable*>(target.column.get());
1011
25
            input_column = nullable_column->get_nested_column_ptr();
1012
25
            null_map_column = nullable_column->get_null_map_column_ptr();
1013
25
        }
1014
25
        block->replace_by_position(idx, std::move(input_column));
1015
25
        block->insert({int_type->create_column_const(block->rows(), to_field<TYPE_INT>(1)),
1016
25
                       int_type, "const 1"});
1017
25
        block->insert({int_type->create_column_const(block->rows(), to_field<TYPE_INT>(len)),
1018
25
                       int_type, "const len"});
1019
25
        block->insert({nullptr, std::make_shared<DataTypeString>(), "result"});
1020
1021
25
        ColumnNumbers temp_arguments(3);
1022
25
        temp_arguments[0] = cast_set<uint32_t>(idx);
1023
25
        temp_arguments[1] = num_columns_without_result;
1024
25
        temp_arguments[2] = num_columns_without_result + 1;
1025
25
        const uint32_t result_column_id = num_columns_without_result + 2;
1026
25
        SubstringUtil::substring_execute(*block, temp_arguments, result_column_id, block->rows());
1027
1028
25
        ColumnPtr result_column = block->get_by_position(result_column_id).column;
1029
25
        if (is_nullable) {
1030
25
            result_column = ColumnNullable::create(std::move(result_column), null_map_column);
1031
25
        }
1032
25
        block->replace_by_position(idx, std::move(result_column));
1033
25
        block->erase_tail(num_columns_without_result);
1034
25
    }
1035
1036
120k
    Status _try_materialize_aggregate_pushdown_rows(Block* block, bool* pushed_down) {
1037
120k
        DORIS_CHECK(block != nullptr);
1038
120k
        DORIS_CHECK(pushed_down != nullptr);
1039
120k
        *pushed_down = false;
1040
120k
        block->clear_column_data(_projected_columns.size());
1041
120k
        _aggregate_pushdown_tried = true;
1042
120k
        if (!_supports_aggregate_pushdown(_push_down_agg_type)) {
1043
119k
            return Status::OK();
1044
119k
        }
1045
1046
1.13k
        FileAggregateRequest file_request;
1047
1.13k
        RETURN_IF_ERROR(_build_file_aggregate_request(_push_down_agg_type, &file_request));
1048
1.13k
        FileAggregateResult file_result;
1049
1.13k
        Status status;
1050
1.13k
        {
1051
1.13k
            SCOPED_TIMER(_profile.file_reader_total_timer);
1052
1.13k
            SCOPED_TIMER(_profile.file_reader_aggregate_timer);
1053
1.13k
            status = _data_reader.reader->get_aggregate_result(file_request, &file_result);
1054
1.13k
        }
1055
1.13k
        if (status.is<ErrorCode::NOT_IMPLEMENTED_ERROR>()) {
1056
13
            return Status::OK();
1057
13
        }
1058
1.12k
        RETURN_IF_ERROR(status);
1059
1.51k
        if (_push_down_agg_type == TPushAggOp::type::COUNT) {
1060
1.51k
            DORIS_CHECK(file_result.count >= 0);
1061
            // The upper aggregate consumes synthetic input rows, but emitting the whole metadata
1062
            // count in one block bypasses the runtime batch contract and can allocate by file size.
1063
            // Keep the remaining cardinality as split state and expose at most one batch per call.
1064
1.51k
            _remaining_file_level_count = file_result.count;
1065
1.51k
            _current_split_uses_metadata_count = true;
1066
1.51k
            if (_remaining_file_level_count > 0) {
1067
1.51k
                RETURN_IF_ERROR(_materialize_next_count_batch(&_remaining_file_level_count, block));
1068
1.51k
            }
1069
18.4E
        } else {
1070
18.4E
            RETURN_IF_ERROR(
1071
18.4E
                    _materialize_aggregate_pushdown_rows(_push_down_agg_type, file_result, block));
1072
18.4E
        }
1073
1.12k
        *pushed_down = true;
1074
1.12k
        RETURN_IF_ERROR(close_current_reader());
1075
1.12k
        return Status::OK();
1076
1.12k
    }
1077
1078
121k
    virtual bool _supports_aggregate_pushdown(TPushAggOp::type agg_type) const {
1079
        // Only COUNT and MIN/MAX can be push down.
1080
121k
        if (agg_type != TPushAggOp::type::COUNT && agg_type != TPushAggOp::type::MINMAX) {
1081
117k
            return false;
1082
117k
        }
1083
        // Aggregate pushdown returns reduced synthetic rows and may close the physical reader
1084
        // before the next scheduler turn. If a runtime filter is still pending, those rows could
1085
        // escape before the filter arrives and cannot later be reconstructed from real file rows.
1086
        // This is the same irreversibility constraint as table-level metadata COUNT, and applies
1087
        // to COUNT and MIN/MAX for Parquet/ORC as well as COUNT for text readers.
1088
4.22k
        if (!_all_runtime_filters_applied_for_split) {
1089
3
            return false;
1090
3
        }
1091
        // Scanner owns the original conjunct list and evaluates it after TableReader finalizes
1092
        // rows. Even a slotless conjunct that cannot become a TableFilter must see every source
1093
        // row before an aggregate reduces the stream to synthetic COUNT/MINMAX rows.
1094
4.22k
        if (!_conjuncts.empty()) {
1095
5
            return false;
1096
5
        }
1097
        // Only support aggregate pushdown when there is no delete or filter, so
1098
        // the reduced rows consumed by the upper aggregate remain semantically equivalent to a
1099
        // normal scan.
1100
4.22k
        if ((_delete_rows != nullptr && !_delete_rows->empty()) ||
1101
4.56k
            (_deletion_vector != nullptr && !_deletion_vector->isEmpty())) {
1102
1.09k
            return false;
1103
1.09k
        }
1104
3.12k
        if (!_table_filters.empty()) {
1105
0
            return false;
1106
0
        }
1107
3.49k
        if (agg_type == TPushAggOp::type::COUNT) {
1108
            // Old FEs do not serialize push_down_count_slot_ids. During the supported BE-first
1109
            // rolling upgrade, nullopt therefore means "COUNT semantics are unknown", not
1110
            // COUNT(*). Fall back to reading rows until the FE explicitly sends either an empty
1111
            // list for COUNT(*) or one slot for COUNT(col).
1112
3.49k
            if (!_push_down_count_columns.has_value()) {
1113
3
                return false;
1114
3
            }
1115
            // COUNT(*) needs no column metadata. COUNT(col) currently supports one direct file
1116
            // column; multiple COUNT arguments fall back to the normal scan so every upper
1117
            // aggregate receives the original rows.
1118
3.48k
            if (_push_down_count_columns->empty()) {
1119
2.66k
                return true;
1120
2.66k
            }
1121
825
            if (_push_down_count_columns->size() != 1) {
1122
37
                return false;
1123
37
            }
1124
788
            const auto& mapping = _push_down_count_mapping();
1125
            // Metadata COUNT skips TableReader's normal materialization path. Only a trivial
1126
            // mapping is safe: for example, a nullable Parquet INT mapped to a NOT NULL table
1127
            // BIGINT normally needs both an INT->BIGINT cast and nullability validation. Counting
1128
            // footer values directly would bypass both operations and could hide invalid data.
1129
788
            return mapping.file_local_id.has_value() && mapping.file_type != nullptr &&
1130
788
                   mapping.table_type != nullptr && mapping.is_trivial &&
1131
788
                   mapping.virtual_column_type == TableVirtualColumnType::INVALID &&
1132
788
                   mapping.default_expr == nullptr;
1133
825
        }
1134
        // For MIN/MAX, only support direct file-to-table column mappings. The two emitted rows
1135
        // must be enough for the upper MIN/MAX aggregate without evaluating default expressions or
1136
        // virtual columns.
1137
18.4E
        for (const auto& mapping : _data_reader.column_mapper->mappings()) {
1138
149
            if (!mapping.file_local_id.has_value() ||
1139
149
                mapping.virtual_column_type != TableVirtualColumnType::INVALID ||
1140
149
                mapping.default_expr != nullptr || mapping.file_type == nullptr ||
1141
149
                mapping.table_type == nullptr) {
1142
9
                return false;
1143
9
            }
1144
140
            if (!_can_push_down_minmax_for_mapping(mapping)) {
1145
46
                return false;
1146
46
            }
1147
140
        }
1148
18.4E
        return true;
1149
18.4E
    }
1150
1151
579k
    static ColumnPtr _detach_column(ColumnPtr column) {
1152
579k
        DORIS_CHECK(column.get() != nullptr);
1153
579k
        return IColumn::mutate(std::move(column));
1154
579k
    }
1155
1156
95.0k
    static ColumnPtr _take_and_detach_block_column(Block* block, int position) {
1157
95.0k
        DORIS_CHECK(block != nullptr);
1158
95.0k
        DORIS_CHECK(position >= 0 && position < static_cast<int>(block->columns()));
1159
95.0k
        auto& source = block->get_by_position(position);
1160
95.0k
        ColumnPtr column = source.column;
1161
        // The final mapping no longer needs the file block. Release its COW owner before mutate(),
1162
        // otherwise nested MAP/STRING columns are deep-copied and a multi-GB payload can OOM.
1163
95.0k
        block->replace_by_position(position, source.type->create_column());
1164
95.0k
        return _detach_column(std::move(column));
1165
95.0k
    }
1166
1167
    static Status _align_column_nullability(ColumnPtr* column, const DataTypePtr& table_type,
1168
131k
                                            const NullMap* nullable_parent_null_map = nullptr) {
1169
131k
        DORIS_CHECK(column != nullptr);
1170
131k
        DORIS_CHECK(column->get() != nullptr);
1171
131k
        DORIS_CHECK(table_type != nullptr);
1172
        // Must return non-const column
1173
131k
        *column = (*column)->convert_to_full_column_if_const();
1174
131k
        if (table_type->is_nullable()) {
1175
65.8k
            const auto& nested_type =
1176
65.8k
                    assert_cast<const DataTypeNullable&>(*table_type).get_nested_type();
1177
65.8k
            if (!(*column)->is_nullable()) {
1178
2
                RETURN_IF_ERROR(
1179
2
                        _align_column_nullability(column, nested_type, nullable_parent_null_map));
1180
2
                *column = make_nullable(*column);
1181
2
                return Status::OK();
1182
2
            }
1183
65.8k
            const auto& nullable_column = assert_cast<const ColumnNullable&>(**column);
1184
65.8k
            ColumnPtr nested_column = nullable_column.get_nested_column_ptr();
1185
65.8k
            NullMap combined_null_map;
1186
65.8k
            const NullMap* nested_parent_null_map = &nullable_column.get_null_map_data();
1187
65.8k
            if (nullable_parent_null_map != nullptr) {
1188
32.2k
                const auto& own_null_map = nullable_column.get_null_map_data();
1189
32.2k
                DORIS_CHECK(nullable_parent_null_map->size() == own_null_map.size());
1190
                // Required descendants are hidden when either this nullable container or any
1191
                // inherited nullable ancestor masks the row, so preserve the union recursively.
1192
32.2k
                combined_null_map.resize(own_null_map.size());
1193
352k
                for (size_t i = 0; i < own_null_map.size(); ++i) {
1194
320k
                    combined_null_map[i] = own_null_map[i] || (*nullable_parent_null_map)[i];
1195
320k
                }
1196
32.2k
                nested_parent_null_map = &combined_null_map;
1197
32.2k
            }
1198
65.8k
            RETURN_IF_ERROR(
1199
65.8k
                    _align_column_nullability(&nested_column, nested_type, nested_parent_null_map));
1200
65.8k
            *column = ColumnNullable::create(nested_column,
1201
65.8k
                                             nullable_column.get_null_map_column_ptr());
1202
65.8k
            return Status::OK();
1203
65.8k
        }
1204
65.9k
        if ((*column)->is_nullable()) {
1205
16
            const auto& nullable_column = assert_cast<const ColumnNullable&>(**column);
1206
16
            if (nullable_column.has_null()) {
1207
6
                const auto& null_map = nullable_column.get_null_map_data();
1208
6
                if (nullable_parent_null_map == nullptr ||
1209
6
                    nullable_parent_null_map->size() != null_map.size()) {
1210
0
                    return Status::InternalError(
1211
0
                            "Default expression produced NULL for non-nullable table column");
1212
0
                }
1213
17
                for (size_t i = 0; i < null_map.size(); ++i) {
1214
                    // A required child may contain a physical NULL placeholder only when its
1215
                    // nullable parent masks that row from the logical value.
1216
12
                    if (null_map[i] && !(*nullable_parent_null_map)[i]) {
1217
1
                        return Status::InternalError(
1218
1
                                "Default expression produced NULL for non-nullable table column");
1219
1
                    }
1220
12
                }
1221
6
            }
1222
15
            ColumnPtr nested_column = nullable_column.get_nested_column_ptr();
1223
15
            RETURN_IF_ERROR(_align_column_nullability(&nested_column, table_type,
1224
15
                                                      nullable_parent_null_map));
1225
15
            *column = nested_column;
1226
15
            return Status::OK();
1227
15
        }
1228
65.9k
        if (const auto* array_type = typeid_cast<const DataTypeArray*>(table_type.get())) {
1229
213
            const auto& array_column = assert_cast<const ColumnArray&>(**column);
1230
213
            ColumnPtr nested_column = array_column.get_data_ptr();
1231
213
            RETURN_IF_ERROR(
1232
213
                    _align_column_nullability(&nested_column, array_type->get_nested_type()));
1233
213
            *column = ColumnArray::create(nested_column, array_column.get_offsets_ptr());
1234
213
            return Status::OK();
1235
213
        }
1236
65.7k
        if (const auto* map_type = typeid_cast<const DataTypeMap*>(table_type.get())) {
1237
165
            const auto& map_column = assert_cast<const ColumnMap&>(**column);
1238
165
            ColumnPtr key_column = map_column.get_keys_ptr();
1239
165
            ColumnPtr value_column = map_column.get_values_ptr();
1240
165
            RETURN_IF_ERROR(_align_column_nullability(&key_column, map_type->get_key_type()));
1241
165
            RETURN_IF_ERROR(_align_column_nullability(&value_column, map_type->get_value_type()));
1242
165
            *column = ColumnMap::create(key_column, value_column, map_column.get_offsets_ptr());
1243
165
            return Status::OK();
1244
165
        }
1245
65.5k
        if (const auto* struct_type = typeid_cast<const DataTypeStruct*>(table_type.get())) {
1246
8.00k
            const auto& struct_column = assert_cast<const ColumnStruct&>(**column);
1247
8.00k
            Columns columns = struct_column.get_columns_copy();
1248
8.00k
            DORIS_CHECK(columns.size() == struct_type->get_elements().size());
1249
26.8k
            for (size_t i = 0; i < columns.size(); ++i) {
1250
18.8k
                RETURN_IF_ERROR(_align_column_nullability(&columns[i], struct_type->get_element(i),
1251
18.8k
                                                          nullable_parent_null_map));
1252
18.8k
            }
1253
8.00k
            *column = ColumnStruct::create(columns);
1254
8.00k
            return Status::OK();
1255
8.00k
        }
1256
57.5k
        return Status::OK();
1257
65.5k
    }
1258
1259
    static Status _execute_default_expr_without_root_type_check(
1260
            const VExprContextSPtr& default_expr, const Block* block,
1261
21.0k
            ColumnWithTypeAndName* result_data) {
1262
21.0k
        DORIS_CHECK(default_expr != nullptr);
1263
21.0k
        DORIS_CHECK(block != nullptr);
1264
21.0k
        DORIS_CHECK(result_data != nullptr);
1265
21.0k
        ColumnPtr result_column;
1266
21.0k
        Status st;
1267
21.0k
        RETURN_IF_CATCH_EXCEPTION({
1268
21.0k
            st = default_expr->root()->execute_column_impl(default_expr.get(), block, nullptr,
1269
21.0k
                                                           block->rows(), result_column);
1270
21.0k
        });
1271
21.0k
        RETURN_IF_ERROR(st);
1272
21.0k
        DORIS_CHECK(result_column.get() != nullptr);
1273
21.0k
        if (result_column->size() != block->rows()) {
1274
0
            return Status::InternalError(
1275
0
                    "Default expr {} return column size {} not equal to expected size {}",
1276
0
                    default_expr->expr_name(), result_column->size(), block->rows());
1277
0
        }
1278
21.0k
        result_data->column = result_column;
1279
21.0k
        result_data->type = default_expr->execute_type(block);
1280
21.0k
        result_data->name = default_expr->expr_name();
1281
21.0k
        return Status::OK();
1282
21.0k
    }
1283
1284
    Status _cast_column_to_type(ColumnPtr* column, const DataTypePtr& file_type,
1285
                                const DataTypePtr& table_type,
1286
9.55k
                                const std::string& column_name) const {
1287
9.55k
        DORIS_CHECK(column != nullptr);
1288
9.55k
        DORIS_CHECK(column->get() != nullptr);
1289
9.55k
        DORIS_CHECK(file_type != nullptr);
1290
9.55k
        DORIS_CHECK(table_type != nullptr);
1291
9.55k
        if (file_type->equals(*table_type)) {
1292
0
            return Status::OK();
1293
0
        }
1294
1295
9.55k
        DataTypePtr input_type = file_type;
1296
        // Cast wrappers unwrap nullable inputs according to the declared input type, so keep the
1297
        // root nullability of the declared type aligned with the actual column shape.
1298
9.55k
        if ((*column)->is_nullable() && !input_type->is_nullable()) {
1299
0
            input_type = make_nullable(input_type);
1300
9.55k
        } else if (!(*column)->is_nullable() && input_type->is_nullable()) {
1301
1
            input_type = remove_nullable(input_type);
1302
1
        }
1303
9.55k
        Block cast_block;
1304
9.55k
        cast_block.insert({*column, input_type, column_name});
1305
9.55k
        auto slot_ref = VSlotRef::create_shared(0, 0, -1, input_type, column_name);
1306
        // Preserve the source null map through conversion; the caller validates and unwraps it
1307
        // against a required table field after the value conversion finishes.
1308
9.55k
        const auto cast_target_type = input_type->is_nullable() && !table_type->is_nullable()
1309
9.55k
                                              ? make_nullable(table_type)
1310
9.55k
                                              : table_type;
1311
9.55k
        auto cast_expr = Cast::create_shared(cast_target_type);
1312
9.55k
        cast_expr->add_child(std::move(slot_ref));
1313
9.55k
        auto cast_ctx = VExprContext::create_shared(std::move(cast_expr));
1314
9.55k
        RowDescriptor row_desc;
1315
9.55k
        RETURN_IF_ERROR(cast_ctx->prepare(_runtime_state, row_desc));
1316
9.55k
        RETURN_IF_ERROR(cast_ctx->open(_runtime_state));
1317
9.55k
        ColumnPtr cast_column;
1318
9.55k
        RETURN_IF_ERROR(cast_ctx->execute(&cast_block, cast_column));
1319
9.55k
        *column = std::move(cast_column);
1320
9.55k
        return Status::OK();
1321
9.55k
    }
1322
1323
    Status _materialize_present_child_mapping_column(
1324
            const ColumnMapping& mapping, const ColumnPtr& file_column, const size_t rows,
1325
20.7k
            ColumnPtr* column, const NullMap* nullable_parent_null_map = nullptr) {
1326
20.7k
        DORIS_CHECK(column != nullptr);
1327
20.7k
        DORIS_CHECK(mapping.file_type != nullptr);
1328
20.7k
        DORIS_CHECK(mapping.table_type != nullptr);
1329
20.7k
        *column = file_column;
1330
20.7k
        if (!mapping.is_trivial) {
1331
12.1k
            if (!mapping.child_mappings.empty()) {
1332
2.56k
                RETURN_IF_ERROR(_materialize_complex_mapping_column(mapping, *column, rows, column,
1333
2.56k
                                                                    nullable_parent_null_map));
1334
9.55k
            } else {
1335
9.55k
                RETURN_IF_ERROR(_cast_column_to_type(column, mapping.file_type, mapping.table_type,
1336
9.55k
                                                     mapping.file_column_name));
1337
9.55k
            }
1338
12.1k
        }
1339
20.7k
        RETURN_IF_ERROR(
1340
20.7k
                _align_column_nullability(column, mapping.table_type, nullable_parent_null_map));
1341
20.7k
        return Status::OK();
1342
20.7k
    }
1343
1344
    Status _materialize_mapping_column(const ColumnMapping& mapping, Block* current_block,
1345
                                       const size_t rows, ColumnPtr* column,
1346
589k
                                       bool take_projection_result = false) {
1347
589k
        if (!mapping.is_trivial && mapping.file_local_id.has_value() &&
1348
589k
            !mapping.child_mappings.empty()) {
1349
11.2k
            DCHECK(mapping.projection != nullptr);
1350
11.2k
            int res_id;
1351
11.2k
            auto st = mapping.projection->execute(current_block, &res_id);
1352
11.2k
            if (!st.ok()) {
1353
0
                return Status::InternalError(
1354
0
                        "Failed to execute complex mapping projection for table column '{}' "
1355
0
                        "(global_index={}, file_local_id={}, rows={}): {}, mapping={}",
1356
0
                        mapping.table_column_name, mapping.global_index.value(),
1357
0
                        *mapping.file_local_id, rows, st.to_string(), mapping.debug_string());
1358
0
            }
1359
11.2k
            ColumnPtr result_column = take_projection_result
1360
11.2k
                                              ? _take_and_detach_block_column(current_block, res_id)
1361
11.2k
                                              : current_block->get_by_position(res_id).column;
1362
11.2k
            RETURN_IF_ERROR(
1363
11.2k
                    _materialize_complex_mapping_column(mapping, result_column, rows, column));
1364
11.2k
            return Status::OK();
1365
11.2k
        }
1366
577k
        if (mapping.projection != nullptr) {
1367
554k
            int res_id;
1368
554k
            auto st = mapping.projection->execute(current_block, &res_id);
1369
554k
            if (!st.ok()) {
1370
1
                std::string file_local_id = "null";
1371
1
                if (mapping.file_local_id.has_value()) {
1372
1
                    file_local_id = std::to_string(*mapping.file_local_id);
1373
1
                }
1374
1
                return Status::InternalError(
1375
1
                        "Failed to execute mapping projection for table column '{}' "
1376
1
                        "(global_index={}, file_local_id={}, rows={}): {}, mapping={}",
1377
1
                        mapping.table_column_name, mapping.global_index.value(), file_local_id,
1378
1
                        rows, st.to_string(), mapping.debug_string());
1379
1
            }
1380
554k
            if (take_projection_result) {
1381
93.3k
                *column = _take_and_detach_block_column(current_block, res_id);
1382
460k
            } else {
1383
460k
                ColumnPtr result_column = current_block->get_by_position(res_id).column;
1384
460k
                *column = _detach_column(std::move(result_column));
1385
460k
            }
1386
554k
            return Status::OK();
1387
554k
        }
1388
23.9k
        if (mapping.default_expr != nullptr) {
1389
21.0k
            if (current_block->rows() == rows) {
1390
18.2k
                ColumnWithTypeAndName result;
1391
18.2k
                RETURN_IF_ERROR(_execute_default_expr_without_root_type_check(
1392
18.2k
                        mapping.default_expr, current_block, &result));
1393
18.2k
                ColumnPtr result_column = result.column;
1394
18.2k
                RETURN_IF_ERROR(_align_column_nullability(&result_column, mapping.table_type));
1395
18.2k
                *column = _detach_column(std::move(result_column));
1396
18.2k
            } else {
1397
2.74k
                DORIS_CHECK(mapping.constant_index.has_value());
1398
2.74k
                Block eval_block;
1399
2.74k
                eval_block.insert({mapping.table_type->create_column_const_with_default_value(rows),
1400
2.74k
                                   mapping.table_type, "__table_reader_const_rows"});
1401
2.74k
                ColumnWithTypeAndName result;
1402
2.74k
                RETURN_IF_ERROR(_execute_default_expr_without_root_type_check(
1403
2.74k
                        mapping.default_expr, &eval_block, &result));
1404
2.74k
                ColumnPtr result_column = result.column;
1405
2.74k
                RETURN_IF_ERROR(_align_column_nullability(&result_column, mapping.table_type));
1406
2.74k
                *column = _detach_column(std::move(result_column));
1407
2.74k
            }
1408
21.0k
            return Status::OK();
1409
21.0k
        }
1410
2.89k
        ColumnPtr result_column = mapping.table_type->create_column_const_with_default_value(rows);
1411
2.89k
        *column = _detach_column(std::move(result_column));
1412
2.89k
        return Status::OK();
1413
23.9k
    }
1414
1415
    Status _materialize_complex_mapping_column(const ColumnMapping& mapping,
1416
                                               const ColumnPtr& file_column, const size_t rows,
1417
                                               ColumnPtr* column,
1418
13.8k
                                               const NullMap* nullable_parent_null_map = nullptr) {
1419
13.8k
        DORIS_CHECK(mapping.table_type != nullptr);
1420
13.8k
        DORIS_CHECK(file_column.get() != nullptr);
1421
13.8k
        const auto table_type = remove_nullable(mapping.table_type);
1422
13.8k
        switch (table_type->get_primitive_type()) {
1423
4.66k
        case TYPE_STRUCT:
1424
4.66k
            RETURN_IF_ERROR(_materialize_struct_mapping_column(mapping, file_column, rows, column,
1425
4.66k
                                                               nullable_parent_null_map));
1426
4.66k
            break;
1427
4.80k
        case TYPE_ARRAY:
1428
4.80k
            RETURN_IF_ERROR(_materialize_array_mapping_column(mapping, file_column, rows, column,
1429
4.80k
                                                              nullable_parent_null_map));
1430
4.80k
            break;
1431
4.80k
        case TYPE_MAP:
1432
4.36k
            RETURN_IF_ERROR(_materialize_map_mapping_column(mapping, file_column, rows, column,
1433
4.36k
                                                            nullable_parent_null_map));
1434
4.36k
            break;
1435
4.36k
        default:
1436
0
            *column = _detach_column(file_column);
1437
0
            break;
1438
13.8k
        }
1439
13.8k
        return Status::OK();
1440
13.8k
    }
1441
1442
    static std::vector<const ColumnMapping*> _present_child_mappings_in_file_order(
1443
4.66k
            const std::vector<ColumnMapping>& child_mappings) {
1444
4.66k
        std::vector<const ColumnMapping*> result;
1445
4.66k
        result.reserve(child_mappings.size());
1446
12.0k
        for (const auto& child_mapping : child_mappings) {
1447
12.0k
            if (child_mapping.file_local_id.has_value()) {
1448
7.25k
                result.push_back(&child_mapping);
1449
7.25k
            }
1450
12.0k
        }
1451
5.70k
        std::ranges::sort(result, [](const ColumnMapping* lhs, const ColumnMapping* rhs) {
1452
5.70k
            DORIS_CHECK(lhs->file_local_id.has_value());
1453
5.70k
            DORIS_CHECK(rhs->file_local_id.has_value());
1454
5.70k
            return *lhs->file_local_id < *rhs->file_local_id;
1455
5.70k
        });
1456
4.66k
        return result;
1457
4.66k
    }
1458
1459
    static size_t _file_child_ordinal_for_mapping(
1460
            const ColumnMapping& mapping, const ColumnMapping& child_mapping,
1461
7.25k
            const std::vector<const ColumnMapping*>& file_ordered_children) {
1462
7.25k
        DORIS_CHECK(child_mapping.file_local_id.has_value());
1463
7.25k
        if (!mapping.projected_file_children.empty()) {
1464
7.24k
            const auto child_it = std::ranges::find_if(
1465
12.1k
                    mapping.projected_file_children, [&](const ColumnDefinition& file_child) {
1466
12.1k
                        return file_child.file_local_id() == *child_mapping.file_local_id;
1467
12.1k
                    });
1468
7.24k
            DORIS_CHECK(child_it != mapping.projected_file_children.end());
1469
7.24k
            return static_cast<size_t>(
1470
7.24k
                    std::distance(mapping.projected_file_children.begin(), child_it));
1471
7.24k
        }
1472
11
        const auto child_it = std::ranges::find(file_ordered_children, &child_mapping);
1473
11
        DORIS_CHECK(child_it != file_ordered_children.end());
1474
11
        return static_cast<size_t>(std::distance(file_ordered_children.begin(), child_it));
1475
7.25k
    }
1476
1477
    static std::vector<const ColumnMapping*> _child_mappings_in_table_type_order(
1478
4.66k
            const ColumnMapping& mapping, const DataTypeStruct& table_type) {
1479
4.66k
        std::vector<const ColumnMapping*> result;
1480
4.66k
        result.reserve(mapping.child_mappings.size());
1481
16.6k
        for (size_t child_idx = 0; child_idx < table_type.get_elements().size(); ++child_idx) {
1482
12.0k
            const auto& child_name = table_type.get_element_name(child_idx);
1483
12.0k
            const auto child_it = std::ranges::find_if(
1484
24.1k
                    mapping.child_mappings, [&](const ColumnMapping& child_mapping) {
1485
24.1k
                        return child_mapping.table_column_name == child_name;
1486
24.1k
                    });
1487
12.0k
            DORIS_CHECK(child_it != mapping.child_mappings.end())
1488
0
                    << mapping.debug_string() << ", table_child_name=" << child_name;
1489
12.0k
            result.push_back(&*child_it);
1490
12.0k
        }
1491
4.66k
        return result;
1492
4.66k
    }
1493
1494
    static const IColumn* _nested_column_if_nullable(const ColumnPtr& column,
1495
13.8k
                                                     const NullMap** null_map) {
1496
13.8k
        DORIS_CHECK(column.get() != nullptr);
1497
13.8k
        if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*column)) {
1498
13.8k
            if (null_map != nullptr) {
1499
13.8k
                *null_map = &nullable_column->get_null_map_data();
1500
13.8k
            }
1501
13.8k
            return &nullable_column->get_nested_column();
1502
13.8k
        }
1503
4
        return column.get();
1504
13.8k
    }
1505
1506
    template <typename Offsets>
1507
    static const NullMap* _project_collection_parent_null_map(
1508
            const NullMap* container_null_map, const NullMap* ancestor_null_map, const size_t rows,
1509
9.17k
            const Offsets& offsets, const size_t child_rows, NullMap* const projected_null_map) {
1510
9.17k
        if (container_null_map == nullptr && ancestor_null_map == nullptr) {
1511
2
            return nullptr;
1512
2
        }
1513
9.17k
        DORIS_CHECK(container_null_map == nullptr || container_null_map->size() == rows);
1514
9.17k
        DORIS_CHECK(ancestor_null_map == nullptr || ancestor_null_map->size() == rows);
1515
9.17k
        DORIS_CHECK(offsets.size() == rows);
1516
9.17k
        bool has_hidden_row = false;
1517
20.5k
        for (size_t row = 0; row < rows; ++row) {
1518
12.3k
            if ((container_null_map != nullptr && (*container_null_map)[row]) ||
1519
12.3k
                (ancestor_null_map != nullptr && (*ancestor_null_map)[row])) {
1520
958
                has_hidden_row = true;
1521
958
                break;
1522
958
            }
1523
12.3k
        }
1524
9.17k
        if (!has_hidden_row) {
1525
            // Nullable collection wrappers expose a null-map even when every row is present; avoid
1526
            // allocating entry-coordinate scratch proportional to a potentially huge collection.
1527
8.21k
            return nullptr;
1528
8.21k
        }
1529
958
        projected_null_map->resize(child_rows);
1530
958
        std::fill(projected_null_map->begin(), projected_null_map->end(), 0);
1531
958
        size_t begin = 0;
1532
2.13k
        for (size_t row = 0; row < rows; ++row) {
1533
1.17k
            const size_t end = offsets[row];
1534
1.17k
            const bool hidden = (container_null_map != nullptr && (*container_null_map)[row]) ||
1535
1.17k
                                (ancestor_null_map != nullptr && (*ancestor_null_map)[row]);
1536
1.17k
            if (hidden) {
1537
                // Collection masks use row coordinates; descendants need the same invariant
1538
                // projected through offsets so hidden physical payload cannot fail validation.
1539
1.17k
                std::fill(projected_null_map->begin() + begin, projected_null_map->begin() + end,
1540
1.17k
                          1);
1541
1.17k
            }
1542
1.17k
            begin = end;
1543
1.17k
        }
1544
958
        DORIS_CHECK(begin == child_rows);
1545
958
        return projected_null_map;
1546
9.17k
    }
1547
1548
    Status _materialize_struct_mapping_column(const ColumnMapping& mapping,
1549
                                              const ColumnPtr& file_column, const size_t rows,
1550
                                              ColumnPtr* column,
1551
4.67k
                                              const NullMap* nullable_parent_null_map = nullptr) {
1552
4.67k
        DORIS_CHECK(mapping.table_type != nullptr);
1553
4.67k
        const auto* table_type =
1554
4.67k
                assert_cast<const DataTypeStruct*>(remove_nullable(mapping.table_type).get());
1555
4.67k
        const auto full_file_column = file_column->convert_to_full_column_if_const();
1556
4.67k
        const NullMap* parent_null_map = nullptr;
1557
4.67k
        const auto* nested_file_column =
1558
4.67k
                _nested_column_if_nullable(full_file_column, &parent_null_map);
1559
4.67k
        const auto* file_struct = assert_cast<const ColumnStruct*>(nested_file_column);
1560
4.67k
        DORIS_CHECK(table_type->get_elements().size() == mapping.child_mappings.size());
1561
1562
4.67k
        NullMap combined_parent_null_map;
1563
4.67k
        const NullMap* descendant_parent_null_map = nullable_parent_null_map;
1564
4.67k
        if (parent_null_map != nullptr) {
1565
4.66k
            DORIS_CHECK(parent_null_map->size() == rows);
1566
4.66k
            if (nullable_parent_null_map != nullptr) {
1567
51
                DORIS_CHECK(nullable_parent_null_map->size() == rows);
1568
51
            }
1569
4.66k
            if (!mapping.table_type->is_nullable()) {
1570
7
                for (size_t i = 0; i < rows; ++i) {
1571
                    // A required nested container may drop its own NULL only when an ancestor
1572
                    // already hides that row; otherwise physical defaults become visible values.
1573
5
                    if ((*parent_null_map)[i] &&
1574
5
                        (nullable_parent_null_map == nullptr || !(*nullable_parent_null_map)[i])) {
1575
1
                        return Status::InternalError(
1576
1
                                "Source struct contains NULL for non-nullable table column");
1577
1
                    }
1578
5
                }
1579
3
            }
1580
4.66k
            combined_parent_null_map.resize(rows);
1581
104k
            for (size_t i = 0; i < rows; ++i) {
1582
99.5k
                combined_parent_null_map[i] =
1583
99.5k
                        (*parent_null_map)[i] ||
1584
99.5k
                        (nullable_parent_null_map != nullptr && (*nullable_parent_null_map)[i]);
1585
99.5k
            }
1586
4.66k
            descendant_parent_null_map = &combined_parent_null_map;
1587
4.66k
        }
1588
1589
4.66k
        Columns child_columns;
1590
4.66k
        child_columns.reserve(mapping.child_mappings.size());
1591
4.66k
        const auto file_ordered_children =
1592
4.66k
                _present_child_mappings_in_file_order(mapping.child_mappings);
1593
4.66k
        const auto table_ordered_children =
1594
4.66k
                _child_mappings_in_table_type_order(mapping, *table_type);
1595
12.0k
        for (const auto* child_mapping : table_ordered_children) {
1596
12.0k
            DORIS_CHECK(child_mapping != nullptr);
1597
12.0k
            if (!child_mapping->file_local_id.has_value()) {
1598
4.75k
                ColumnPtr child_column =
1599
4.75k
                        (child_mapping->initial_default_column
1600
4.75k
                                 ? child_mapping->initial_default_column->clone_resized(rows)
1601
4.75k
                                 : child_mapping->table_type
1602
4.75k
                                           ->create_column_const_with_default_value(rows))
1603
4.75k
                                ->convert_to_full_column_if_const();
1604
4.75k
                RETURN_IF_ERROR(_align_column_nullability(&child_column, child_mapping->table_type,
1605
4.75k
                                                          descendant_parent_null_map));
1606
4.75k
                child_columns.push_back(std::move(child_column));
1607
4.75k
                continue;
1608
4.75k
            }
1609
7.25k
            const auto file_child_idx =
1610
7.25k
                    _file_child_ordinal_for_mapping(mapping, *child_mapping, file_ordered_children);
1611
7.25k
            DORIS_CHECK(file_child_idx < file_struct->get_columns().size());
1612
7.25k
            ColumnPtr child_column = file_struct->get_column_ptr(file_child_idx);
1613
7.25k
            RETURN_IF_ERROR(_materialize_present_child_mapping_column(
1614
7.25k
                    *child_mapping, child_column, rows, &child_column, descendant_parent_null_map));
1615
7.25k
            child_columns.push_back(std::move(child_column));
1616
7.25k
        }
1617
4.66k
        MutableColumns mutable_child_columns;
1618
4.66k
        mutable_child_columns.reserve(child_columns.size());
1619
12.0k
        for (auto& child_column : child_columns) {
1620
12.0k
            mutable_child_columns.push_back(IColumn::mutate(std::move(child_column)));
1621
12.0k
        }
1622
4.66k
        auto result = ColumnStruct::create(std::move(mutable_child_columns));
1623
4.66k
        if (mapping.table_type->is_nullable()) {
1624
4.66k
            auto null_map = ColumnUInt8::create();
1625
4.66k
            auto& null_map_data = null_map->get_data();
1626
4.66k
            null_map_data.resize(rows);
1627
4.66k
            if (parent_null_map != nullptr) {
1628
4.66k
                DORIS_CHECK(parent_null_map->size() == rows);
1629
4.66k
                null_map_data.assign(parent_null_map->begin(), parent_null_map->end());
1630
4.66k
            } else {
1631
0
                std::fill(null_map_data.begin(), null_map_data.end(), 0);
1632
0
            }
1633
4.66k
            *column = ColumnNullable::create(std::move(result), std::move(null_map));
1634
4.66k
        } else {
1635
4
            *column = std::move(result);
1636
4
        }
1637
4.66k
        return Status::OK();
1638
4.66k
    }
1639
1640
    Status _materialize_array_mapping_column(const ColumnMapping& mapping,
1641
                                             const ColumnPtr& file_column, const size_t rows,
1642
                                             ColumnPtr* column,
1643
4.80k
                                             const NullMap* nullable_parent_null_map = nullptr) {
1644
4.80k
        DORIS_CHECK(mapping.child_mappings.size() == 1);
1645
4.80k
        const auto full_file_column = file_column->convert_to_full_column_if_const();
1646
4.80k
        const NullMap* parent_null_map = nullptr;
1647
4.80k
        const auto* nested_file_column =
1648
4.80k
                _nested_column_if_nullable(full_file_column, &parent_null_map);
1649
4.80k
        if (parent_null_map != nullptr && !mapping.table_type->is_nullable()) {
1650
2
            DORIS_CHECK(parent_null_map->size() == rows);
1651
2
            if (nullable_parent_null_map != nullptr) {
1652
1
                DORIS_CHECK(nullable_parent_null_map->size() == rows);
1653
1
            }
1654
4
            for (size_t i = 0; i < rows; ++i) {
1655
                // ARRAY row masks cannot be forwarded to elements because they use different
1656
                // coordinates, so validate the container before dropping its nullable wrapper.
1657
3
                if ((*parent_null_map)[i] &&
1658
3
                    (nullable_parent_null_map == nullptr || !(*nullable_parent_null_map)[i])) {
1659
1
                    return Status::InternalError(
1660
1
                            "Source array contains NULL for non-nullable table column");
1661
1
                }
1662
3
            }
1663
2
        }
1664
4.80k
        const auto* file_array = assert_cast<const ColumnArray*>(nested_file_column);
1665
4.80k
        ColumnPtr nested_column = file_array->get_data_ptr();
1666
4.80k
        auto element_mapping = mapping.child_mappings[0];
1667
        // Keep the descriptor type for schema matching. ARRAY's nullable element wrapper is a
1668
        // storage invariant, so add it only at the materialization boundary.
1669
4.80k
        element_mapping.table_type = make_nullable(element_mapping.table_type);
1670
4.80k
        NullMap descendant_parent_null_map;
1671
4.80k
        const NullMap* descendant_parent_null_map_ptr = _project_collection_parent_null_map(
1672
4.80k
                parent_null_map, nullable_parent_null_map, rows, file_array->get_offsets(),
1673
4.80k
                nested_column->size(), &descendant_parent_null_map);
1674
4.80k
        RETURN_IF_ERROR(_materialize_present_child_mapping_column(
1675
4.80k
                element_mapping, nested_column, nested_column->size(), &nested_column,
1676
4.80k
                descendant_parent_null_map_ptr));
1677
4.80k
        auto offsets_column = file_array->get_offsets_ptr()->convert_to_full_column_if_const();
1678
4.80k
        auto result = ColumnArray::create(IColumn::mutate(std::move(nested_column)),
1679
4.80k
                                          IColumn::mutate(std::move(offsets_column)));
1680
4.80k
        if (mapping.table_type->is_nullable()) {
1681
4.80k
            auto null_map = ColumnUInt8::create();
1682
4.80k
            auto& null_map_data = null_map->get_data();
1683
4.80k
            null_map_data.resize(rows);
1684
4.80k
            if (parent_null_map != nullptr) {
1685
4.80k
                DORIS_CHECK(parent_null_map->size() == rows);
1686
4.80k
                null_map_data.assign(parent_null_map->begin(), parent_null_map->end());
1687
4.80k
            } else {
1688
0
                std::fill(null_map_data.begin(), null_map_data.end(), 0);
1689
0
            }
1690
4.80k
            *column = ColumnNullable::create(std::move(result), std::move(null_map));
1691
4.80k
        } else {
1692
1
            *column = std::move(result);
1693
1
        }
1694
4.80k
        return Status::OK();
1695
4.80k
    }
1696
1697
    Status _materialize_map_mapping_column(const ColumnMapping& mapping,
1698
                                           const ColumnPtr& file_column, const size_t rows,
1699
                                           ColumnPtr* column,
1700
4.36k
                                           const NullMap* nullable_parent_null_map = nullptr) {
1701
4.36k
        const auto full_file_column = file_column->convert_to_full_column_if_const();
1702
4.36k
        const NullMap* parent_null_map = nullptr;
1703
4.36k
        const auto* nested_file_column =
1704
4.36k
                _nested_column_if_nullable(full_file_column, &parent_null_map);
1705
4.36k
        if (parent_null_map != nullptr && !mapping.table_type->is_nullable()) {
1706
0
            DORIS_CHECK(parent_null_map->size() == rows);
1707
0
            if (nullable_parent_null_map != nullptr) {
1708
0
                DORIS_CHECK(nullable_parent_null_map->size() == rows);
1709
0
            }
1710
0
            for (size_t i = 0; i < rows; ++i) {
1711
                // MAP row masks cannot be forwarded to entries because they use different
1712
                // coordinates, so validate the container before dropping its nullable wrapper.
1713
0
                if ((*parent_null_map)[i] &&
1714
0
                    (nullable_parent_null_map == nullptr || !(*nullable_parent_null_map)[i])) {
1715
0
                    return Status::InternalError(
1716
0
                            "Source map contains NULL for non-nullable table column");
1717
0
                }
1718
0
            }
1719
0
        }
1720
4.36k
        const auto* file_map = assert_cast<const ColumnMap*>(nested_file_column);
1721
4.36k
        ColumnPtr key_column = file_map->get_keys_ptr();
1722
4.36k
        ColumnPtr value_column = file_map->get_values_ptr();
1723
4.36k
        DORIS_CHECK(key_column->size() == value_column->size());
1724
4.36k
        NullMap descendant_parent_null_map;
1725
4.36k
        const NullMap* descendant_parent_null_map_ptr = _project_collection_parent_null_map(
1726
4.36k
                parent_null_map, nullable_parent_null_map, rows, file_map->get_offsets(),
1727
4.36k
                key_column->size(), &descendant_parent_null_map);
1728
1729
4.36k
        const ColumnMapping* key_mapping = nullptr;
1730
4.36k
        const ColumnMapping* value_mapping = nullptr;
1731
8.73k
        for (const auto& child_mapping : mapping.child_mappings) {
1732
8.73k
            if (!child_mapping.file_local_id.has_value()) {
1733
0
                continue;
1734
0
            }
1735
8.73k
            if (*child_mapping.file_local_id == 0) {
1736
4.36k
                key_mapping = &child_mapping;
1737
4.36k
            } else if (*child_mapping.file_local_id == 1) {
1738
4.36k
                value_mapping = &child_mapping;
1739
4.36k
            }
1740
8.73k
        }
1741
1742
4.36k
        if (key_mapping != nullptr) {
1743
4.36k
            RETURN_IF_ERROR(_materialize_present_child_mapping_column(
1744
4.36k
                    *key_mapping, key_column, key_column->size(), &key_column,
1745
4.36k
                    descendant_parent_null_map_ptr));
1746
4.36k
        } else {
1747
0
            const auto* table_map =
1748
0
                    assert_cast<const DataTypeMap*>(remove_nullable(mapping.table_type).get());
1749
            // Value-only projection retains the physical key stream to preserve entry offsets;
1750
            // align it under the entry mask so NULL placeholders from hidden Map rows stay hidden.
1751
0
            RETURN_IF_ERROR(_align_column_nullability(&key_column, table_map->get_key_type(),
1752
0
                                                      descendant_parent_null_map_ptr));
1753
0
        }
1754
4.36k
        if (value_mapping != nullptr) {
1755
4.36k
            RETURN_IF_ERROR(_materialize_present_child_mapping_column(
1756
4.36k
                    *value_mapping, value_column, value_column->size(), &value_column,
1757
4.36k
                    descendant_parent_null_map_ptr));
1758
4.36k
        } else {
1759
0
            const auto* table_map =
1760
0
                    assert_cast<const DataTypeMap*>(remove_nullable(mapping.table_type).get());
1761
            // A retained structural value stream follows the same hidden-entry invariant as keys.
1762
0
            RETURN_IF_ERROR(_align_column_nullability(&value_column, table_map->get_value_type(),
1763
0
                                                      descendant_parent_null_map_ptr));
1764
0
        }
1765
4.36k
        auto offsets_column = file_map->get_offsets_ptr()->convert_to_full_column_if_const();
1766
4.36k
        auto result = ColumnMap::create(IColumn::mutate(std::move(key_column)),
1767
4.36k
                                        IColumn::mutate(std::move(value_column)),
1768
4.36k
                                        IColumn::mutate(std::move(offsets_column)));
1769
4.36k
        if (mapping.table_type->is_nullable()) {
1770
4.36k
            auto null_map = ColumnUInt8::create();
1771
4.36k
            auto& null_map_data = null_map->get_data();
1772
4.36k
            null_map_data.resize(rows);
1773
4.36k
            if (parent_null_map != nullptr) {
1774
4.36k
                DORIS_CHECK(parent_null_map->size() == rows);
1775
4.36k
                null_map_data.assign(parent_null_map->begin(), parent_null_map->end());
1776
4.36k
            } else {
1777
0
                std::fill(null_map_data.begin(), null_map_data.end(), 0);
1778
0
            }
1779
4.36k
            *column = ColumnNullable::create(std::move(result), std::move(null_map));
1780
4.36k
        } else {
1781
0
            *column = std::move(result);
1782
0
        }
1783
4.36k
        return Status::OK();
1784
4.36k
    }
1785
1786
120k
    Status _open_mapping_exprs() {
1787
120k
        RowDescriptor row_desc;
1788
526k
        for (const auto& mapping : _data_reader.column_mapper->mappings()) {
1789
526k
            if (mapping.projection != nullptr) {
1790
501k
                RETURN_IF_ERROR(mapping.projection->prepare(_runtime_state, row_desc));
1791
501k
                RETURN_IF_ERROR(mapping.projection->open(_runtime_state));
1792
501k
            }
1793
526k
            if (mapping.default_expr != nullptr) {
1794
21.7k
                RETURN_IF_ERROR(mapping.default_expr->prepare(_runtime_state, row_desc));
1795
21.7k
                RETURN_IF_ERROR(mapping.default_expr->open(_runtime_state));
1796
21.7k
            }
1797
526k
        }
1798
120k
        return Status::OK();
1799
120k
    }
1800
1801
    Status _build_file_aggregate_request(TPushAggOp::type agg_type,
1802
1.53k
                                         FileAggregateRequest* request) const {
1803
1.53k
        DORIS_CHECK(request != nullptr);
1804
1.53k
        DORIS_CHECK(_supports_aggregate_pushdown(agg_type));
1805
1.53k
        request->agg_type = agg_type;
1806
1.53k
        request->columns.clear();
1807
1.53k
        if (agg_type == TPushAggOp::type::COUNT) {
1808
1.51k
            DORIS_CHECK(_push_down_count_columns.has_value());
1809
            // An empty explicit list is the semantic signal for COUNT(*). Do not inspect the
1810
            // mapping count: `SELECT COUNT(*) FROM t` may still project one nullable column because
1811
            // the planner keeps a placeholder slot. In a 10,000-row file where that arbitrary slot
1812
            // has 9,015 non-null values, passing the slot would ask Parquet/ORC metadata for
1813
            // COUNT(slot)=9,015 instead of the required row count 10,000.
1814
1.51k
            if (!_push_down_count_columns->empty()) {
1815
252
                const auto& mapping = _push_down_count_mapping();
1816
252
                DORIS_CHECK(mapping.file_local_id.has_value());
1817
252
                FileAggregateRequest::Column column;
1818
252
                column.projection =
1819
252
                        LocalColumnIndex::top_level(LocalColumnId(*mapping.file_local_id));
1820
252
                request->columns.push_back(std::move(column));
1821
252
            }
1822
1.51k
            return Status::OK();
1823
1.51k
        }
1824
28
        request->columns.reserve(_data_reader.column_mapper->mappings().size());
1825
47
        for (const auto& mapping : _data_reader.column_mapper->mappings()) {
1826
47
            DORIS_CHECK(mapping.file_local_id.has_value());
1827
47
            FileAggregateRequest::Column column;
1828
47
            column.projection = LocalColumnIndex::top_level(LocalColumnId(*mapping.file_local_id));
1829
47
            if (!mapping.child_mappings.empty()) {
1830
1
                RETURN_IF_ERROR(build_aggregate_projection(mapping, &column.projection));
1831
1
            }
1832
47
            request->columns.push_back(std::move(column));
1833
47
        }
1834
28
        return Status::OK();
1835
28
    }
1836
1837
1.04k
    const ColumnMapping& _push_down_count_mapping() const {
1838
1.04k
        DORIS_CHECK(_push_down_count_columns.has_value());
1839
1.04k
        DORIS_CHECK(_push_down_count_columns->size() == 1);
1840
1.04k
        const auto mapping_it =
1841
1.04k
                std::ranges::find(_data_reader.column_mapper->mappings(),
1842
1.04k
                                  _push_down_count_columns->front(), &ColumnMapping::global_index);
1843
        // FileScannerV2 translates FE SlotIds through the same projected-column list used to build
1844
        // the mapper, so a missing mapping is an FE/BE contract violation rather than a fallback.
1845
1.04k
        DORIS_CHECK(mapping_it != _data_reader.column_mapper->mappings().end());
1846
1.04k
        return *mapping_it;
1847
1.04k
    }
1848
1849
    Status _materialize_aggregate_pushdown_rows(TPushAggOp::type agg_type,
1850
                                                const FileAggregateResult& file_result,
1851
21
                                                Block* block) {
1852
21
        DORIS_CHECK(agg_type == TPushAggOp::type::MINMAX);
1853
        // MIN/MAX pushdown emits two rows, min first and max second, for each projected column.
1854
        // The upper MIN/MAX aggregate consumes those two rows to produce the final aggregate value.
1855
21
        DORIS_CHECK(file_result.columns.size() == _data_reader.column_mapper->mappings().size());
1856
21
        DORIS_CHECK(block->columns() == _data_reader.column_mapper->mappings().size());
1857
21
        Block file_block;
1858
21
        file_block.reserve(_data_reader.file_block_layout.size());
1859
26
        for (const auto& column : _data_reader.file_block_layout) {
1860
26
            file_block.insert({column.type->create_column(), column.type, column.name});
1861
26
        }
1862
47
        for (size_t column_idx = 0; column_idx < file_result.columns.size(); ++column_idx) {
1863
26
            const auto& result_column = file_result.columns[column_idx];
1864
26
            if (!result_column.has_min || !result_column.has_max) {
1865
0
                return Status::NotSupported("Missing min/max aggregate result for column {}",
1866
0
                                            _projected_columns[column_idx].name);
1867
0
            }
1868
26
            bool found_file_column = false;
1869
33
            for (size_t block_position = 0; block_position < _data_reader.file_block_layout.size();
1870
33
                 ++block_position) {
1871
33
                if (_data_reader.file_block_layout[block_position].file_column_id ==
1872
33
                    file_result.columns[column_idx].projection.column_id()) {
1873
26
                    found_file_column = true;
1874
26
                    auto column = file_block.get_by_position(block_position)
1875
26
                                          .type->create_column()
1876
26
                                          ->assert_mutable();
1877
26
                    RETURN_IF_ERROR(_insert_aggregate_projection_value(
1878
26
                            file_result.columns[column_idx].projection, result_column.min_value,
1879
26
                            column.get()));
1880
26
                    RETURN_IF_ERROR(_insert_aggregate_projection_value(
1881
26
                            file_result.columns[column_idx].projection, result_column.max_value,
1882
26
                            column.get()));
1883
26
                    file_block.replace_by_position(block_position, std::move(column));
1884
26
                    break;
1885
26
                }
1886
33
            }
1887
26
            DORIS_CHECK(found_file_column);
1888
26
        }
1889
47
        for (size_t column_idx = 0; column_idx < _data_reader.column_mapper->mappings().size();
1890
26
             ++column_idx) {
1891
26
            ColumnPtr table_column;
1892
26
            RETURN_IF_ERROR(_materialize_mapping_column(
1893
26
                    _data_reader.column_mapper->mappings()[column_idx], &file_block, 2,
1894
26
                    &table_column,
1895
26
                    column_idx + 1 == _data_reader.column_mapper->mappings().size()));
1896
26
            block->replace_by_position(column_idx, std::move(table_column));
1897
26
        }
1898
21
        return Status::OK();
1899
21
    }
1900
1901
    struct FileBlockColumn {
1902
        LocalColumnId file_column_id = LocalColumnId::invalid();
1903
        std::string name;
1904
        DataTypePtr type;
1905
    };
1906
1907
    struct DataReader {
1908
        std::unique_ptr<FileReader> reader;
1909
        std::unique_ptr<TableColumnMapper> column_mapper;
1910
        // Schema of the data file, also including virtual column (row position).
1911
        std::vector<ColumnDefinition> file_schema;
1912
        // Layout of the block returned by file reader, determined by column mapping and file
1913
        // schema. It is used for file reader to materialize columns into correct type and position.
1914
        std::vector<FileBlockColumn> file_block_layout;
1915
        Block block_template;
1916
    };
1917
    DataReader _data_reader;
1918
    // Latest immutable request queued to the physical reader. The file-block layout remains fixed
1919
    // for the split even while predicates are refreshed at a reader-defined granule boundary.
1920
    std::shared_ptr<FileScanRequest> _file_scan_request;
1921
    std::vector<ColumnDefinition> _projected_columns;
1922
    std::unique_ptr<ScanTask> _current_task;
1923
    std::optional<io::FileDescription> _current_file_description;
1924
    // Range-level compression has higher priority than scan-param compression. TVF/load can keep
1925
    // the logical format as CSV/TEXT while carrying the concrete compression such as GZ or LZO on
1926
    // each TFileRangeDesc, matching the old FileScanner reader contract.
1927
    TFileCompressType::type _current_range_compress_type = TFileCompressType::UNKNOWN;
1928
    std::optional<TUniqueId> _current_range_load_id;
1929
    TFileRangeDesc _current_file_range_desc;
1930
    std::shared_ptr<io::FileSystemProperties> _system_properties;
1931
    // partition key -> value
1932
    std::map<std::string, Field> _partition_values;
1933
    // Predicates built from scan conjuncts before file-level localization.
1934
    std::vector<TableFilter> _table_filters;
1935
    // Number of localized filters before the first unsafe conjunct in the original row-level
1936
    // order. This differs from scanning `_table_filters` for safety because slotless predicates are
1937
    // intentionally absent from that vector but must still act as ordering barriers.
1938
    size_t _constant_pruning_safe_filter_count = 0;
1939
    VExprContextSPtrs _conjuncts;
1940
    ReadProfile _profile;
1941
    // Parsed from row-position based delete files, including position delete and deletion vector.
1942
    DeleteRows* _delete_rows = nullptr;
1943
    DeletionVector* _deletion_vector = nullptr;
1944
    TFileScanRangeParams* _scan_params;
1945
    std::shared_ptr<io::IOContext> _io_ctx;
1946
    RuntimeState* _runtime_state;
1947
    RuntimeProfile* _scanner_profile;
1948
    const std::vector<SlotDescriptor*>* _file_slot_descs = nullptr;
1949
    FileFormat _format;
1950
    TPushAggOp::type _push_down_agg_type = TPushAggOp::type::NONE;
1951
    std::optional<std::vector<GlobalIndex>> _push_down_count_columns;
1952
    size_t _batch_size = 0;
1953
    uint64_t _initial_condition_cache_digest = 0;
1954
    uint64_t _condition_cache_digest = 0;
1955
    // True only when prepare_split() received a digest for the exact conjunct snapshot used by
1956
    // this split. Standalone callers that only supplied TableReadOptions::condition_cache_digest
1957
    // keep the conservative runtime-filter guard.
1958
    bool _condition_cache_digest_covers_current_split = false;
1959
    segment_v2::ConditionCache::ExternalCacheKey _condition_cache_key;
1960
    std::shared_ptr<std::vector<bool>> _condition_cache;
1961
    std::shared_ptr<ConditionCacheContext> _condition_cache_ctx;
1962
    int64_t _condition_cache_hit_count = 0;
1963
    bool _current_reader_reached_eof = false;
1964
    int64_t _remaining_table_level_count = -1;
1965
    int64_t _remaining_file_level_count = -1;
1966
    // True only after the active split selects a table-level row-count shortcut or successfully
1967
    // materializes COUNT rows from file metadata. FileScannerV2 uses this result, rather than the
1968
    // raw aggregate opcode, to keep adaptive batching enabled for normal row-scan fallbacks.
1969
    bool _current_split_uses_metadata_count = false;
1970
    // Snapshot supplied by FileScannerV2 for the active split. It gates every shortcut that emits
1971
    // irreversible aggregate rows, not only the table-level row-count shortcut in prepare_split().
1972
    bool _all_runtime_filters_applied_for_split = true;
1973
    std::optional<GlobalRowIdContext> _global_rowid_context;
1974
    bool _aggregate_pushdown_tried = false;
1975
    bool _current_split_pruned = false;
1976
    TableColumnMapperOptions _mapper_options;
1977
1978
private:
1979
    static const ColumnDefinition* _find_column_definition(
1980
561k
            const std::vector<ColumnDefinition>& schema, LocalColumnId column_id) {
1981
10.1M
        for (const auto& field : schema) {
1982
10.1M
            if (field.file_local_id() == column_id.value()) {
1983
532k
                return &field;
1984
532k
            }
1985
10.1M
        }
1986
28.5k
        return nullptr;
1987
561k
    }
1988
1989
142
    static bool _can_push_down_minmax_for_mapping(const ColumnMapping& mapping) {
1990
142
        if (mapping.child_mappings.empty()) {
1991
            // Direct mappings use a slot-ref projection to materialize the file column. The
1992
            // projection does not transform ordering; casts and other conversions are already
1993
            // represented by a non-trivial mapping and must fall back to row scanning.
1994
139
            return mapping.is_trivial;
1995
139
        }
1996
3
        const auto primitive_type = remove_nullable(mapping.file_type)->get_primitive_type();
1997
3
        if (primitive_type != TYPE_STRUCT) {
1998
1
            return false;
1999
1
        }
2000
2
        size_t mapped_children = 0;
2001
2
        const ColumnMapping* mapped_child = nullptr;
2002
2
        for (const auto& child_mapping : mapping.child_mappings) {
2003
2
            if (!child_mapping.file_local_id.has_value()) {
2004
0
                continue;
2005
0
            }
2006
2
            ++mapped_children;
2007
2
            mapped_child = &child_mapping;
2008
2
        }
2009
2
        return mapped_children == 1 && mapped_child != nullptr &&
2010
2
               _can_push_down_minmax_for_mapping(*mapped_child);
2011
3
    }
2012
2013
    static Status build_aggregate_projection(const ColumnMapping& mapping,
2014
2
                                             LocalColumnIndex* projection) {
2015
2
        DORIS_CHECK(projection != nullptr);
2016
2
        DORIS_CHECK(mapping.file_local_id.has_value());
2017
2
        *projection = LocalColumnIndex::local(*mapping.file_local_id);
2018
2
        projection->children.clear();
2019
2
        projection->project_all_children = true;
2020
2
        if (mapping.child_mappings.empty()) {
2021
1
            return Status::OK();
2022
1
        }
2023
1
        projection->project_all_children = false;
2024
1
        for (const auto& child_mapping : mapping.child_mappings) {
2025
1
            if (!child_mapping.file_local_id.has_value()) {
2026
0
                continue;
2027
0
            }
2028
1
            LocalColumnIndex child_projection;
2029
1
            RETURN_IF_ERROR(build_aggregate_projection(child_mapping, &child_projection));
2030
1
            projection->children.push_back(std::move(child_projection));
2031
1
        }
2032
1
        DORIS_CHECK(projection->children.size() == 1);
2033
1
        return Status::OK();
2034
1
    }
2035
2036
    static Status _insert_aggregate_projection_value(const LocalColumnIndex& projection,
2037
108
                                                     const Field& value, IColumn* column) {
2038
108
        DORIS_CHECK(column != nullptr);
2039
108
        if (auto* nullable_column = check_and_get_column<ColumnNullable>(*column)) {
2040
54
            RETURN_IF_ERROR(_insert_aggregate_projection_value(
2041
54
                    projection, value, &nullable_column->get_nested_column()));
2042
54
            nullable_column->get_null_map_data().push_back(0);
2043
54
            return Status::OK();
2044
54
        }
2045
54
        if (projection.project_all_children || projection.children.empty()) {
2046
52
            column->insert(value);
2047
52
            return Status::OK();
2048
52
        }
2049
2
        auto* struct_column = assert_cast<ColumnStruct*>(column);
2050
2
        DORIS_CHECK(projection.children.size() == 1);
2051
2
        const auto& child_projection = projection.children[0];
2052
2
        DORIS_CHECK(struct_column->get_columns().size() == 1);
2053
2
        RETURN_IF_ERROR(_insert_aggregate_projection_value(child_projection, value,
2054
2
                                                           &struct_column->get_column(0)));
2055
2
        return Status::OK();
2056
2
    }
2057
2058
    // Parse a DV into its compressed bitmap. Position delete files continue to use _delete_rows.
2059
    Status _parse_delete_predicates(const SplitReadOptions& options);
2060
};
2061
2062
} // namespace doris::format