Coverage Report

Created: 2026-11-02 06:32

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