Coverage Report

Created: 2026-11-03 11:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/table/iceberg_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 <memory>
21
#include <optional>
22
#include <string>
23
#include <unordered_map>
24
#include <vector>
25
26
#include "common/status.h"
27
#include "core/block/block.h"
28
#include "format/table/iceberg_delete_file_reader_helper.h"
29
#include "format_v2/file_reader.h"
30
#include "format_v2/table/iceberg_schema_utils.h"
31
#include "format_v2/table_reader.h"
32
#include "gen_cpp/PlanNodes_types.h"
33
34
namespace doris {
35
class Block;
36
class EqualityDeleteHashIndex;
37
struct DeleteFileDesc;
38
namespace io {
39
struct FileDescription;
40
struct FileSystemProperties;
41
} // namespace io
42
} // namespace doris
43
44
namespace doris::format::iceberg {
45
46
Status prepare_iceberg_initial_default_exprs(format::ColumnDefinition* column);
47
48
// Iceberg table-level reader.
49
// It reuses TableReader for split orchestration, dynamic partition pruning and table-block
50
// finalization, while composing a FileReader for physical data-file reads instead of inheriting
51
// from a concrete file-format reader.
52
class IcebergTableReader : public format::TableReader {
53
public:
54
257
    ~IcebergTableReader() override = default;
55
    static Status validate_variant_file_mappings(
56
            FileFormat format, const std::vector<format::ColumnMapping>& mappings);
57
227
    Status init(format::TableReadOptions&& options) override {
58
227
        RETURN_IF_ERROR(format::TableReader::init(std::move(options)));
59
227
        _mapper_options.mode = format::TableColumnMappingMode::BY_FIELD_ID;
60
227
        _mapper_options.reject_missing_required_field =
61
227
                supports_iceberg_scan_semantics_v2(_scan_params);
62
227
        return Status::OK();
63
227
    }
64
65
    Status prepare_split(const format::SplitReadOptions& options) override;
66
    Status annotate_projected_column(const TFileScanSlotInfo& slot_info,
67
                                     format::ProjectedColumnBuildContext* context,
68
                                     format::ColumnDefinition* column) const override;
69
    std::string debug_string() const override;
70
511
    format::TableColumnMappingMode mapping_mode() const override {
71
511
        return _mapping_mode(_data_reader.file_schema);
72
511
    }
73
74
protected:
75
    // Iceberg UUID uses the same 16-byte STRING/VARBINARY carrier in data, defaults and deletes.
76
318
    bool preserve_binary_uuid() const override { return true; }
77
78
    Status validate_file_mapping(const format::TableColumnMapper& mapper) const override;
79
80
    // Iceberg's Parquet reader resolves a data file that carries no field ids at all through the
81
    // table's `schema.name-mapping.default`; when that mapping is absent it falls back to
82
    // positional ids (ParquetSchemaUtil.addFallbackIds + pruneColumnsFallback, gated by
83
    // `iceberg.netflix.unsafe-parquet-id-fallback.enabled`, default true through 1.12 and
84
    // scheduled for removal in 2.0). Mirror that decision for Parquet by stamping ordinal ids
85
    // (1..N) on the file's top-level fields, so the shared BY_FIELD_ID path resolves those files
86
    // instead of silently materializing NULL. Only top-level fields are stamped: Iceberg assigns
87
    // no ids to nested fields, so struct children of an id-less file stay unreadable without a
88
    // name mapping (or a rewrite that persists field ids).
89
    Status annotate_file_schema(std::vector<format::ColumnDefinition>* file_schema) override;
90
91
    // Iceberg's positional fallback matches an ID-less Parquet file by physical ordinals, so the
92
    // same table column can bind a different file column when the table's
93
    // `schema.name-mapping.default` is added or removed without touching the data file. The
94
    // condition cache key covers the file identity and the table-level predicate digest only, so it
95
    // cannot tell those bindings apart; keep such splits out of the cache (neither read nor
96
    // written) instead of reusing a verdict produced by the other binding.
97
    bool _should_enable_condition_cache(
98
254
            const format::FileScanRequest& file_request) const override {
99
254
        return !_positional_id_fallback &&
100
254
               format::TableReader::_should_enable_condition_cache(file_request);
101
254
    }
102
103
258
    void configure_mapper_options(format::TableColumnMapperOptions* options) const override {
104
258
        options->enable_row_lineage_virtual_columns = true;
105
258
        options->enable_iceberg_metadata_virtual_columns = true;
106
258
        options->reject_missing_required_field = supports_iceberg_scan_semantics_v2(_scan_params);
107
258
        options->allow_idless_complex_wrapper_projection =
108
258
                supports_iceberg_scan_semantics_v1(_scan_params) && _format == FileFormat::PARQUET;
109
258
    }
110
111
    Status materialize_virtual_columns(Block* table_block) override;
112
113
    Status customize_file_scan_request(format::FileScanRequest* file_request) override;
114
115
    bool _supports_aggregate_pushdown(TPushAggOp::type agg_type) const override;
116
117
    Status _parse_deletion_vector_file(const TTableFormatFileDesc& t_desc, DeleteFileDesc* desc,
118
                                       bool* has_delete_file) override;
119
120
    Status _init_delete_predicates(const TTableFormatFileDesc& t_desc);
121
122
private:
123
    struct EqualityDeleteFilter;
124
    static constexpr int MIN_SUPPORT_DELETE_FILES_VERSION = 2;
125
    static constexpr int POSITION_DELETE = 1;
126
    static constexpr int EQUALITY_DELETE = 2;
127
    static constexpr int DELETION_VECTOR = 3;
128
129
    struct RowLineageColumns {
130
        int64_t first_row_id = -1;
131
        int64_t last_updated_sequence_number = -1;
132
    };
133
134
    static constexpr const char* ICEBERG_FILE_PATH = "file_path";
135
    static constexpr const char* ICEBERG_ROW_POS = "pos";
136
    static constexpr size_t ICEBERG_FILE_PATH_BLOCK_POSITION = 0;
137
    static constexpr size_t ICEBERG_ROW_POS_BLOCK_POSITION = 1;
138
139
    bool _scan_has_any_authoritative_name_mapping() const;
140
    // annotate_file_schema() runs before TableReader stores the file schema, so the mode is also
141
    // computable from the schema being annotated.
142
    format::TableColumnMappingMode _mapping_mode(
143
719
            const std::vector<format::ColumnDefinition>& file_schema) const {
144
719
        const bool has_field_ids = supports_iceberg_scan_semantics_v1(_scan_params)
145
719
                                           ? schema_has_any_field_id(file_schema)
146
719
                                           : schema_has_all_field_ids(file_schema);
147
719
        if (!file_schema.empty() && has_field_ids) {
148
654
            return format::TableColumnMappingMode::BY_FIELD_ID;
149
654
        }
150
65
        if (!file_schema.empty() && supports_iceberg_scan_semantics_v2(_scan_params) &&
151
65
            !_scan_has_any_authoritative_name_mapping()) {
152
            // ID-less migrated files are name-readable only while Iceberg's explicit default name
153
            // mapping exists; current names must not resurrect file fields after it is removed.
154
1
            return format::TableColumnMappingMode::BY_FIELD_ID;
155
1
        }
156
64
        return format::TableColumnMappingMode::BY_NAME;
157
65
    }
158
    void _apply_positional_id_fallback(std::vector<format::ColumnDefinition>* file_schema);
159
    Status _apply_table_timestamp_semantics(std::vector<format::ColumnDefinition>* file_schema,
160
                                            format::TableColumnMappingMode mode) const;
161
162
    class PositionDeleteRowsCollector final {
163
    public:
164
        using PositionDeleteFile = std::unordered_map<std::string, format::DeleteRows>;
165
166
        explicit PositionDeleteRowsCollector(PositionDeleteFile* rows_by_data_file);
167
168
        Status collect(const Block& block, size_t read_rows);
169
170
    private:
171
        PositionDeleteFile* _rows_by_data_file = nullptr;
172
    };
173
174
    static std::shared_ptr<io::FileSystemProperties> _delete_file_system_properties(
175
            const TFileScanRangeParams& scan_params);
176
177
    static std::unique_ptr<io::FileDescription> _delete_file_description(
178
            const TFileRangeDesc& range);
179
180
    std::string _data_file_path() const;
181
182
    // Append row position column to file scan request for position delete handling.
183
    Status _append_row_position_output_column(format::FileScanRequest* request);
184
    // Append equality delete predicates to file scan request based on the delete files in iceberg
185
    // params. DeleteVector and position delete files use the common DeleteRows path in TableReader.
186
    using EqualityDeleteColumnPath = std::vector<const format::ColumnDefinition*>;
187
    Status _append_equality_delete_predicates(format::FileScanRequest* request);
188
    Status _build_missing_equality_delete_key_expr(const EqualityDeleteFilter& filter,
189
                                                   size_t key_idx,
190
                                                   const EqualityDeleteColumnPath& data_path,
191
                                                   format::FileScanRequest* request,
192
                                                   VExprSPtr* key_expr,
193
                                                   DataTypePtr* comparison_type);
194
    // Returns `filter` with its delete keys converted to `comparison_types`, cached per scanner.
195
    Status _convert_equality_delete_filter(const EqualityDeleteFilter& filter,
196
                                           const DataTypes& comparison_types,
197
                                           EqualityDeleteFilter* result);
198
    Status _build_converted_equality_delete_filter(const EqualityDeleteFilter& filter,
199
                                                   const DataTypes& comparison_types,
200
                                                   EqualityDeleteFilter* result) const;
201
    Status _find_equality_delete_data_field(const EqualityDeleteFilter& filter, size_t key_idx,
202
                                            EqualityDeleteColumnPath* data_path,
203
                                            bool* complete_path) const;
204
    Status _find_equality_delete_table_field(const EqualityDeleteFilter& filter, size_t key_idx,
205
                                             format::ColumnDefinition* table_field) const;
206
    void _append_equality_delete_row_count_carrier(format::FileScanRequest* request);
207
    std::string _delete_file_cache_key(const char* prefix, const std::string& path) const;
208
209
    Status _init_equality_delete_predicates(
210
            const std::vector<TIcebergDeleteFileDesc>& delete_files);
211
212
    // Read equality/position delete files.
213
    Status _create_delete_file_reader(const TIcebergDeleteFileDesc& delete_file,
214
                                      const TFileScanRangeParams& scan_params,
215
                                      IcebergDeleteFileIOContext* delete_io_ctx,
216
                                      std::unique_ptr<format::FileReader>* reader);
217
    Status _read_equality_delete_file(const TIcebergDeleteFileDesc& delete_file,
218
                                      const TFileScanRangeParams& scan_params,
219
                                      IcebergDeleteFileIOContext* delete_io_ctx);
220
    Status _load_equality_delete_file(const TIcebergDeleteFileDesc& delete_file,
221
                                      const TFileScanRangeParams& scan_params,
222
                                      IcebergDeleteFileIOContext* delete_io_ctx,
223
                                      EqualityDeleteFilter* result);
224
    Status _resolve_equality_delete_fields(const TIcebergDeleteFileDesc& delete_file,
225
                                           const std::vector<format::ColumnDefinition>& schema,
226
                                           std::vector<EqualityDeleteColumnPath>* delete_paths,
227
                                           EqualityDeleteFilter* result) const;
228
    Status _read_position_delete_file(const TIcebergDeleteFileDesc& delete_file,
229
                                      const TFileScanRangeParams& scan_params,
230
                                      IcebergDeleteFileIOContext* delete_io_ctx,
231
                                      PositionDeleteRowsCollector* collector);
232
233
    // Read position delete files and collect deleted row positions to update DeletePredicate.
234
    Status _init_position_delete_rows(const std::vector<TIcebergDeleteFileDesc>& delete_files);
235
236
    // Materialize row lineage virtual columns based on the position delete file.
237
    Status _materialize_iceberg_rowid(Block* table_block, size_t column_idx);
238
    Status _materialize_iceberg_file_path(Block* table_block, size_t column_idx);
239
    Status _materialize_iceberg_row_position(Block* table_block, size_t column_idx);
240
    Status _materialize_row_lineage_row_id(Block* table_block, size_t column_idx);
241
    Status _materialize_row_lineage_last_updated_sequence_number(Block* table_block,
242
                                                                 size_t column_idx);
243
244
    RowLineageColumns _row_lineage_columns;
245
    size_t _row_position_block_position = 0;
246
    std::optional<TIcebergFileDesc> _iceberg_params;
247
    bool _delete_predicates_initialized = false;
248
    // Set when this split's Parquet file carried no field ids and the table exposed no usable name
249
    // mapping, so the reader stamped Iceberg's positional fallback ids on the file's top-level
250
    // fields. Observability only; the decision itself lives in annotate_file_schema().
251
    bool _positional_id_fallback = false;
252
    format::DeleteRows _position_delete_rows_storage;
253
    struct EqualityDeleteFilter {
254
        std::vector<int> field_ids;
255
        // Delete-file names are retained for Iceberg tables imported from formats that did not
256
        // persist field ids. In BY_NAME mode they are the fallback binding key.
257
        std::vector<std::string> field_names;
258
        // Table-side types of the keys, from the scan's schema metadata. They resolve table
259
        // fields and build defaults for keys a data file lacks. The comparison type comes from
260
        // the file types; a table type only lets a timestamptz key read as DATETIMEV2 compare
261
        // as TIMESTAMPTZ, and a STRING placeholder (an Iceberg TIME or timestamptz_ns, which
262
        // Doris cannot represent) lets an ORC TIME key and its text default compare as TIMEV2.
263
        std::vector<DataTypePtr> key_types;
264
        // Types of the delete block columns: the delete file's own key types, or the comparison
265
        // types of a converted filter.
266
        std::vector<DataTypePtr> delete_key_types;
267
        Block delete_block;
268
        std::shared_ptr<const EqualityDeleteHashIndex> hash_index;
269
        // Split-cache key of this filter, extended by the comparison types for converted copies.
270
        std::string cache_key;
271
    };
272
    std::vector<EqualityDeleteFilter> _equality_delete_filters;
273
    // Scanner-shared cache supplied in SplitReadOptions. Parsed delete files outlive one data-file
274
    // split and can be reused by every split referencing the same delete file.
275
    ShardedKVCache* _split_cache = nullptr;
276
277
    bool _need_row_lineage_row_id() const;
278
    bool _need_iceberg_rowid() const;
279
    bool _need_iceberg_metadata() const;
280
};
281
282
} // namespace doris::format::iceberg