Coverage Report

Created: 2026-09-09 18:17

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