Coverage Report

Created: 2026-09-24 14:26

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