Coverage Report

Created: 2026-11-04 15:53

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