From b4c2598a2e72f66b1cf145c3d48c1897cc0e72ef Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Wed, 28 Oct 2026 18:47:17 +0800 Subject: [PATCH 01/11] feat(read): materialize partition columns from file scan tasks --- src/iceberg/avro/avro_data_util.cc | 27 +++- src/iceberg/avro/avro_direct_decoder.cc | 3 +- src/iceberg/avro/avro_reader.cc | 5 +- src/iceberg/avro/avro_schema_util.cc | 61 +++++---- src/iceberg/avro/avro_schema_util_internal.h | 4 +- src/iceberg/catalog/rest/json_serde.cc | 9 +- src/iceberg/catalog/rest/rest_table_scan.cc | 6 +- src/iceberg/data/file_scan_task_reader.cc | 83 ++++++++++-- src/iceberg/file_reader.h | 16 +++ src/iceberg/json_serde.cc | 2 +- src/iceberg/manifest/manifest_group.cc | 3 +- src/iceberg/parquet/parquet_data_util.cc | 15 ++- src/iceberg/parquet/parquet_reader.cc | 12 +- src/iceberg/parquet/parquet_schema_util.cc | 14 +- .../parquet/parquet_schema_util_internal.h | 4 +- src/iceberg/schema_util.cc | 46 +++++++ src/iceberg/schema_util.h | 5 + src/iceberg/table_scan.cc | 17 ++- src/iceberg/table_scan.h | 14 +- src/iceberg/test/avro_test.cc | 25 ++++ .../test/file_scan_task_reader_test.cc | 123 ++++++++++++++++++ src/iceberg/test/manifest_group_test.cc | 4 + src/iceberg/test/parquet_test.cc | 19 +++ src/iceberg/test/rest_json_serde_test.cc | 2 + 24 files changed, 447 insertions(+), 72 deletions(-) diff --git a/src/iceberg/avro/avro_data_util.cc b/src/iceberg/avro/avro_data_util.cc index 5c6c19decf..622cde5840 100644 --- a/src/iceberg/avro/avro_data_util.cc +++ b/src/iceberg/avro/avro_data_util.cc @@ -94,7 +94,8 @@ Status AppendStructToBuilder(const ::avro::NodePtr& avro_node, metadata_context, field_builder)); } else if (field_projection.kind == FieldProjection::Kind::kNull) { ICEBERG_ARROW_RETURN_NOT_OK(field_builder->AppendNull()); - } else if (field_projection.kind == FieldProjection::Kind::kDefault) { + } else if (field_projection.kind == FieldProjection::Kind::kDefault || + field_projection.kind == FieldProjection::Kind::kConstant) { ICEBERG_RETURN_UNEXPECTED(AppendDefaultToBuilder(field_projection, field_builder)); } else if (field_projection.kind == FieldProjection::Kind::kMetadata) { int32_t field_id = expected_field.field_id(); @@ -477,7 +478,8 @@ Status AppendFieldToBuilder(const ::avro::NodePtr& avro_node, return {}; } - if (projection.kind == FieldProjection::Kind::kDefault) { + if (projection.kind == FieldProjection::Kind::kDefault || + projection.kind == FieldProjection::Kind::kConstant) { return AppendDefaultToBuilder(projection, array_builder); } @@ -594,7 +596,13 @@ Status PrepareStructDefaultScalars(std::span projections, auto& field_projection = projections[i]; auto* field_builder = struct_builder->field_builder(static_cast(i)); - if (field_projection.kind == FieldProjection::Kind::kDefault) { + if (field_projection.kind == FieldProjection::Kind::kDefault || + field_projection.kind == FieldProjection::Kind::kConstant) { + if (field_builder->type()->id() == ::arrow::Type::STRUCT) { + ICEBERG_RETURN_UNEXPECTED( + PrepareStructDefaultScalars(field_projection.children, field_builder)); + continue; + } // Get-or-create the single Avro attributes container: another Avro attribute may // have created it already, so guard on `default_scalar` being unset rather than on // the container's presence (otherwise a pre-existing container would skip @@ -641,6 +649,19 @@ Status AppendDefaultToBuilder(const Literal& literal, ::arrow::ArrayBuilder* bui Status AppendDefaultToBuilder(const FieldProjection& projection, ::arrow::ArrayBuilder* builder) { + if (projection.kind == FieldProjection::Kind::kNull) { + ICEBERG_ARROW_RETURN_NOT_OK(builder->AppendNull()); + return {}; + } + if (builder->type()->id() == ::arrow::Type::STRUCT) { + auto* struct_builder = internal::checked_cast<::arrow::StructBuilder*>(builder); + ICEBERG_ARROW_RETURN_NOT_OK(struct_builder->Append()); + for (size_t i = 0; i < projection.children.size(); ++i) { + ICEBERG_RETURN_UNEXPECTED(AppendDefaultToBuilder( + projection.children[i], struct_builder->field_builder(static_cast(i)))); + } + return {}; + } // Avro projections carry a single attributes type, so once one is attached it is an // AvroExtraAttributes; use checked_cast instead of a per-row dynamic_cast. if (projection.attributes != nullptr) { diff --git a/src/iceberg/avro/avro_direct_decoder.cc b/src/iceberg/avro/avro_direct_decoder.cc index c2d0a3c9c3..42ae3f13b2 100644 --- a/src/iceberg/avro/avro_direct_decoder.cc +++ b/src/iceberg/avro/avro_direct_decoder.cc @@ -216,7 +216,8 @@ Status DecodeStructToBuilder(const ::avro::NodePtr& avro_node, ::avro::Decoder& auto* field_builder = struct_builder->field_builder(static_cast(proj_idx)); if (field_projection.kind == FieldProjection::Kind::kNull) { ICEBERG_ARROW_RETURN_NOT_OK(field_builder->AppendNull()); - } else if (field_projection.kind == FieldProjection::Kind::kDefault) { + } else if (field_projection.kind == FieldProjection::Kind::kDefault || + field_projection.kind == FieldProjection::Kind::kConstant) { ICEBERG_RETURN_UNEXPECTED(AppendDefaultToBuilder(field_projection, field_builder)); } else if (field_projection.kind == FieldProjection::Kind::kMetadata) { int32_t field_id = expected_field.field_id(); diff --git a/src/iceberg/avro/avro_reader.cc b/src/iceberg/avro/avro_reader.cc index 06d536e7dc..051d9e49a7 100644 --- a/src/iceberg/avro/avro_reader.cc +++ b/src/iceberg/avro/avro_reader.cc @@ -349,8 +349,9 @@ class AvroReader::Impl { } // Project the read schema on top of the file schema. - ICEBERG_ASSIGN_OR_RAISE(projection_, Project(*read_schema_, file_schema.root(), - /*prune_source=*/false)); + ICEBERG_ASSIGN_OR_RAISE(projection_, + Project(*read_schema_, file_schema.root(), + /*prune_source=*/false, options.constants)); ICEBERG_RETURN_UNEXPECTED(backend_->InitWithSchema(file_schema, options.split)); diff --git a/src/iceberg/avro/avro_schema_util.cc b/src/iceberg/avro/avro_schema_util.cc index 94d0a6116b..819b4e2641 100644 --- a/src/iceberg/avro/avro_schema_util.cc +++ b/src/iceberg/avro/avro_schema_util.cc @@ -685,12 +685,13 @@ Status UnwrapUnion(const ::avro::NodePtr& node, ::avro::NodePtr* result) { // Forward declaration Result ProjectNested(const Type& expected_type, - const ::avro::NodePtr& avro_node, - bool prune_source); + const ::avro::NodePtr& avro_node, bool prune_source, + const ColumnConstants& constants); Result ProjectField(const SchemaField& expected_field, const ::avro::NodePtr& avro_node, - size_t source_index, bool prune_source) { + size_t source_index, bool prune_source, + const ColumnConstants& constants) { const Type& expected_type = *expected_field.type(); ::avro::NodePtr field_node; ICEBERG_RETURN_UNEXPECTED(UnwrapUnion(avro_node, &field_node)); @@ -707,8 +708,8 @@ Result ProjectField(const SchemaField& expected_field, } if (expected_type.is_nested()) { - ICEBERG_ASSIGN_OR_RAISE(projection, - ProjectNested(expected_type, field_node, prune_source)); + ICEBERG_ASSIGN_OR_RAISE( + projection, ProjectNested(expected_type, field_node, prune_source, constants)); } else { ICEBERG_RETURN_UNEXPECTED(ValidateAvroSchemaEvolution(expected_type, field_node)); } @@ -718,8 +719,8 @@ Result ProjectField(const SchemaField& expected_field, } Result ProjectStruct(const StructType& struct_type, - const ::avro::NodePtr& avro_node, - bool prune_source) { + const ::avro::NodePtr& avro_node, bool prune_source, + const ColumnConstants& constants) { if (avro_node->type() != ::avro::AVRO_RECORD) { return InvalidSchema("Expected AVRO_RECORD type, but got {}", ToString(avro_node)); } @@ -752,9 +753,13 @@ Result ProjectStruct(const StructType& struct_type, FieldProjection child_projection; if (auto iter = node_info_map.find(field_id); iter != node_info_map.cend()) { + ICEBERG_ASSIGN_OR_RAISE( + child_projection, + ProjectField(expected_field, iter->second.field_node, iter->second.local_index, + prune_source, constants)); + } else if (auto constant = constants.find(field_id); constant != constants.end()) { ICEBERG_ASSIGN_OR_RAISE(child_projection, - ProjectField(expected_field, iter->second.field_node, - iter->second.local_index, prune_source)); + ProjectConstant(expected_field, constant->second)); } else if (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (expected_field.initial_default() != nullptr) { @@ -778,7 +783,8 @@ Result ProjectStruct(const StructType& struct_type, } Result ProjectList(const ListType& list_type, - const ::avro::NodePtr& avro_node, bool prune_source) { + const ::avro::NodePtr& avro_node, bool prune_source, + const ColumnConstants& constants) { if (avro_node->type() != ::avro::AVRO_ARRAY) { return InvalidSchema("Expected AVRO_ARRAY type, but got {}", ToString(avro_node)); } @@ -795,9 +801,10 @@ Result ProjectList(const ListType& list_type, } FieldProjection element_projection; - ICEBERG_ASSIGN_OR_RAISE(element_projection, - ProjectField(expected_element_field, avro_node->leafAt(0), - /*source_index*/ size_t{0}, prune_source)); + ICEBERG_ASSIGN_OR_RAISE( + element_projection, + ProjectField(expected_element_field, avro_node->leafAt(0), + /*source_index*/ size_t{0}, prune_source, constants)); FieldProjection result; result.children.emplace_back(std::move(element_projection)); @@ -805,7 +812,8 @@ Result ProjectList(const ListType& list_type, } Result ProjectMap(const MapType& map_type, - const ::avro::NodePtr& avro_node, bool prune_source) { + const ::avro::NodePtr& avro_node, bool prune_source, + const ColumnConstants& constants) { const auto& expected_key_field = map_type.key(); const auto& expected_value_field = map_type.value(); @@ -854,9 +862,9 @@ Result ProjectMap(const MapType& map_type, for (size_t i = 0; i < map_node->leaves(); ++i) { FieldProjection sub_projection; const auto& expected_sub_field = map_type.fields()[i]; - ICEBERG_ASSIGN_OR_RAISE( - sub_projection, - ProjectField(expected_sub_field, map_node->leafAt(i), i, prune_source)); + ICEBERG_ASSIGN_OR_RAISE(sub_projection, + ProjectField(expected_sub_field, map_node->leafAt(i), i, + prune_source, constants)); result.children.emplace_back(std::move(sub_projection)); } @@ -864,8 +872,8 @@ Result ProjectMap(const MapType& map_type, } Result ProjectNested(const Type& expected_type, - const ::avro::NodePtr& avro_node, - bool prune_source) { + const ::avro::NodePtr& avro_node, bool prune_source, + const ColumnConstants& constants) { if (!expected_type.is_nested()) { return InvalidSchema("Expected a nested type, but got {}", expected_type); } @@ -873,13 +881,13 @@ Result ProjectNested(const Type& expected_type, switch (expected_type.type_id()) { case TypeId::kStruct: return ProjectStruct(internal::checked_cast(expected_type), - avro_node, prune_source); + avro_node, prune_source, constants); case TypeId::kList: return ProjectList(internal::checked_cast(expected_type), - avro_node, prune_source); + avro_node, prune_source, constants); case TypeId::kMap: return ProjectMap(internal::checked_cast(expected_type), avro_node, - prune_source); + prune_source, constants); default: return InvalidSchema("Unsupported nested type: {}", expected_type); } @@ -894,10 +902,11 @@ bool HasMapLogicalType(const ::avro::NodePtr& node) { } Result Project(const Schema& expected_schema, - const ::avro::NodePtr& avro_node, bool prune_source) { - ICEBERG_ASSIGN_OR_RAISE( - auto field_projection, - ProjectNested(static_cast(expected_schema), avro_node, prune_source)); + const ::avro::NodePtr& avro_node, bool prune_source, + const ColumnConstants& constants) { + ICEBERG_ASSIGN_OR_RAISE(auto field_projection, + ProjectNested(static_cast(expected_schema), + avro_node, prune_source, constants)); return SchemaProjection{std::move(field_projection.children)}; } diff --git a/src/iceberg/avro/avro_schema_util_internal.h b/src/iceberg/avro/avro_schema_util_internal.h index 342b119a53..7cc0012b5a 100644 --- a/src/iceberg/avro/avro_schema_util_internal.h +++ b/src/iceberg/avro/avro_schema_util_internal.h @@ -142,9 +142,11 @@ class HasIdVisitor { /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param avro_node The Avro node to read data from. /// \param prune_source Whether the source schema can be pruned. +/// \param constants File-level values used for fields absent from the file. /// \return The schema projection result. Result Project(const Schema& expected_schema, - const ::avro::NodePtr& avro_node, bool prune_source); + const ::avro::NodePtr& avro_node, bool prune_source, + const ColumnConstants& constants = {}); std::string ToString(const ::avro::NodePtr& node); std::string ToString(const ::avro::LogicalType& logical_type); diff --git a/src/iceberg/catalog/rest/json_serde.cc b/src/iceberg/catalog/rest/json_serde.cc index 7b862e7293..46edba4ab0 100644 --- a/src/iceberg/catalog/rest/json_serde.cc +++ b/src/iceberg/catalog/rest/json_serde.cc @@ -231,9 +231,16 @@ Result>> FileScanTasksFromJson( ICEBERG_ASSIGN_OR_RAISE(residual_filter, ExpressionFromJson(filter_json)); } + std::shared_ptr spec; + if (data_file.partition_spec_id.has_value()) { + auto it = partition_spec_by_id.find(*data_file.partition_spec_id); + if (it != partition_spec_by_id.end()) { + spec = it->second; + } + } auto task = FileScanTask::MakeSplit(std::make_shared(std::move(data_file)), start, length, std::move(task_delete_files), - std::move(residual_filter)); + std::move(residual_filter), std::move(spec)); if (!task) { return JsonParseError("Invalid FileScanTask range: {}", task.error().message); } diff --git a/src/iceberg/catalog/rest/rest_table_scan.cc b/src/iceberg/catalog/rest/rest_table_scan.cc index fa2bc67375..9ef9cdb74c 100644 --- a/src/iceberg/catalog/rest/rest_table_scan.cc +++ b/src/iceberg/catalog/rest/rest_table_scan.cc @@ -286,9 +286,9 @@ class RestFileScanTaskStream final : public FileScanTaskStream { // The server may leave row filtering to the client. ICEBERG_ASSIGN_OR_RAISE( task, - FileScanTask::MakeSplit(task->data_file(), task->start(), task->length(), - task->delete_files(), - ignore_residuals_ ? True::Instance() : filter_)); + FileScanTask::MakeSplit( + task->data_file(), task->start(), task->length(), task->delete_files(), + ignore_residuals_ ? True::Instance() : filter_, task->spec())); } return task; } diff --git a/src/iceberg/data/file_scan_task_reader.cc b/src/iceberg/data/file_scan_task_reader.cc index a277f507bf..728f340a25 100644 --- a/src/iceberg/data/file_scan_task_reader.cc +++ b/src/iceberg/data/file_scan_task_reader.cc @@ -35,24 +35,76 @@ #include "iceberg/expression/evaluator.h" #include "iceberg/file_reader.h" #include "iceberg/manifest/manifest_entry.h" +#include "iceberg/metadata_columns.h" #include "iceberg/nanoarrow_status_internal.h" +#include "iceberg/partition_spec.h" #include "iceberg/row/arrow_array_wrapper.h" #include "iceberg/schema.h" #include "iceberg/table_scan.h" +#include "iceberg/transform.h" #include "iceberg/util/macros.h" namespace iceberg { namespace { -ReaderOptions MakeReaderOptions(const FileScanTask& task, std::shared_ptr io, - std::shared_ptr projection, - std::shared_ptr filter, bool case_sensitive, - std::shared_ptr name_mapping, - ReaderProperties properties, - std::optional first_row_id, - std::optional data_sequence_number) { +Result ConstantsOf(const FileScanTask& task, const Schema& projection) { + const auto& file = *task.data_file(); + const auto& spec = task.spec(); + ICEBERG_ASSIGN_OR_RAISE(auto partition_field, + projection.FindFieldById(MetadataColumns::kPartitionColumnId)); + ICEBERG_ASSIGN_OR_RAISE(auto spec_field, + projection.FindFieldById(MetadataColumns::kSpecIdColumnId)); + ColumnConstants constants; + auto spec_id = file.partition_spec_id; + if (spec) { + if (spec_id.has_value() && *spec_id != spec->spec_id()) { + return InvalidArgument("Data file spec ID {} does not match task spec ID {}", + *spec_id, spec->spec_id()); + } + spec_id = spec->spec_id(); + if (file.partition.num_fields() != spec->fields().size()) { + return InvalidArgument( + "Partition value count {} does not match spec field count {}", + file.partition.num_fields(), spec->fields().size()); + } + StructConstant partition; + for (size_t i = 0; i < spec->fields().size(); ++i) { + const auto& field = spec->fields()[i]; + const auto& value = file.partition.values()[i]; + if (field.transform() == nullptr) { + return InvalidArgument("Missing transform for partition field {}", + field.field_id()); + } + if (field.transform()->transform_type() == TransformType::kIdentity) { + constants.emplace(field.source_id(), value); + } + if (partition_field.has_value()) { + partition.emplace(field.field_id(), value); + } + } + if (partition_field.has_value()) { + constants.emplace(MetadataColumns::kPartitionColumnId, std::move(partition)); + } + } else if (file.partition.num_fields() != 0 || partition_field.has_value()) { + return InvalidArgument("A partition spec is required to read partition values"); + } + if (spec_field.has_value()) { + if (!spec_id.has_value()) { + return InvalidArgument("A partition spec ID is required to read _spec_id"); + } + constants.emplace(MetadataColumns::kSpecIdColumnId, Literal::Int(*spec_id)); + } + return constants; +} + +Result MakeReaderOptions( + const FileScanTask& task, std::shared_ptr io, + std::shared_ptr projection, std::shared_ptr filter, bool case_sensitive, + std::shared_ptr name_mapping, ReaderProperties properties, + std::optional first_row_id, std::optional data_sequence_number) { const auto& data_file = *task.data_file(); + ICEBERG_ASSIGN_OR_RAISE(auto constants, ConstantsOf(task, *projection)); return ReaderOptions{ .path = data_file.file_path, .length = static_cast(data_file.file_size_in_bytes), @@ -68,6 +120,7 @@ ReaderOptions MakeReaderOptions(const FileScanTask& task, std::shared_ptrfirst_row_id, data_file->data_sequence_number); + ICEBERG_ASSIGN_OR_RAISE( + auto options, + MakeReaderOptions(task, io_, projected_schema_, filter, case_sensitive_, + name_mapping_, properties_, data_file->first_row_id, + data_file->data_sequence_number)); ICEBERG_ASSIGN_OR_RAISE( auto reader, ReaderFactoryRegistry::Open(data_file->file_format, options)); return MakeArrowArrayStream(std::move(reader)); @@ -287,9 +342,11 @@ class FileScanTaskReader::Impl { required_schema = delete_filter->RequiredSchema(); } - auto options = MakeReaderOptions(task, io_, required_schema, filter, case_sensitive_, - name_mapping_, properties_, data_file->first_row_id, - data_file->data_sequence_number); + ICEBERG_ASSIGN_OR_RAISE( + auto options, + MakeReaderOptions(task, io_, required_schema, filter, case_sensitive_, + name_mapping_, properties_, data_file->first_row_id, + data_file->data_sequence_number)); ICEBERG_ASSIGN_OR_RAISE(auto reader, ReaderFactoryRegistry::Open(data_file->file_format, options)); diff --git a/src/iceberg/file_reader.h b/src/iceberg/file_reader.h index 00fc2583d2..76b0ff23d6 100644 --- a/src/iceberg/file_reader.h +++ b/src/iceberg/file_reader.h @@ -26,8 +26,11 @@ #include #include #include +#include +#include #include "iceberg/arrow_c_data.h" +#include "iceberg/expression/literal.h" #include "iceberg/file_format.h" #include "iceberg/result.h" #include "iceberg/type_fwd.h" @@ -103,6 +106,14 @@ class ICEBERG_EXPORT ReaderProperties : public ConfigBase { const std::unordered_map& properties); }; +/// A non-null struct constant, keyed by child field ID. Children are primitive +/// literals, including typed nulls. Projected children absent from the map are null. +using StructConstant = std::unordered_map; + +/// A file-level primitive or struct constant, independent of the file format. +using ColumnConstant = std::variant; +using ColumnConstants = std::unordered_map; + /// \brief Options for creating a reader. struct ICEBERG_EXPORT ReaderOptions { /// \brief The path to the file to read. @@ -129,6 +140,11 @@ struct ICEBERG_EXPORT ReaderOptions { std::optional data_sequence_number; /// \brief Format-specific or implementation-specific properties. ReaderProperties properties; + + /// File-level values keyed by field ID, used when physical columns are absent. + /// Constants precede initial defaults and optional-field nulls. + /// Example: `options.constants.emplace(2, Literal::String("CN"));` + ColumnConstants constants; }; /// \brief Factory function to create a reader of a specific file format. diff --git a/src/iceberg/json_serde.cc b/src/iceberg/json_serde.cc index 1ea1469012..b47a35fd84 100644 --- a/src/iceberg/json_serde.cc +++ b/src/iceberg/json_serde.cc @@ -2554,7 +2554,7 @@ Result> FileScanTaskFromJson(const nlohmann::json& auto task = FileScanTask::MakeSplit(std::make_shared(std::move(data_file)), start, length, std::move(delete_files), - std::move(residual_filter)); + std::move(residual_filter), std::move(shared_spec)); if (!task) { return JsonParseError("Invalid FileScanTask range: {}", task.error().message); } diff --git a/src/iceberg/manifest/manifest_group.cc b/src/iceberg/manifest/manifest_group.cc index 036a71bdcb..883fd770ef 100644 --- a/src/iceberg/manifest/manifest_group.cc +++ b/src/iceberg/manifest/manifest_group.cc @@ -320,7 +320,8 @@ class ManifestGroup::FilePlanningStream final : public FileScanTaskStream { residuals->ResidualFor(value.data_file->partition)); return std::optional>{std::make_shared( - std::move(value.data_file), std::move(delete_files), std::move(residual))}; + std::move(value.data_file), std::move(delete_files), std::move(residual), + group_->specs_by_id_.at(spec_id))}; } } diff --git a/src/iceberg/parquet/parquet_data_util.cc b/src/iceberg/parquet/parquet_data_util.cc index b5024c4867..dda5370164 100644 --- a/src/iceberg/parquet/parquet_data_util.cc +++ b/src/iceberg/parquet/parquet_data_util.cc @@ -252,7 +252,20 @@ Result> ProjectStructArray( projected_array, ProjectPrimitiveArray(parquet_array, output_arrow_type, pool)); } - } else if (field_projection.kind == FieldProjection::Kind::kDefault) { + } else if (field_projection.kind == FieldProjection::Kind::kConstant && + projected_field.type()->type_id() == TypeId::kStruct) { + // An empty source struct supplies the batch length; children come entirely + // from the constant projection and retain the requested field IDs/order. + auto source = std::make_shared<::arrow::StructArray>( + ::arrow::struct_({}), struct_array->length(), ::arrow::ArrayVector{}); + ICEBERG_ASSIGN_OR_RAISE( + projected_array, + ProjectNestedArray( + source, output_arrow_type, + internal::checked_cast(*projected_field.type()), + field_projection.children, metadata_context, row_positions, pool)); + } else if (field_projection.kind == FieldProjection::Kind::kDefault || + field_projection.kind == FieldProjection::Kind::kConstant) { ICEBERG_ASSIGN_OR_RAISE( projected_array, arrow::MakeDefaultArray(std::get(field_projection.from), diff --git a/src/iceberg/parquet/parquet_reader.cc b/src/iceberg/parquet/parquet_reader.cc index 3e5930f10f..27da5e888a 100644 --- a/src/iceberg/parquet/parquet_reader.cc +++ b/src/iceberg/parquet/parquet_reader.cc @@ -65,7 +65,8 @@ Result> OpenInputStream( Result BuildProjection(::parquet::arrow::FileReader* reader, const Schema& read_schema, - const NameMapping* name_mapping) { + const NameMapping* name_mapping, + const ColumnConstants& constants) { auto metadata = reader->parquet_reader()->metadata(); if (!HasFieldIds(metadata->schema()->schema_root())) { @@ -78,10 +79,10 @@ Result BuildProjection(::parquet::arrow::FileReader* reader, metadata->schema(), metadata->key_value_metadata(), reader->properties(), &schema_manifest)); ApplyNameMapping(*name_mapping, &schema_manifest); - return Project(read_schema, schema_manifest); + return Project(read_schema, schema_manifest, constants); } - ICEBERG_ASSIGN_OR_RAISE(auto projection, Project(read_schema, reader->manifest())); + ICEBERG_ASSIGN_OR_RAISE(auto projection, Project(read_schema, reader->manifest(), constants)); return projection; } @@ -158,8 +159,9 @@ class ParquetReader::Impl { arrow_reader_properties)); // Project read schema onto the Parquet file schema - ICEBERG_ASSIGN_OR_RAISE(projection_, BuildProjection(reader_.get(), *read_schema_, - options.name_mapping.get())); + ICEBERG_ASSIGN_OR_RAISE( + projection_, BuildProjection(reader_.get(), *read_schema_, + options.name_mapping.get(), options.constants)); if (options.filter && options.properties.Get(ReaderProperties::kParquetRowGroupFilter)) { auto filter = options.filter; diff --git a/src/iceberg/parquet/parquet_schema_util.cc b/src/iceberg/parquet/parquet_schema_util.cc index d16b8a1ae6..a6727e9eea 100644 --- a/src/iceberg/parquet/parquet_schema_util.cc +++ b/src/iceberg/parquet/parquet_schema_util.cc @@ -504,7 +504,9 @@ namespace { class ProjectionBuilder { public: - explicit ProjectionBuilder(const ::parquet::SchemaDescriptor* descr) : descr_(descr) {} + ProjectionBuilder(const ::parquet::SchemaDescriptor* descr, + const ColumnConstants& constants) + : descr_(descr), constants_(constants) {} Result Project( const Type& nested_type, @@ -592,6 +594,10 @@ class ProjectionBuilder { const auto& parquet_field = iter->second.parquet_field; ICEBERG_ASSIGN_OR_RAISE(child_projection, ProjectField(field, parquet_field, iter->second.local_index)); + } else if (auto constant = constants_.find(field_id); + constant != constants_.end()) { + ICEBERG_ASSIGN_OR_RAISE(child_projection, + ProjectConstant(field, constant->second)); } else if (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (field.initial_default() != nullptr) { @@ -719,6 +725,7 @@ class ProjectionBuilder { } const ::parquet::SchemaDescriptor* descr_; + const ColumnConstants& constants_; }; void CollectColumnIds(const FieldProjection& field_projection, @@ -784,8 +791,9 @@ void ApplyNameMappingToField(const NameMapping& mapping, std::vector Project(const Schema& expected_schema, - const ::parquet::arrow::SchemaManifest& parquet_schema) { - ProjectionBuilder builder(parquet_schema.descr); + const ::parquet::arrow::SchemaManifest& parquet_schema, + const ColumnConstants& constants) { + ProjectionBuilder builder(parquet_schema.descr, constants); ICEBERG_ASSIGN_OR_RAISE(auto field_projection, builder.Project(static_cast(expected_schema), parquet_schema.schema_fields)); diff --git a/src/iceberg/parquet/parquet_schema_util_internal.h b/src/iceberg/parquet/parquet_schema_util_internal.h index 49c62ff090..43d476b0bd 100644 --- a/src/iceberg/parquet/parquet_schema_util_internal.h +++ b/src/iceberg/parquet/parquet_schema_util_internal.h @@ -54,10 +54,12 @@ Status ValidateParquetTypeCompatibility( /// /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param parquet_schema The Parquet schema to read data from. +/// \param constants File-level values used for fields absent from the file. /// \return The schema projection result with column indices of projected Parquet columns /// specified via ParquetExtraAttributes. Result Project(const Schema& expected_schema, - const ::parquet::arrow::SchemaManifest& parquet_schema); + const ::parquet::arrow::SchemaManifest& parquet_schema, + const ColumnConstants& constants = {}); /// \brief Get the selected column indices by walking through the projection result. /// diff --git a/src/iceberg/schema_util.cc b/src/iceberg/schema_util.cc index d7d261757e..ccf864477f 100644 --- a/src/iceberg/schema_util.cc +++ b/src/iceberg/schema_util.cc @@ -230,6 +230,52 @@ Result ProjectNested(const Type& expected_type, const Type& sou } // namespace +Result ProjectConstant(const SchemaField& field, + const ColumnConstant& constant) { + FieldProjection projection{.kind = FieldProjection::Kind::kConstant}; + if (const auto* literal = std::get_if(&constant)) { + if (!field.type()->is_primitive() || literal->type() == nullptr || + literal->IsAboveMax() || literal->IsBelowMin()) { + return InvalidSchema("Invalid constant for field {}", field.field_id()); + } + ICEBERG_RETURN_UNEXPECTED(ValidateSchemaEvolution(*field.type(), *literal->type())); + if (literal->IsNull() && !field.optional()) { + return InvalidSchema("Null constant for required field {}", field.field_id()); + } + if (literal->IsNull()) { + projection.kind = FieldProjection::Kind::kNull; + return projection; + } + projection.from = *literal; + return projection; + } + + if (field.type()->type_id() != TypeId::kStruct) { + return InvalidSchema("Struct constant requires a struct field: {}", field.field_id()); + } + const auto& fields = internal::checked_cast(*field.type()).fields(); + const auto& values = std::get(constant); + if (fields.empty() && field.optional()) { + projection.kind = FieldProjection::Kind::kNull; + return projection; + } + for (const auto& child : fields) { + if (!child.type()->is_primitive()) { + return InvalidSchema("Struct constants require primitive children: {}", + child.field_id()); + } + if (const auto it = values.find(child.field_id()); it != values.end()) { + ICEBERG_ASSIGN_OR_RAISE(auto child_projection, ProjectConstant(child, it->second)); + projection.children.push_back(std::move(child_projection)); + } else if (child.optional()) { + projection.children.push_back({.kind = FieldProjection::Kind::kNull}); + } else { + return InvalidSchema("Missing required constant field {}", child.field_id()); + } + } + return projection; +} + Result Project(const Schema& expected_schema, const Schema& source_schema, bool prune_source, ProjectionMode mode) { diff --git a/src/iceberg/schema_util.h b/src/iceberg/schema_util.h index 397013f44a..3bb0aa35a6 100644 --- a/src/iceberg/schema_util.h +++ b/src/iceberg/schema_util.h @@ -28,6 +28,7 @@ #include #include "iceberg/expression/literal.h" +#include "iceberg/file_reader.h" #include "iceberg/iceberg_export.h" #include "iceberg/result.h" #include "iceberg/type_fwd.h" @@ -104,6 +105,10 @@ ICEBERG_EXPORT Result Project( const Schema& expected_schema, const Schema& source_schema, bool prune_source, ProjectionMode mode = ProjectionMode::kRead); +/// Build a typed constant projection, matching struct children by field ID. +ICEBERG_EXPORT Result ProjectConstant(const SchemaField& field, + const ColumnConstant& constant); + ICEBERG_EXPORT std::string_view ToString(FieldProjection::Kind kind); ICEBERG_EXPORT std::string ToString(const FieldProjection& projection); ICEBERG_EXPORT std::string ToString(const SchemaProjection& projection); diff --git a/src/iceberg/table_scan.cc b/src/iceberg/table_scan.cc index a29ee00434..ded076981a 100644 --- a/src/iceberg/table_scan.cc +++ b/src/iceberg/table_scan.cc @@ -174,25 +174,28 @@ ScanTask::~ScanTask() = default; FileScanTask::FileScanTask(std::shared_ptr data_file, std::vector> delete_files, - std::shared_ptr residual_filter) + std::shared_ptr residual_filter, + std::shared_ptr spec) : data_file_(std::move(data_file)), delete_files_(std::move(delete_files)), - residual_filter_(std::move(residual_filter)) { + residual_filter_(std::move(residual_filter)), + spec_(std::move(spec)) { ICEBERG_DCHECK(data_file_ != nullptr, "Data file cannot be null for FileScanTask"); } FileScanTask::FileScanTask(std::shared_ptr data_file, std::vector> delete_files, - std::shared_ptr residual_filter, Range range) + std::shared_ptr residual_filter, Range range, + std::shared_ptr spec) : FileScanTask(std::move(data_file), std::move(delete_files), - std::move(residual_filter)) { + std::move(residual_filter), std::move(spec)) { range_ = range; } Result> FileScanTask::MakeSplit( std::shared_ptr data_file, int64_t start, int64_t length, std::vector> delete_files, - std::shared_ptr filter) { + std::shared_ptr filter, std::shared_ptr spec) { if (data_file == nullptr) { return InvalidArgument("Cannot create a file scan task without a data file"); } @@ -215,7 +218,7 @@ Result> FileScanTask::MakeSplit( // only valid empty range: [0, 0) of an empty file. if (start == 0 && length == file_size) { return std::make_shared(std::move(data_file), std::move(delete_files), - std::move(filter)); + std::move(filter), std::move(spec)); } if (length == 0) { return InvalidArgument("A partial split of file {} must have positive length", @@ -224,7 +227,7 @@ Result> FileScanTask::MakeSplit( return std::shared_ptr( new FileScanTask(std::move(data_file), std::move(delete_files), std::move(filter), - Range{.start = start, .length = length})); + Range{.start = start, .length = length}, std::move(spec))); } int64_t FileScanTask::length() const { diff --git a/src/iceberg/table_scan.h b/src/iceberg/table_scan.h index 3781d88cf2..10d9274931 100644 --- a/src/iceberg/table_scan.h +++ b/src/iceberg/table_scan.h @@ -73,11 +73,13 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { /// \param data_file The data file to read. /// \param delete_files Delete files that apply to this data file. /// \param filter Optional residual filter to apply after reading. + /// \param spec Partition spec corresponding to the data file partition tuple. /// \note The shared data file, delete files, and residual filter must remain /// unchanged for this task's lifetime. Metadata changes require rebuilding tasks. explicit FileScanTask(std::shared_ptr data_file, std::vector> delete_files = {}, - std::shared_ptr filter = nullptr); + std::shared_ptr filter = nullptr, + std::shared_ptr spec = nullptr); /// \brief Make a task for a validated half-open byte range [start, start + length). /// @@ -88,7 +90,8 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { static Result> MakeSplit( std::shared_ptr data_file, int64_t start, int64_t length, std::vector> delete_files = {}, - std::shared_ptr filter = nullptr); + std::shared_ptr filter = nullptr, + std::shared_ptr spec = nullptr); /// \brief The inclusive byte offset where this task starts, or zero for a whole file. int64_t start() const { return range_ ? range_->start : 0; } @@ -110,6 +113,9 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { /// \brief Residual filter to apply after reading. const std::shared_ptr& residual_filter() const { return residual_filter_; } + /// The partition spec used to write this file, including historical field IDs. + const std::shared_ptr& spec() const { return spec_; } + Kind kind() const override { return Kind::kFileScanTask; } int64_t size_bytes() const override; int32_t files_count() const override; @@ -128,12 +134,14 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { FileScanTask(std::shared_ptr data_file, std::vector> delete_files, - std::shared_ptr filter, Range range); + std::shared_ptr filter, Range range, + std::shared_ptr spec); std::shared_ptr data_file_; std::vector> delete_files_; std::shared_ptr residual_filter_; std::optional range_; + std::shared_ptr spec_; }; /// \brief Stream of file scan tasks. diff --git a/src/iceberg/test/avro_test.cc b/src/iceberg/test/avro_test.cc index 71062375f7..44a06f7764 100644 --- a/src/iceberg/test/avro_test.cc +++ b/src/iceberg/test/avro_test.cc @@ -567,6 +567,31 @@ class AvroReaderParameterizedTest : public AvroReaderTest, } }; +TEST_P(AvroReaderParameterizedTest, ReadsPartitionConstants) { + CreateSimpleAvroFile(); + auto schema = std::make_shared(std::vector{ + SchemaField::MakeRequired(1, "id", int32()), + SchemaField::MakeRequired(3, "region", string()), + SchemaField::MakeOptional(4, "missing", string()), + SchemaField::MakeOptional( + MetadataColumns::kPartitionColumnId, "_partition", + struct_({SchemaField::MakeOptional(1001, "bucket", int64()), + SchemaField::MakeOptional(1002, "added", string())}))}); + ReaderOptions options{.path = temp_avro_file_, .io = file_io_, .projection = schema}; + options.properties.Set(ReaderProperties::kAvroSkipDatum, skip_datum_); + options.constants = { + {1, Literal::Int(999)}, + {3, Literal::String("CN")}, + {4, Literal::Null(string())}, + {MetadataColumns::kPartitionColumnId, StructConstant{{1001, Literal::Int(7)}}}}; + ICEBERG_UNWRAP_OR_FAIL(auto reader, + ReaderFactoryRegistry::Open(FileFormatType::kAvro, options)); + VerifyNextBatch(*reader, R"([[1,"CN",null,[7,null]], + [2,"CN",null,[7,null]], + [3,"CN",null,[7,null]]])"); + VerifyExhausted(*reader); +} + TEST_P(AvroReaderParameterizedTest, AvroWriterBasicType) { auto schema = std::make_shared(std::vector{ SchemaField::MakeRequired(1, "name", std::make_shared())}); diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index 898342d760..67aa1c5606 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -60,6 +61,7 @@ #include "iceberg/file_format.h" #include "iceberg/file_io.h" #include "iceberg/file_reader.h" +#include "iceberg/json_serde_internal.h" #include "iceberg/manifest/manifest_entry.h" #include "iceberg/metadata_columns.h" #include "iceberg/parquet/parquet_register.h" @@ -72,6 +74,7 @@ #include "iceberg/test/matchers.h" #include "iceberg/test/std_io.h" #include "iceberg/test/temp_file_test_base.h" +#include "iceberg/transform.h" #include "iceberg/type.h" #include "iceberg/util/macros.h" @@ -461,6 +464,126 @@ class FileScanTaskReaderTest : public TempFileTestBase { std::shared_ptr projected_schema_; }; +TEST_F(FileScanTaskReaderTest, IdentityPartitionConstantsSurviveJsonAndSplit) { + auto physical = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int32())}); + ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(physical, "[[1], [2], [3]]")); + ICEBERG_UNWRAP_OR_FAIL( + auto spec, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}})); + file->partition_spec_id = 7; + file->partition = PartitionValues({Literal::String("CN")}); + FileScanTask task(file, {}, nullptr, std::move(spec)); + ICEBERG_UNWRAP_OR_FAIL( + auto json, ToJson(task, {{7, std::const_pointer_cast(task.spec())}}, + *table_schema_)); + ICEBERG_UNWRAP_OR_FAIL(auto parsed, FileScanTaskFromJson(json)); + ASSERT_NE(parsed->spec(), nullptr); + EXPECT_EQ(parsed->spec()->spec_id(), 7); + ICEBERG_UNWRAP_OR_FAIL( + auto split, FileScanTask::MakeSplit(parsed->data_file(), 0, parsed->length(), {}, + nullptr, parsed->spec())); + EXPECT_EQ(split->spec(), parsed->spec()); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, FileScanTaskReader::Make({.io = file_io_, + .table_schema = table_schema_, + .schemas = {table_schema_}, + .projected_schema = projected_schema_})); + ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*split)); + VerifyStream(&stream, R"([[1, "CN"], [2, "CN"], [3, "CN"]])"); +} + +TEST_F(FileScanTaskReaderTest, IdentityConstantsApplyBeforeEqualityDeletes) { + auto physical = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int32())}); + ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(physical, "[[1], [2], [3]]")); + auto delete_schema = std::make_shared( + std::vector{SchemaField::MakeOptional(2, "name", string())}); + ICEBERG_UNWRAP_OR_FAIL( + auto deletes, MakeEqualityDeleteFile(CreateNewTempFilePathWithSuffix(".parquet"), + delete_schema, R"([["CN"]])", {2})); + ICEBERG_UNWRAP_OR_FAIL( + auto spec, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}})); + file->partition_spec_id = 7; + file->partition = PartitionValues({Literal::String("CN")}); + FileScanTask task(file, {deletes}, nullptr, std::move(spec)); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + FileScanTaskReader::Make({.io = file_io_, + .table_schema = table_schema_, + .schemas = {table_schema_}, + .projected_schema = physical})); + ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(task)); + auto batches = ::arrow::ImportRecordBatchReader(&stream).ValueOrDie(); + auto table = batches->ToTable().ValueOrDie(); + EXPECT_EQ(table->num_rows(), 0); +} + +TEST_F(FileScanTaskReaderTest, PartitionMetadataMatchesHistoricalFieldIds) { + ICEBERG_UNWRAP_OR_FAIL( + auto file, MakeDataFile(table_schema_, + R"([[1, "physical", "blue"], [2, "physical", "red"]])", 2)); + ICEBERG_UNWRAP_OR_FAIL( + auto spec, PartitionSpec::Make(4, {{1, 1000, "bucket", Transform::Bucket(16)}, + {2, 1001, "name", Transform::Identity()}})); + file->partition_spec_id = 4; + file->partition = PartitionValues({Literal::Int(5), Literal::String("constant")}); + auto projection = std::make_shared(std::vector{ + SchemaField::MakeOptional(2, "renamed", string()), MetadataColumns::kSpecId, + SchemaField::MakeOptional( + MetadataColumns::kPartitionColumnId, "_partition", + struct_({SchemaField::MakeOptional(1001, "region", string()), + SchemaField::MakeOptional(1002, "added", int32()), + SchemaField::MakeOptional(1000, "bucket", int64())}))}); + FileScanTask task(file, {}, nullptr, std::move(spec)); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + FileScanTaskReader::Make({.io = file_io_, + .table_schema = table_schema_, + .schemas = {table_schema_}, + .projected_schema = projection})); + ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(task)); + VerifyStream(&stream, R"([["physical", 4, ["constant", null, 5]], + ["physical", 4, ["constant", null, 5]]])"); +} + +TEST_F(FileScanTaskReaderTest, NullIdentityOverridesInitialDefault) { + auto physical = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int32())}); + ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(physical, "[[1], [2], [3]]")); + ICEBERG_UNWRAP_OR_FAIL( + auto spec, PartitionSpec::Make(0, {{2, 1000, "name", Transform::Identity()}})); + file->partition = PartitionValues({Literal::Null(string())}); + auto projection = std::make_shared(std::vector{ + SchemaField(2, "name", string(), true, {}, + std::make_shared(Literal::String("default")))}); + FileScanTask task(file, {}, nullptr, std::move(spec)); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + FileScanTaskReader::Make({.io = file_io_, + .table_schema = table_schema_, + .schemas = {table_schema_}, + .projected_schema = projection})); + ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(task)); + VerifyStream(&stream, "[[null], [null], [null]]"); +} + +TEST_F(FileScanTaskReaderTest, RejectsMissingOrInconsistentPartitionContext) { + ICEBERG_UNWRAP_OR_FAIL(auto file, + MakeDataFile(table_schema_, R"([[1, "Foo", "blue"]])", 1)); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, FileScanTaskReader::Make({.io = file_io_, + .table_schema = table_schema_, + .schemas = {table_schema_}, + .projected_schema = projected_schema_})); + file->partition = PartitionValues({Literal::String("CN")}); + EXPECT_FALSE(reader->Open(FileScanTask(file)).has_value()); + ICEBERG_UNWRAP_OR_FAIL( + auto spec, PartitionSpec::Make(3, {{2, 1000, "name", Transform::Identity()}})); + auto shared_spec = std::shared_ptr(std::move(spec)); + file->partition_spec_id = 9; + EXPECT_FALSE(reader->Open(FileScanTask(file, {}, nullptr, shared_spec)).has_value()); + file->partition_spec_id = 3; + file->partition = PartitionValues{}; + EXPECT_FALSE(reader->Open(FileScanTask(file, {}, nullptr, shared_spec)).has_value()); +} + TEST_F(FileScanTaskReaderTest, OpenWithoutDeletesReadsProjectedSchema) { ICEBERG_UNWRAP_OR_FAIL( auto data_file, diff --git a/src/iceberg/test/manifest_group_test.cc b/src/iceberg/test/manifest_group_test.cc index 063ce5804b..84bd971a96 100644 --- a/src/iceberg/test/manifest_group_test.cc +++ b/src/iceberg/test/manifest_group_test.cc @@ -290,6 +290,10 @@ TEST_P(ManifestGroupTest, CreateAndGetEntries) { ASSERT_EQ(tasks.size(), 2); EXPECT_THAT(GetPaths(tasks), testing::UnorderedElementsAre("/path/to/data1.parquet", "/path/to/data2.parquet")); + for (const auto& task : tasks) { + ASSERT_NE(task->spec(), nullptr); + EXPECT_EQ(task->spec()->spec_id(), task->data_file()->partition_spec_id); + } EXPECT_EQ(tasks[0]->delete_files().size(), 1); EXPECT_EQ(tasks[1]->delete_files()[0]->file_path, "/path/to/delete.parquet"); EXPECT_EQ(tasks[1]->delete_files().size(), 1); diff --git a/src/iceberg/test/parquet_test.cc b/src/iceberg/test/parquet_test.cc index e7642dbe0f..cd70952eec 100644 --- a/src/iceberg/test/parquet_test.cc +++ b/src/iceberg/test/parquet_test.cc @@ -517,6 +517,25 @@ class ParquetReaderTest : public TempFileTestBase { std::string temp_parquet_file_; }; +TEST_F(ParquetReaderTest, ConstantsValidateTypesAndRequiredNulls) { + CreateSimpleParquetFile(); + auto schema = std::make_shared( + std::vector{SchemaField::MakeRequired(3, "constant", int64())}); + for (const auto& value : {Literal::String("7"), Literal::Null(int64())}) { + ReaderOptions options{ + .path = temp_parquet_file_, .io = file_io_, .projection = schema}; + options.constants.emplace(3, value); + EXPECT_FALSE( + ReaderFactoryRegistry::Open(FileFormatType::kParquet, options).has_value()); + } + ReaderOptions options{.path = temp_parquet_file_, .io = file_io_, .projection = schema}; + options.constants.emplace(3, Literal::Int(7)); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + ReaderFactoryRegistry::Open(FileFormatType::kParquet, options)); + VerifyNextBatch(*reader, "[[7], [7], [7]]"); + VerifyExhausted(*reader); +} + TEST_F(ParquetReaderTest, ReadTwoFields) { CreateSimpleParquetFile(); diff --git a/src/iceberg/test/rest_json_serde_test.cc b/src/iceberg/test/rest_json_serde_test.cc index 3470a21936..0ef1843769 100644 --- a/src/iceberg/test/rest_json_serde_test.cc +++ b/src/iceberg/test/rest_json_serde_test.cc @@ -2652,6 +2652,8 @@ TEST(FetchScanTasksResponseRoundtripTest, PreservesResidualFilter) { ASSERT_TRUE(result->file_scan_tasks.has_value()); ASSERT_EQ(result->file_scan_tasks->size(), 1); ASSERT_NE(result->file_scan_tasks->at(0)->residual_filter(), nullptr); + ASSERT_NE(result->file_scan_tasks->at(0)->spec(), nullptr); + EXPECT_EQ(result->file_scan_tasks->at(0)->spec()->spec_id(), 0); ICEBERG_UNWRAP_OR_FAIL(auto roundtrip_json, ToJson(*result, UnpartitionedSpecs(), EmptySchema())); From 1f8587d01abf681d8b973efd8b69b54ad05252a2 Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Wed, 28 Oct 2026 19:07:14 +0800 Subject: [PATCH 02/11] fix(read): prefer partition constants as in Iceberg Java --- src/iceberg/avro/avro_schema_util.cc | 8 ++++---- src/iceberg/file_reader.h | 4 ++-- src/iceberg/parquet/parquet_schema_util.cc | 11 +++++------ src/iceberg/test/avro_test.cc | 6 +++--- src/iceberg/test/file_scan_task_reader_test.cc | 4 ++-- 5 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/iceberg/avro/avro_schema_util.cc b/src/iceberg/avro/avro_schema_util.cc index 819b4e2641..e1003117cd 100644 --- a/src/iceberg/avro/avro_schema_util.cc +++ b/src/iceberg/avro/avro_schema_util.cc @@ -752,14 +752,14 @@ Result ProjectStruct(const StructType& struct_type, int32_t field_id = expected_field.field_id(); FieldProjection child_projection; - if (auto iter = node_info_map.find(field_id); iter != node_info_map.cend()) { + if (auto constant = constants.find(field_id); constant != constants.end()) { + ICEBERG_ASSIGN_OR_RAISE(child_projection, + ProjectConstant(expected_field, constant->second)); + } else if (auto iter = node_info_map.find(field_id); iter != node_info_map.cend()) { ICEBERG_ASSIGN_OR_RAISE( child_projection, ProjectField(expected_field, iter->second.field_node, iter->second.local_index, prune_source, constants)); - } else if (auto constant = constants.find(field_id); constant != constants.end()) { - ICEBERG_ASSIGN_OR_RAISE(child_projection, - ProjectConstant(expected_field, constant->second)); } else if (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (expected_field.initial_default() != nullptr) { diff --git a/src/iceberg/file_reader.h b/src/iceberg/file_reader.h index 76b0ff23d6..0ad06fd5b0 100644 --- a/src/iceberg/file_reader.h +++ b/src/iceberg/file_reader.h @@ -141,8 +141,8 @@ struct ICEBERG_EXPORT ReaderOptions { /// \brief Format-specific or implementation-specific properties. ReaderProperties properties; - /// File-level values keyed by field ID, used when physical columns are absent. - /// Constants precede initial defaults and optional-field nulls. + /// File-level values keyed by field ID, overriding physical columns, + /// initial defaults and optional-field nulls, matching Iceberg Java. /// Example: `options.constants.emplace(2, Literal::String("CN"));` ColumnConstants constants; }; diff --git a/src/iceberg/parquet/parquet_schema_util.cc b/src/iceberg/parquet/parquet_schema_util.cc index a6727e9eea..9af60284bb 100644 --- a/src/iceberg/parquet/parquet_schema_util.cc +++ b/src/iceberg/parquet/parquet_schema_util.cc @@ -589,15 +589,14 @@ class ProjectionBuilder { int32_t field_id = field.field_id(); FieldProjection child_projection; - if (auto iter = field_context_map.find(field_id); - iter != field_context_map.cend()) { + if (auto constant = constants_.find(field_id); constant != constants_.end()) { + ICEBERG_ASSIGN_OR_RAISE(child_projection, + ProjectConstant(field, constant->second)); + } else if (auto iter = field_context_map.find(field_id); + iter != field_context_map.cend()) { const auto& parquet_field = iter->second.parquet_field; ICEBERG_ASSIGN_OR_RAISE(child_projection, ProjectField(field, parquet_field, iter->second.local_index)); - } else if (auto constant = constants_.find(field_id); - constant != constants_.end()) { - ICEBERG_ASSIGN_OR_RAISE(child_projection, - ProjectConstant(field, constant->second)); } else if (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (field.initial_default() != nullptr) { diff --git a/src/iceberg/test/avro_test.cc b/src/iceberg/test/avro_test.cc index 44a06f7764..2af735c44f 100644 --- a/src/iceberg/test/avro_test.cc +++ b/src/iceberg/test/avro_test.cc @@ -586,9 +586,9 @@ TEST_P(AvroReaderParameterizedTest, ReadsPartitionConstants) { {MetadataColumns::kPartitionColumnId, StructConstant{{1001, Literal::Int(7)}}}}; ICEBERG_UNWRAP_OR_FAIL(auto reader, ReaderFactoryRegistry::Open(FileFormatType::kAvro, options)); - VerifyNextBatch(*reader, R"([[1,"CN",null,[7,null]], - [2,"CN",null,[7,null]], - [3,"CN",null,[7,null]]])"); + VerifyNextBatch(*reader, R"([[999,"CN",null,[7,null]], + [999,"CN",null,[7,null]], + [999,"CN",null,[7,null]]])"); VerifyExhausted(*reader); } diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index 67aa1c5606..32e27dee49 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -540,8 +540,8 @@ TEST_F(FileScanTaskReaderTest, PartitionMetadataMatchesHistoricalFieldIds) { .schemas = {table_schema_}, .projected_schema = projection})); ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(task)); - VerifyStream(&stream, R"([["physical", 4, ["constant", null, 5]], - ["physical", 4, ["constant", null, 5]]])"); + VerifyStream(&stream, R"([["constant", 4, ["constant", null, 5]], + ["constant", 4, ["constant", null, 5]]])"); } TEST_F(FileScanTaskReaderTest, NullIdentityOverridesInitialDefault) { From cef3741abdcdf5008af792c1b009a439d56a4e8c Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Wed, 28 Oct 2026 19:11:43 +0800 Subject: [PATCH 03/11] refactor(read): limit partition constants to identity source columns --- src/iceberg/avro/avro_data_util.cc | 18 ------ src/iceberg/data/file_scan_task_reader.cc | 64 +++++++------------ src/iceberg/file_reader.h | 10 +-- src/iceberg/parquet/parquet_data_util.cc | 12 ---- src/iceberg/schema_util.cc | 50 +++------------ src/iceberg/schema_util.h | 4 +- src/iceberg/test/avro_test.cc | 23 +++---- .../test/file_scan_task_reader_test.cc | 27 -------- 8 files changed, 44 insertions(+), 164 deletions(-) diff --git a/src/iceberg/avro/avro_data_util.cc b/src/iceberg/avro/avro_data_util.cc index 622cde5840..3be8919022 100644 --- a/src/iceberg/avro/avro_data_util.cc +++ b/src/iceberg/avro/avro_data_util.cc @@ -598,11 +598,6 @@ Status PrepareStructDefaultScalars(std::span projections, if (field_projection.kind == FieldProjection::Kind::kDefault || field_projection.kind == FieldProjection::Kind::kConstant) { - if (field_builder->type()->id() == ::arrow::Type::STRUCT) { - ICEBERG_RETURN_UNEXPECTED( - PrepareStructDefaultScalars(field_projection.children, field_builder)); - continue; - } // Get-or-create the single Avro attributes container: another Avro attribute may // have created it already, so guard on `default_scalar` being unset rather than on // the container's presence (otherwise a pre-existing container would skip @@ -649,19 +644,6 @@ Status AppendDefaultToBuilder(const Literal& literal, ::arrow::ArrayBuilder* bui Status AppendDefaultToBuilder(const FieldProjection& projection, ::arrow::ArrayBuilder* builder) { - if (projection.kind == FieldProjection::Kind::kNull) { - ICEBERG_ARROW_RETURN_NOT_OK(builder->AppendNull()); - return {}; - } - if (builder->type()->id() == ::arrow::Type::STRUCT) { - auto* struct_builder = internal::checked_cast<::arrow::StructBuilder*>(builder); - ICEBERG_ARROW_RETURN_NOT_OK(struct_builder->Append()); - for (size_t i = 0; i < projection.children.size(); ++i) { - ICEBERG_RETURN_UNEXPECTED(AppendDefaultToBuilder( - projection.children[i], struct_builder->field_builder(static_cast(i)))); - } - return {}; - } // Avro projections carry a single attributes type, so once one is attached it is an // AvroExtraAttributes; use checked_cast instead of a per-row dynamic_cast. if (projection.attributes != nullptr) { diff --git a/src/iceberg/data/file_scan_task_reader.cc b/src/iceberg/data/file_scan_task_reader.cc index 728f340a25..0be1c84b12 100644 --- a/src/iceberg/data/file_scan_task_reader.cc +++ b/src/iceberg/data/file_scan_task_reader.cc @@ -35,7 +35,6 @@ #include "iceberg/expression/evaluator.h" #include "iceberg/file_reader.h" #include "iceberg/manifest/manifest_entry.h" -#include "iceberg/metadata_columns.h" #include "iceberg/nanoarrow_status_internal.h" #include "iceberg/partition_spec.h" #include "iceberg/row/arrow_array_wrapper.h" @@ -48,52 +47,33 @@ namespace iceberg { namespace { -Result ConstantsOf(const FileScanTask& task, const Schema& projection) { +Result ConstantsOf(const FileScanTask& task) { const auto& file = *task.data_file(); const auto& spec = task.spec(); - ICEBERG_ASSIGN_OR_RAISE(auto partition_field, - projection.FindFieldById(MetadataColumns::kPartitionColumnId)); - ICEBERG_ASSIGN_OR_RAISE(auto spec_field, - projection.FindFieldById(MetadataColumns::kSpecIdColumnId)); ColumnConstants constants; - auto spec_id = file.partition_spec_id; - if (spec) { - if (spec_id.has_value() && *spec_id != spec->spec_id()) { - return InvalidArgument("Data file spec ID {} does not match task spec ID {}", - *spec_id, spec->spec_id()); + if (!spec) { + if (file.partition.num_fields() != 0) { + return InvalidArgument("A partition spec is required to read partition values"); } - spec_id = spec->spec_id(); - if (file.partition.num_fields() != spec->fields().size()) { - return InvalidArgument( - "Partition value count {} does not match spec field count {}", - file.partition.num_fields(), spec->fields().size()); - } - StructConstant partition; - for (size_t i = 0; i < spec->fields().size(); ++i) { - const auto& field = spec->fields()[i]; - const auto& value = file.partition.values()[i]; - if (field.transform() == nullptr) { - return InvalidArgument("Missing transform for partition field {}", - field.field_id()); - } - if (field.transform()->transform_type() == TransformType::kIdentity) { - constants.emplace(field.source_id(), value); - } - if (partition_field.has_value()) { - partition.emplace(field.field_id(), value); - } - } - if (partition_field.has_value()) { - constants.emplace(MetadataColumns::kPartitionColumnId, std::move(partition)); - } - } else if (file.partition.num_fields() != 0 || partition_field.has_value()) { - return InvalidArgument("A partition spec is required to read partition values"); + return constants; + } + if (file.partition_spec_id.has_value() && *file.partition_spec_id != spec->spec_id()) { + return InvalidArgument("Data file spec ID {} does not match task spec ID {}", + *file.partition_spec_id, spec->spec_id()); } - if (spec_field.has_value()) { - if (!spec_id.has_value()) { - return InvalidArgument("A partition spec ID is required to read _spec_id"); + if (file.partition.num_fields() != spec->fields().size()) { + return InvalidArgument("Partition value count {} does not match spec field count {}", + file.partition.num_fields(), spec->fields().size()); + } + for (size_t i = 0; i < spec->fields().size(); ++i) { + const auto& field = spec->fields()[i]; + if (field.transform() == nullptr) { + return InvalidArgument("Missing transform for partition field {}", + field.field_id()); + } + if (field.transform()->transform_type() == TransformType::kIdentity) { + constants.emplace(field.source_id(), file.partition.values()[i]); } - constants.emplace(MetadataColumns::kSpecIdColumnId, Literal::Int(*spec_id)); } return constants; } @@ -104,7 +84,7 @@ Result MakeReaderOptions( std::shared_ptr name_mapping, ReaderProperties properties, std::optional first_row_id, std::optional data_sequence_number) { const auto& data_file = *task.data_file(); - ICEBERG_ASSIGN_OR_RAISE(auto constants, ConstantsOf(task, *projection)); + ICEBERG_ASSIGN_OR_RAISE(auto constants, ConstantsOf(task)); return ReaderOptions{ .path = data_file.file_path, .length = static_cast(data_file.file_size_in_bytes), diff --git a/src/iceberg/file_reader.h b/src/iceberg/file_reader.h index 0ad06fd5b0..1083b0c9f3 100644 --- a/src/iceberg/file_reader.h +++ b/src/iceberg/file_reader.h @@ -27,7 +27,6 @@ #include #include #include -#include #include "iceberg/arrow_c_data.h" #include "iceberg/expression/literal.h" @@ -106,13 +105,8 @@ class ICEBERG_EXPORT ReaderProperties : public ConfigBase { const std::unordered_map& properties); }; -/// A non-null struct constant, keyed by child field ID. Children are primitive -/// literals, including typed nulls. Projected children absent from the map are null. -using StructConstant = std::unordered_map; - -/// A file-level primitive or struct constant, independent of the file format. -using ColumnConstant = std::variant; -using ColumnConstants = std::unordered_map; +/// File-level primitive values keyed by source field ID, including typed nulls. +using ColumnConstants = std::unordered_map; /// \brief Options for creating a reader. struct ICEBERG_EXPORT ReaderOptions { diff --git a/src/iceberg/parquet/parquet_data_util.cc b/src/iceberg/parquet/parquet_data_util.cc index dda5370164..27453dac0a 100644 --- a/src/iceberg/parquet/parquet_data_util.cc +++ b/src/iceberg/parquet/parquet_data_util.cc @@ -252,18 +252,6 @@ Result> ProjectStructArray( projected_array, ProjectPrimitiveArray(parquet_array, output_arrow_type, pool)); } - } else if (field_projection.kind == FieldProjection::Kind::kConstant && - projected_field.type()->type_id() == TypeId::kStruct) { - // An empty source struct supplies the batch length; children come entirely - // from the constant projection and retain the requested field IDs/order. - auto source = std::make_shared<::arrow::StructArray>( - ::arrow::struct_({}), struct_array->length(), ::arrow::ArrayVector{}); - ICEBERG_ASSIGN_OR_RAISE( - projected_array, - ProjectNestedArray( - source, output_arrow_type, - internal::checked_cast(*projected_field.type()), - field_projection.children, metadata_context, row_positions, pool)); } else if (field_projection.kind == FieldProjection::Kind::kDefault || field_projection.kind == FieldProjection::Kind::kConstant) { ICEBERG_ASSIGN_OR_RAISE( diff --git a/src/iceberg/schema_util.cc b/src/iceberg/schema_util.cc index ccf864477f..2c8008deee 100644 --- a/src/iceberg/schema_util.cc +++ b/src/iceberg/schema_util.cc @@ -231,49 +231,19 @@ Result ProjectNested(const Type& expected_type, const Type& sou } // namespace Result ProjectConstant(const SchemaField& field, - const ColumnConstant& constant) { - FieldProjection projection{.kind = FieldProjection::Kind::kConstant}; - if (const auto* literal = std::get_if(&constant)) { - if (!field.type()->is_primitive() || literal->type() == nullptr || - literal->IsAboveMax() || literal->IsBelowMin()) { - return InvalidSchema("Invalid constant for field {}", field.field_id()); - } - ICEBERG_RETURN_UNEXPECTED(ValidateSchemaEvolution(*field.type(), *literal->type())); - if (literal->IsNull() && !field.optional()) { - return InvalidSchema("Null constant for required field {}", field.field_id()); - } - if (literal->IsNull()) { - projection.kind = FieldProjection::Kind::kNull; - return projection; - } - projection.from = *literal; - return projection; - } - - if (field.type()->type_id() != TypeId::kStruct) { - return InvalidSchema("Struct constant requires a struct field: {}", field.field_id()); + const Literal& literal) { + if (!field.type()->is_primitive() || literal.type() == nullptr || + literal.IsAboveMax() || literal.IsBelowMin()) { + return InvalidSchema("Invalid constant for field {}", field.field_id()); } - const auto& fields = internal::checked_cast(*field.type()).fields(); - const auto& values = std::get(constant); - if (fields.empty() && field.optional()) { - projection.kind = FieldProjection::Kind::kNull; - return projection; + ICEBERG_RETURN_UNEXPECTED(ValidateSchemaEvolution(*field.type(), *literal.type())); + if (literal.IsNull() && !field.optional()) { + return InvalidSchema("Null constant for required field {}", field.field_id()); } - for (const auto& child : fields) { - if (!child.type()->is_primitive()) { - return InvalidSchema("Struct constants require primitive children: {}", - child.field_id()); - } - if (const auto it = values.find(child.field_id()); it != values.end()) { - ICEBERG_ASSIGN_OR_RAISE(auto child_projection, ProjectConstant(child, it->second)); - projection.children.push_back(std::move(child_projection)); - } else if (child.optional()) { - projection.children.push_back({.kind = FieldProjection::Kind::kNull}); - } else { - return InvalidSchema("Missing required constant field {}", child.field_id()); - } + if (literal.IsNull()) { + return FieldProjection{.kind = FieldProjection::Kind::kNull}; } - return projection; + return FieldProjection{.kind = FieldProjection::Kind::kConstant, .from = literal}; } Result Project(const Schema& expected_schema, diff --git a/src/iceberg/schema_util.h b/src/iceberg/schema_util.h index 3bb0aa35a6..db8e1dbe48 100644 --- a/src/iceberg/schema_util.h +++ b/src/iceberg/schema_util.h @@ -105,9 +105,9 @@ ICEBERG_EXPORT Result Project( const Schema& expected_schema, const Schema& source_schema, bool prune_source, ProjectionMode mode = ProjectionMode::kRead); -/// Build a typed constant projection, matching struct children by field ID. +/// Build a primitive constant projection, validating type promotion and nullability. ICEBERG_EXPORT Result ProjectConstant(const SchemaField& field, - const ColumnConstant& constant); + const Literal& literal); ICEBERG_EXPORT std::string_view ToString(FieldProjection::Kind kind); ICEBERG_EXPORT std::string ToString(const FieldProjection& projection); diff --git a/src/iceberg/test/avro_test.cc b/src/iceberg/test/avro_test.cc index 2af735c44f..634ecf3f8d 100644 --- a/src/iceberg/test/avro_test.cc +++ b/src/iceberg/test/avro_test.cc @@ -569,26 +569,19 @@ class AvroReaderParameterizedTest : public AvroReaderTest, TEST_P(AvroReaderParameterizedTest, ReadsPartitionConstants) { CreateSimpleAvroFile(); - auto schema = std::make_shared(std::vector{ - SchemaField::MakeRequired(1, "id", int32()), - SchemaField::MakeRequired(3, "region", string()), - SchemaField::MakeOptional(4, "missing", string()), - SchemaField::MakeOptional( - MetadataColumns::kPartitionColumnId, "_partition", - struct_({SchemaField::MakeOptional(1001, "bucket", int64()), - SchemaField::MakeOptional(1002, "added", string())}))}); + auto schema = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int32()), + SchemaField::MakeRequired(3, "region", string()), + SchemaField::MakeOptional(4, "missing", string())}); ReaderOptions options{.path = temp_avro_file_, .io = file_io_, .projection = schema}; options.properties.Set(ReaderProperties::kAvroSkipDatum, skip_datum_); options.constants = { - {1, Literal::Int(999)}, - {3, Literal::String("CN")}, - {4, Literal::Null(string())}, - {MetadataColumns::kPartitionColumnId, StructConstant{{1001, Literal::Int(7)}}}}; + {1, Literal::Int(999)}, {3, Literal::String("CN")}, {4, Literal::Null(string())}}; ICEBERG_UNWRAP_OR_FAIL(auto reader, ReaderFactoryRegistry::Open(FileFormatType::kAvro, options)); - VerifyNextBatch(*reader, R"([[999,"CN",null,[7,null]], - [999,"CN",null,[7,null]], - [999,"CN",null,[7,null]]])"); + VerifyNextBatch(*reader, R"([[999,"CN",null], + [999,"CN",null], + [999,"CN",null]])"); VerifyExhausted(*reader); } diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index 32e27dee49..7a25dbf8c3 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -517,33 +517,6 @@ TEST_F(FileScanTaskReaderTest, IdentityConstantsApplyBeforeEqualityDeletes) { EXPECT_EQ(table->num_rows(), 0); } -TEST_F(FileScanTaskReaderTest, PartitionMetadataMatchesHistoricalFieldIds) { - ICEBERG_UNWRAP_OR_FAIL( - auto file, MakeDataFile(table_schema_, - R"([[1, "physical", "blue"], [2, "physical", "red"]])", 2)); - ICEBERG_UNWRAP_OR_FAIL( - auto spec, PartitionSpec::Make(4, {{1, 1000, "bucket", Transform::Bucket(16)}, - {2, 1001, "name", Transform::Identity()}})); - file->partition_spec_id = 4; - file->partition = PartitionValues({Literal::Int(5), Literal::String("constant")}); - auto projection = std::make_shared(std::vector{ - SchemaField::MakeOptional(2, "renamed", string()), MetadataColumns::kSpecId, - SchemaField::MakeOptional( - MetadataColumns::kPartitionColumnId, "_partition", - struct_({SchemaField::MakeOptional(1001, "region", string()), - SchemaField::MakeOptional(1002, "added", int32()), - SchemaField::MakeOptional(1000, "bucket", int64())}))}); - FileScanTask task(file, {}, nullptr, std::move(spec)); - ICEBERG_UNWRAP_OR_FAIL(auto reader, - FileScanTaskReader::Make({.io = file_io_, - .table_schema = table_schema_, - .schemas = {table_schema_}, - .projected_schema = projection})); - ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(task)); - VerifyStream(&stream, R"([["constant", 4, ["constant", null, 5]], - ["constant", 4, ["constant", null, 5]]])"); -} - TEST_F(FileScanTaskReaderTest, NullIdentityOverridesInitialDefault) { auto physical = std::make_shared( std::vector{SchemaField::MakeRequired(1, "id", int32())}); From 8633654b8e1e1e5ca4a9bab48e6bc40071ffb967 Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Thu, 29 Oct 2026 11:03:25 +0800 Subject: [PATCH 04/11] fix(read): validate constant types and cover partition evolution --- src/iceberg/avro/avro_schema_util_internal.h | 2 +- .../parquet/parquet_schema_util_internal.h | 2 +- src/iceberg/schema_util.cc | 4 +- .../test/file_scan_task_reader_test.cc | 69 +++++++++++++++++++ src/iceberg/test/schema_util_test.cc | 6 ++ 5 files changed, 79 insertions(+), 4 deletions(-) diff --git a/src/iceberg/avro/avro_schema_util_internal.h b/src/iceberg/avro/avro_schema_util_internal.h index 7cc0012b5a..02ced14441 100644 --- a/src/iceberg/avro/avro_schema_util_internal.h +++ b/src/iceberg/avro/avro_schema_util_internal.h @@ -142,7 +142,7 @@ class HasIdVisitor { /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param avro_node The Avro node to read data from. /// \param prune_source Whether the source schema can be pruned. -/// \param constants File-level values used for fields absent from the file. +/// \param constants File-level values that override physical fields and defaults. /// \return The schema projection result. Result Project(const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source, diff --git a/src/iceberg/parquet/parquet_schema_util_internal.h b/src/iceberg/parquet/parquet_schema_util_internal.h index 43d476b0bd..37af7574c7 100644 --- a/src/iceberg/parquet/parquet_schema_util_internal.h +++ b/src/iceberg/parquet/parquet_schema_util_internal.h @@ -54,7 +54,7 @@ Status ValidateParquetTypeCompatibility( /// /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param parquet_schema The Parquet schema to read data from. -/// \param constants File-level values used for fields absent from the file. +/// \param constants File-level values that override physical fields and defaults. /// \return The schema projection result with column indices of projected Parquet columns /// specified via ParquetExtraAttributes. Result Project(const Schema& expected_schema, diff --git a/src/iceberg/schema_util.cc b/src/iceberg/schema_util.cc index 2c8008deee..36143a7510 100644 --- a/src/iceberg/schema_util.cc +++ b/src/iceberg/schema_util.cc @@ -232,8 +232,8 @@ Result ProjectNested(const Type& expected_type, const Type& sou Result ProjectConstant(const SchemaField& field, const Literal& literal) { - if (!field.type()->is_primitive() || literal.type() == nullptr || - literal.IsAboveMax() || literal.IsBelowMin()) { + if (field.type() == nullptr || !field.type()->is_primitive() || + literal.type() == nullptr || literal.IsAboveMax() || literal.IsBelowMin()) { return InvalidSchema("Invalid constant for field {}", field.field_id()); } ICEBERG_RETURN_UNEXPECTED(ValidateSchemaEvolution(*field.type(), *literal.type())); diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index 7a25dbf8c3..faaeef7018 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -537,6 +537,75 @@ TEST_F(FileScanTaskReaderTest, NullIdentityOverridesInitialDefault) { VerifyStream(&stream, "[[null], [null], [null]]"); } +TEST_F(FileScanTaskReaderTest, ReadsEvolvedSpecsWithoutLeakingConstantsBetweenFiles) { + ICEBERG_UNWRAP_OR_FAIL( + auto identity, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}})); + ICEBERG_UNWRAP_OR_FAIL(auto unpartitioned, PartitionSpec::Make(8, {})); + ICEBERG_UNWRAP_OR_FAIL( + auto bucket, + PartitionSpec::Make(9, {{2, 1001, "name_bucket", Transform::Bucket(16)}})); + ICEBERG_UNWRAP_OR_FAIL( + auto reordered, + PartitionSpec::Make(10, {{3, 1002, "category", Transform::Identity()}, + {2, 1000, "renamed_name", Transform::Identity()}})); + struct Case { + std::shared_ptr spec; + PartitionValues partition; + std::string expected; + }; + auto identity_spec = std::shared_ptr(std::move(identity)); + const std::vector cases{ + {identity_spec, PartitionValues(Literal::String("CN")), + R"([[1, "CN"], [2, "CN"], [3, "CN"]])"}, + {std::move(unpartitioned), PartitionValues(), + R"([[1, "file"], [2, "file"], [3, "file"]])"}, + {std::move(bucket), PartitionValues(Literal::Int(3)), + R"([[1, "file"], [2, "file"], [3, "file"]])"}, + {std::move(reordered), + PartitionValues({Literal::String("retired"), Literal::String("US")}), + R"([[1, "US"], [2, "US"], [3, "US"]])"}, + {identity_spec, PartitionValues(Literal::Null(string())), + "[[1, null], [2, null], [3, null]]"}}; + // The current schema omits category, but historical task schemas retain its type. + ICEBERG_UNWRAP_OR_FAIL( + auto reader, FileScanTaskReader::Make({.io = file_io_, + .table_schema = projected_schema_, + .schemas = {table_schema_}, + .projected_schema = projected_schema_})); + std::vector> readers; + for (const auto& test : cases) { + SCOPED_TRACE(test.spec->spec_id()); + ICEBERG_UNWRAP_OR_FAIL( + auto file, + MakeDataFile(projected_schema_, R"([[1, "file"], [2, "file"], [3, "file"]])")); + file->partition_spec_id = test.spec->spec_id(); + file->partition = test.partition; + ICEBERG_UNWRAP_OR_FAIL(auto json, + ToJson(FileScanTask(file, {}, nullptr, test.spec), + {{test.spec->spec_id(), test.spec}}, *table_schema_)); + ICEBERG_UNWRAP_OR_FAIL(auto task, FileScanTaskFromJson(json)); + ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*task)); + auto imported = ::arrow::ImportRecordBatchReader(&stream); + ASSERT_TRUE(imported.ok()) << imported.status().ToString(); + readers.push_back(imported.ValueOrDie()); + } + // Keep all streams alive to detect accidental sharing of per-file constants. + for (size_t i = 0; i < cases.size(); ++i) { + SCOPED_TRACE(i); + auto next = readers[i]->Next(); + ASSERT_TRUE(next.ok()) << next.status().ToString(); + auto batch = next.ValueOrDie(); + ASSERT_NE(batch, nullptr); + ASSERT_TRUE(batch->ValidateFull().ok()); + ICEBERG_UNWRAP_OR_FAIL(auto expected, + MakeRecordBatch(batch->schema(), cases[i].expected)); + EXPECT_TRUE(batch->Equals(*expected)); + next = readers[i]->Next(); + ASSERT_TRUE(next.ok()) << next.status().ToString(); + EXPECT_EQ(next.ValueOrDie(), nullptr); + } +} + TEST_F(FileScanTaskReaderTest, RejectsMissingOrInconsistentPartitionContext) { ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(table_schema_, R"([[1, "Foo", "blue"]])", 1)); diff --git a/src/iceberg/test/schema_util_test.cc b/src/iceberg/test/schema_util_test.cc index 785a903509..3cbe7d5be7 100644 --- a/src/iceberg/test/schema_util_test.cc +++ b/src/iceberg/test/schema_util_test.cc @@ -101,6 +101,12 @@ std::shared_ptr CreateMapOfList() { } // namespace +TEST(SchemaUtilTest, ProjectConstantRejectsMissingFieldType) { + auto field = SchemaField::MakeOptional(1, "invalid", nullptr); + ASSERT_THAT(ProjectConstant(field, Literal::Long(7)), + IsError(ErrorKind::kInvalidSchema)); +} + TEST(SchemaUtilTest, ProjectIdenticalSchemas) { Schema schema = CreateFlatSchema(); From 2517437db1642b30f43b22dd88e84e945140974b Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Thu, 29 Oct 2026 12:00:33 +0800 Subject: [PATCH 05/11] fix(test): use designated initializers for partition evolution cases --- .../test/file_scan_task_reader_test.cc | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index faaeef7018..0b21dd6415 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -555,17 +555,21 @@ TEST_F(FileScanTaskReaderTest, ReadsEvolvedSpecsWithoutLeakingConstantsBetweenFi }; auto identity_spec = std::shared_ptr(std::move(identity)); const std::vector cases{ - {identity_spec, PartitionValues(Literal::String("CN")), - R"([[1, "CN"], [2, "CN"], [3, "CN"]])"}, - {std::move(unpartitioned), PartitionValues(), - R"([[1, "file"], [2, "file"], [3, "file"]])"}, - {std::move(bucket), PartitionValues(Literal::Int(3)), - R"([[1, "file"], [2, "file"], [3, "file"]])"}, - {std::move(reordered), - PartitionValues({Literal::String("retired"), Literal::String("US")}), - R"([[1, "US"], [2, "US"], [3, "US"]])"}, - {identity_spec, PartitionValues(Literal::Null(string())), - "[[1, null], [2, null], [3, null]]"}}; + {.spec = identity_spec, + .partition = PartitionValues(Literal::String("CN")), + .expected = R"([[1, "CN"], [2, "CN"], [3, "CN"]])"}, + {.spec = std::move(unpartitioned), + .partition = PartitionValues(), + .expected = R"([[1, "file"], [2, "file"], [3, "file"]])"}, + {.spec = std::move(bucket), + .partition = PartitionValues(Literal::Int(3)), + .expected = R"([[1, "file"], [2, "file"], [3, "file"]])"}, + {.spec = std::move(reordered), + .partition = PartitionValues({Literal::String("retired"), Literal::String("US")}), + .expected = R"([[1, "US"], [2, "US"], [3, "US"]])"}, + {.spec = identity_spec, + .partition = PartitionValues(Literal::Null(string())), + .expected = "[[1, null], [2, null], [3, null]]"}}; // The current schema omits category, but historical task schemas retain its type. ICEBERG_UNWRAP_OR_FAIL( auto reader, FileScanTaskReader::Make({.io = file_io_, From aac2fdc2b1b661a8d466685a76d8b0196db88c5b Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Thu, 29 Oct 2026 16:44:31 +0800 Subject: [PATCH 06/11] refactor(read): trust constants during schema projection --- src/iceberg/avro/avro_reader.cc | 2 +- src/iceberg/avro/avro_schema_util.cc | 78 ++++++++++--------- src/iceberg/avro/avro_schema_util_internal.h | 8 +- src/iceberg/catalog/rest/json_serde.cc | 2 +- src/iceberg/data/file_scan_task_reader.cc | 21 ++--- src/iceberg/file_reader.h | 8 +- .../parquet_metrics_row_group_filter.cc | 6 +- ...arquet_metrics_row_group_filter_internal.h | 4 +- src/iceberg/parquet/parquet_reader.cc | 20 ++--- src/iceberg/parquet/parquet_schema_util.cc | 23 +++--- .../parquet/parquet_schema_util_internal.h | 8 +- src/iceberg/schema_util.cc | 64 +++++++-------- src/iceberg/schema_util.h | 12 +-- src/iceberg/table_scan.cc | 6 +- src/iceberg/table_scan.h | 11 +-- src/iceberg/test/avro_test.cc | 2 +- src/iceberg/test/parquet_test.cc | 28 ++++--- src/iceberg/test/schema_util_test.cc | 45 ++++++++++- 18 files changed, 200 insertions(+), 148 deletions(-) diff --git a/src/iceberg/avro/avro_reader.cc b/src/iceberg/avro/avro_reader.cc index 051d9e49a7..95c90ad926 100644 --- a/src/iceberg/avro/avro_reader.cc +++ b/src/iceberg/avro/avro_reader.cc @@ -351,7 +351,7 @@ class AvroReader::Impl { // Project the read schema on top of the file schema. ICEBERG_ASSIGN_OR_RAISE(projection_, Project(*read_schema_, file_schema.root(), - /*prune_source=*/false, options.constants)); + /*prune_source=*/false, options.id_to_constant)); ICEBERG_RETURN_UNEXPECTED(backend_->InitWithSchema(file_schema, options.split)); diff --git a/src/iceberg/avro/avro_schema_util.cc b/src/iceberg/avro/avro_schema_util.cc index e1003117cd..e58d1f47a6 100644 --- a/src/iceberg/avro/avro_schema_util.cc +++ b/src/iceberg/avro/avro_schema_util.cc @@ -684,14 +684,14 @@ Status UnwrapUnion(const ::avro::NodePtr& node, ::avro::NodePtr* result) { } // Forward declaration -Result ProjectNested(const Type& expected_type, - const ::avro::NodePtr& avro_node, bool prune_source, - const ColumnConstants& constants); - -Result ProjectField(const SchemaField& expected_field, - const ::avro::NodePtr& avro_node, - size_t source_index, bool prune_source, - const ColumnConstants& constants) { +Result ProjectNested( + const Type& expected_type, const ::avro::NodePtr& avro_node, bool prune_source, + const std::unordered_map& id_to_constant); + +Result ProjectField( + const SchemaField& expected_field, const ::avro::NodePtr& avro_node, + size_t source_index, bool prune_source, + const std::unordered_map& id_to_constant) { const Type& expected_type = *expected_field.type(); ::avro::NodePtr field_node; ICEBERG_RETURN_UNEXPECTED(UnwrapUnion(avro_node, &field_node)); @@ -708,8 +708,8 @@ Result ProjectField(const SchemaField& expected_field, } if (expected_type.is_nested()) { - ICEBERG_ASSIGN_OR_RAISE( - projection, ProjectNested(expected_type, field_node, prune_source, constants)); + ICEBERG_ASSIGN_OR_RAISE(projection, ProjectNested(expected_type, field_node, + prune_source, id_to_constant)); } else { ICEBERG_RETURN_UNEXPECTED(ValidateAvroSchemaEvolution(expected_type, field_node)); } @@ -718,9 +718,9 @@ Result ProjectField(const SchemaField& expected_field, return projection; } -Result ProjectStruct(const StructType& struct_type, - const ::avro::NodePtr& avro_node, bool prune_source, - const ColumnConstants& constants) { +Result ProjectStruct( + const StructType& struct_type, const ::avro::NodePtr& avro_node, bool prune_source, + const std::unordered_map& id_to_constant) { if (avro_node->type() != ::avro::AVRO_RECORD) { return InvalidSchema("Expected AVRO_RECORD type, but got {}", ToString(avro_node)); } @@ -745,21 +745,23 @@ Result ProjectStruct(const StructType& struct_type, } } - FieldProjection result; + FieldProjection result{.kind = FieldProjection::Kind::kProjected}; result.children.reserve(expected_fields.size()); for (const auto& expected_field : expected_fields) { int32_t field_id = expected_field.field_id(); FieldProjection child_projection; - if (auto constant = constants.find(field_id); constant != constants.end()) { - ICEBERG_ASSIGN_OR_RAISE(child_projection, - ProjectConstant(expected_field, constant->second)); + if (auto constant = id_to_constant.find(field_id); constant != id_to_constant.end()) { + child_projection.kind = constant->second.IsNull() + ? FieldProjection::Kind::kNull + : FieldProjection::Kind::kConstant; + child_projection.from = constant->second; } else if (auto iter = node_info_map.find(field_id); iter != node_info_map.cend()) { ICEBERG_ASSIGN_OR_RAISE( child_projection, ProjectField(expected_field, iter->second.field_node, iter->second.local_index, - prune_source, constants)); + prune_source, id_to_constant)); } else if (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (expected_field.initial_default() != nullptr) { @@ -782,9 +784,9 @@ Result ProjectStruct(const StructType& struct_type, return result; } -Result ProjectList(const ListType& list_type, - const ::avro::NodePtr& avro_node, bool prune_source, - const ColumnConstants& constants) { +Result ProjectList( + const ListType& list_type, const ::avro::NodePtr& avro_node, bool prune_source, + const std::unordered_map& id_to_constant) { if (avro_node->type() != ::avro::AVRO_ARRAY) { return InvalidSchema("Expected AVRO_ARRAY type, but got {}", ToString(avro_node)); } @@ -804,20 +806,20 @@ Result ProjectList(const ListType& list_type, ICEBERG_ASSIGN_OR_RAISE( element_projection, ProjectField(expected_element_field, avro_node->leafAt(0), - /*source_index*/ size_t{0}, prune_source, constants)); + /*source_index*/ size_t{0}, prune_source, id_to_constant)); - FieldProjection result; + FieldProjection result{.kind = FieldProjection::Kind::kProjected}; result.children.emplace_back(std::move(element_projection)); return result; } -Result ProjectMap(const MapType& map_type, - const ::avro::NodePtr& avro_node, bool prune_source, - const ColumnConstants& constants) { +Result ProjectMap( + const MapType& map_type, const ::avro::NodePtr& avro_node, bool prune_source, + const std::unordered_map& id_to_constant) { const auto& expected_key_field = map_type.key(); const auto& expected_value_field = map_type.value(); - FieldProjection result; + FieldProjection result{.kind = FieldProjection::Kind::kProjected}; int32_t avro_key_id; int32_t avro_value_id; ::avro::NodePtr map_node; @@ -864,16 +866,16 @@ Result ProjectMap(const MapType& map_type, const auto& expected_sub_field = map_type.fields()[i]; ICEBERG_ASSIGN_OR_RAISE(sub_projection, ProjectField(expected_sub_field, map_node->leafAt(i), i, - prune_source, constants)); + prune_source, id_to_constant)); result.children.emplace_back(std::move(sub_projection)); } return result; } -Result ProjectNested(const Type& expected_type, - const ::avro::NodePtr& avro_node, bool prune_source, - const ColumnConstants& constants) { +Result ProjectNested( + const Type& expected_type, const ::avro::NodePtr& avro_node, bool prune_source, + const std::unordered_map& id_to_constant) { if (!expected_type.is_nested()) { return InvalidSchema("Expected a nested type, but got {}", expected_type); } @@ -881,13 +883,13 @@ Result ProjectNested(const Type& expected_type, switch (expected_type.type_id()) { case TypeId::kStruct: return ProjectStruct(internal::checked_cast(expected_type), - avro_node, prune_source, constants); + avro_node, prune_source, id_to_constant); case TypeId::kList: return ProjectList(internal::checked_cast(expected_type), - avro_node, prune_source, constants); + avro_node, prune_source, id_to_constant); case TypeId::kMap: return ProjectMap(internal::checked_cast(expected_type), avro_node, - prune_source, constants); + prune_source, id_to_constant); default: return InvalidSchema("Unsupported nested type: {}", expected_type); } @@ -901,12 +903,12 @@ bool HasMapLogicalType(const ::avro::NodePtr& node) { node->logicalType().customLogicalType()->name() == "map"; } -Result Project(const Schema& expected_schema, - const ::avro::NodePtr& avro_node, bool prune_source, - const ColumnConstants& constants) { +Result Project( + const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source, + const std::unordered_map& id_to_constant) { ICEBERG_ASSIGN_OR_RAISE(auto field_projection, ProjectNested(static_cast(expected_schema), - avro_node, prune_source, constants)); + avro_node, prune_source, id_to_constant)); return SchemaProjection{std::move(field_projection.children)}; } diff --git a/src/iceberg/avro/avro_schema_util_internal.h b/src/iceberg/avro/avro_schema_util_internal.h index 02ced14441..8d5d420ca9 100644 --- a/src/iceberg/avro/avro_schema_util_internal.h +++ b/src/iceberg/avro/avro_schema_util_internal.h @@ -142,11 +142,11 @@ class HasIdVisitor { /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param avro_node The Avro node to read data from. /// \param prune_source Whether the source schema can be pruned. -/// \param constants File-level values that override physical fields and defaults. +/// \param id_to_constant File-level values that override physical fields and defaults. /// \return The schema projection result. -Result Project(const Schema& expected_schema, - const ::avro::NodePtr& avro_node, bool prune_source, - const ColumnConstants& constants = {}); +Result Project( + const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source, + const std::unordered_map& id_to_constant = {}); std::string ToString(const ::avro::NodePtr& node); std::string ToString(const ::avro::LogicalType& logical_type); diff --git a/src/iceberg/catalog/rest/json_serde.cc b/src/iceberg/catalog/rest/json_serde.cc index 46edba4ab0..23de188fde 100644 --- a/src/iceberg/catalog/rest/json_serde.cc +++ b/src/iceberg/catalog/rest/json_serde.cc @@ -231,7 +231,7 @@ Result>> FileScanTasksFromJson( ICEBERG_ASSIGN_OR_RAISE(residual_filter, ExpressionFromJson(filter_json)); } - std::shared_ptr spec; + std::shared_ptr spec; if (data_file.partition_spec_id.has_value()) { auto it = partition_spec_by_id.find(*data_file.partition_spec_id); if (it != partition_spec_by_id.end()) { diff --git a/src/iceberg/data/file_scan_task_reader.cc b/src/iceberg/data/file_scan_task_reader.cc index 0be1c84b12..23c77fcf4e 100644 --- a/src/iceberg/data/file_scan_task_reader.cc +++ b/src/iceberg/data/file_scan_task_reader.cc @@ -47,15 +47,15 @@ namespace iceberg { namespace { -Result ConstantsOf(const FileScanTask& task) { +Result> ConstantsOf(const FileScanTask& task) { const auto& file = *task.data_file(); const auto& spec = task.spec(); - ColumnConstants constants; + std::unordered_map id_to_constant; if (!spec) { if (file.partition.num_fields() != 0) { return InvalidArgument("A partition spec is required to read partition values"); } - return constants; + return id_to_constant; } if (file.partition_spec_id.has_value() && *file.partition_spec_id != spec->spec_id()) { return InvalidArgument("Data file spec ID {} does not match task spec ID {}", @@ -72,19 +72,20 @@ Result ConstantsOf(const FileScanTask& task) { field.field_id()); } if (field.transform()->transform_type() == TransformType::kIdentity) { - constants.emplace(field.source_id(), file.partition.values()[i]); + id_to_constant.emplace(field.source_id(), file.partition.values()[i]); } } - return constants; + return id_to_constant; } Result MakeReaderOptions( const FileScanTask& task, std::shared_ptr io, - std::shared_ptr projection, std::shared_ptr filter, bool case_sensitive, - std::shared_ptr name_mapping, ReaderProperties properties, - std::optional first_row_id, std::optional data_sequence_number) { + std::shared_ptr projection, std::shared_ptr filter, + bool case_sensitive, std::shared_ptr name_mapping, + ReaderProperties properties, std::optional first_row_id, + std::optional data_sequence_number) { const auto& data_file = *task.data_file(); - ICEBERG_ASSIGN_OR_RAISE(auto constants, ConstantsOf(task)); + ICEBERG_ASSIGN_OR_RAISE(auto id_to_constant, ConstantsOf(task)); return ReaderOptions{ .path = data_file.file_path, .length = static_cast(data_file.file_size_in_bytes), @@ -100,7 +101,7 @@ Result MakeReaderOptions( .first_row_id = first_row_id, .data_sequence_number = data_sequence_number, .properties = std::move(properties), - .constants = std::move(constants), + .id_to_constant = std::move(id_to_constant), }; } diff --git a/src/iceberg/file_reader.h b/src/iceberg/file_reader.h index 1083b0c9f3..8768726c3a 100644 --- a/src/iceberg/file_reader.h +++ b/src/iceberg/file_reader.h @@ -105,9 +105,6 @@ class ICEBERG_EXPORT ReaderProperties : public ConfigBase { const std::unordered_map& properties); }; -/// File-level primitive values keyed by source field ID, including typed nulls. -using ColumnConstants = std::unordered_map; - /// \brief Options for creating a reader. struct ICEBERG_EXPORT ReaderOptions { /// \brief The path to the file to read. @@ -137,8 +134,9 @@ struct ICEBERG_EXPORT ReaderOptions { /// File-level values keyed by field ID, overriding physical columns, /// initial defaults and optional-field nulls, matching Iceberg Java. - /// Example: `options.constants.emplace(2, Literal::String("CN"));` - ColumnConstants constants; + /// Example: `options.id_to_constant.emplace(2, Literal::String("CN"));` + // TODO(yzsun): Use a nested value representation if struct constants are needed. + std::unordered_map id_to_constant; }; /// \brief Factory function to create a reader of a specific file format. diff --git a/src/iceberg/parquet/parquet_metrics_row_group_filter.cc b/src/iceberg/parquet/parquet_metrics_row_group_filter.cc index a607bdadbd..6aefa02d99 100644 --- a/src/iceberg/parquet/parquet_metrics_row_group_filter.cc +++ b/src/iceberg/parquet/parquet_metrics_row_group_filter.cc @@ -291,12 +291,14 @@ class MetricsVisitor : public BoundVisitor { Result> ParquetMetricsRowGroupFilter::Make( const std::shared_ptr& filter, - const ::parquet::SchemaDescriptor& file_schema) { + const ::parquet::SchemaDescriptor& file_schema, + const std::unordered_map& id_to_constant) { auto result = std::unique_ptr(new ParquetMetricsRowGroupFilter()); for (int i = 0; i < file_schema.num_columns(); ++i) { auto id = file_schema.Column(i)->schema_node()->field_id(); - if (id >= 0) { + // Footer statistics describe physical values, not substituted constants. + if (id >= 0 && !id_to_constant.contains(id)) { result->field_id_to_column_idx_.emplace(id, i); } } diff --git a/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h b/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h index 5d80fe3bfe..b28f7bf4ac 100644 --- a/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h +++ b/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h @@ -25,6 +25,7 @@ #include +#include "iceberg/expression/literal.h" #include "iceberg/iceberg_bundle_export.h" #include "iceberg/result.h" #include "iceberg/type_fwd.h" @@ -38,7 +39,8 @@ class ICEBERG_BUNDLE_EXPORT ParquetMetricsRowGroupFilter { public: static Result> Make( const std::shared_ptr& filter, - const ::parquet::SchemaDescriptor& file_schema); + const ::parquet::SchemaDescriptor& file_schema, + const std::unordered_map& id_to_constant = {}); Result ShouldRead(const ::parquet::arrow::SchemaManifest& manifest, const ::parquet::RowGroupMetaData& row_group) const; diff --git a/src/iceberg/parquet/parquet_reader.cc b/src/iceberg/parquet/parquet_reader.cc index 27da5e888a..9590e25b88 100644 --- a/src/iceberg/parquet/parquet_reader.cc +++ b/src/iceberg/parquet/parquet_reader.cc @@ -63,10 +63,10 @@ Result> OpenInputStream( return arrow::OpenArrowInputStream(options.io, options.path, options.length); } -Result BuildProjection(::parquet::arrow::FileReader* reader, - const Schema& read_schema, - const NameMapping* name_mapping, - const ColumnConstants& constants) { +Result BuildProjection( + ::parquet::arrow::FileReader* reader, const Schema& read_schema, + const NameMapping* name_mapping, + const std::unordered_map& id_to_constant) { auto metadata = reader->parquet_reader()->metadata(); if (!HasFieldIds(metadata->schema()->schema_root())) { @@ -79,10 +79,11 @@ Result BuildProjection(::parquet::arrow::FileReader* reader, metadata->schema(), metadata->key_value_metadata(), reader->properties(), &schema_manifest)); ApplyNameMapping(*name_mapping, &schema_manifest); - return Project(read_schema, schema_manifest, constants); + return Project(read_schema, schema_manifest, id_to_constant); } - ICEBERG_ASSIGN_OR_RAISE(auto projection, Project(read_schema, reader->manifest(), constants)); + ICEBERG_ASSIGN_OR_RAISE(auto projection, + Project(read_schema, reader->manifest(), id_to_constant)); return projection; } @@ -161,7 +162,7 @@ class ParquetReader::Impl { // Project read schema onto the Parquet file schema ICEBERG_ASSIGN_OR_RAISE( projection_, BuildProjection(reader_.get(), *read_schema_, - options.name_mapping.get(), options.constants)); + options.name_mapping.get(), options.id_to_constant)); if (options.filter && options.properties.Get(ReaderProperties::kParquetRowGroupFilter)) { auto filter = options.filter; @@ -170,8 +171,9 @@ class ParquetReader::Impl { ICEBERG_ASSIGN_OR_RAISE( filter, Binder::Bind(*options.projection, filter, options.case_sensitive)); } - ICEBERG_ASSIGN_OR_RAISE(stats_filter_, ParquetMetricsRowGroupFilter::Make( - filter, *reader_->manifest().descr)); + ICEBERG_ASSIGN_OR_RAISE( + stats_filter_, ParquetMetricsRowGroupFilter::Make( + filter, *reader_->manifest().descr, options.id_to_constant)); ICEBERG_ASSIGN_OR_RAISE( dictionary_filter_, ParquetDictionaryRowGroupFilter::Make(filter, *reader_->manifest().descr)); diff --git a/src/iceberg/parquet/parquet_schema_util.cc b/src/iceberg/parquet/parquet_schema_util.cc index 9af60284bb..34ae158cd6 100644 --- a/src/iceberg/parquet/parquet_schema_util.cc +++ b/src/iceberg/parquet/parquet_schema_util.cc @@ -505,8 +505,8 @@ namespace { class ProjectionBuilder { public: ProjectionBuilder(const ::parquet::SchemaDescriptor* descr, - const ColumnConstants& constants) - : descr_(descr), constants_(constants) {} + const std::unordered_map& id_to_constant) + : descr_(descr), id_to_constant_(id_to_constant) {} Result Project( const Type& nested_type, @@ -589,9 +589,12 @@ class ProjectionBuilder { int32_t field_id = field.field_id(); FieldProjection child_projection; - if (auto constant = constants_.find(field_id); constant != constants_.end()) { - ICEBERG_ASSIGN_OR_RAISE(child_projection, - ProjectConstant(field, constant->second)); + if (auto constant = id_to_constant_.find(field_id); + constant != id_to_constant_.end()) { + child_projection.kind = constant->second.IsNull() + ? FieldProjection::Kind::kNull + : FieldProjection::Kind::kConstant; + child_projection.from = constant->second; } else if (auto iter = field_context_map.find(field_id); iter != field_context_map.cend()) { const auto& parquet_field = iter->second.parquet_field; @@ -724,7 +727,7 @@ class ProjectionBuilder { } const ::parquet::SchemaDescriptor* descr_; - const ColumnConstants& constants_; + const std::unordered_map& id_to_constant_; }; void CollectColumnIds(const FieldProjection& field_projection, @@ -789,10 +792,10 @@ void ApplyNameMappingToField(const NameMapping& mapping, std::vector Project(const Schema& expected_schema, - const ::parquet::arrow::SchemaManifest& parquet_schema, - const ColumnConstants& constants) { - ProjectionBuilder builder(parquet_schema.descr, constants); +Result Project( + const Schema& expected_schema, const ::parquet::arrow::SchemaManifest& parquet_schema, + const std::unordered_map& id_to_constant) { + ProjectionBuilder builder(parquet_schema.descr, id_to_constant); ICEBERG_ASSIGN_OR_RAISE(auto field_projection, builder.Project(static_cast(expected_schema), parquet_schema.schema_fields)); diff --git a/src/iceberg/parquet/parquet_schema_util_internal.h b/src/iceberg/parquet/parquet_schema_util_internal.h index 37af7574c7..18c4ce6307 100644 --- a/src/iceberg/parquet/parquet_schema_util_internal.h +++ b/src/iceberg/parquet/parquet_schema_util_internal.h @@ -54,12 +54,12 @@ Status ValidateParquetTypeCompatibility( /// /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param parquet_schema The Parquet schema to read data from. -/// \param constants File-level values that override physical fields and defaults. +/// \param id_to_constant File-level values that override physical fields and defaults. /// \return The schema projection result with column indices of projected Parquet columns /// specified via ParquetExtraAttributes. -Result Project(const Schema& expected_schema, - const ::parquet::arrow::SchemaManifest& parquet_schema, - const ColumnConstants& constants = {}); +Result Project( + const Schema& expected_schema, const ::parquet::arrow::SchemaManifest& parquet_schema, + const std::unordered_map& id_to_constant = {}); /// \brief Get the selected column indices by walking through the projection result. /// diff --git a/src/iceberg/schema_util.cc b/src/iceberg/schema_util.cc index 36143a7510..2194f3212d 100644 --- a/src/iceberg/schema_util.cc +++ b/src/iceberg/schema_util.cc @@ -82,12 +82,14 @@ Status ValidateSchemaEvolution(const Type& expected_type, const Type& source_typ return NotSupported("Cannot read {} from {}", expected_type, source_type); } -Result ProjectNested(const Type& expected_type, const Type& source_type, - bool prune_source, ProjectionMode mode); +Result ProjectNested( + const Type& expected_type, const Type& source_type, bool prune_source, + ProjectionMode mode, const std::unordered_map& id_to_constant); -Result ProjectField(const SchemaField& expected_field, - const SchemaField& source_field, size_t source_index, - bool prune_source, ProjectionMode mode) { +Result ProjectField( + const SchemaField& expected_field, const SchemaField& source_field, + size_t source_index, bool prune_source, ProjectionMode mode, + const std::unordered_map& id_to_constant) { FieldProjection projection; if (mode == ProjectionMode::kWrite && source_field.optional() && @@ -123,9 +125,9 @@ Result ProjectField(const SchemaField& expected_field, } if (expected_field.type()->is_nested()) { - ICEBERG_ASSIGN_OR_RAISE( - projection, - ProjectNested(*expected_field.type(), *source_field.type(), prune_source, mode)); + ICEBERG_ASSIGN_OR_RAISE(projection, + ProjectNested(*expected_field.type(), *source_field.type(), + prune_source, mode, id_to_constant)); } else if (mode == ProjectionMode::kWrite) { if (*expected_field.type() != *source_field.type()) { return NotSupported("Cannot project {} as {}: type promotion is not allowed", @@ -144,8 +146,9 @@ Result ProjectField(const SchemaField& expected_field, return projection; } -Result ProjectNested(const Type& expected_type, const Type& source_type, - bool prune_source, ProjectionMode mode) { +Result ProjectNested( + const Type& expected_type, const Type& source_type, bool prune_source, + ProjectionMode mode, const std::unordered_map& id_to_constant) { if (!expected_type.is_nested()) { return InvalidSchema("Expected a nested type, but got {}", expected_type); } @@ -184,10 +187,18 @@ Result ProjectNested(const Type& expected_type, const Type& sou int32_t field_id = expected_field.field_id(); FieldProjection child_projection; - if (auto iter = source_field_map.find(field_id); iter != source_field_map.cend()) { - ICEBERG_ASSIGN_OR_RAISE(child_projection, - ProjectField(expected_field, *iter->second.field, - iter->second.local_index, prune_source, mode)); + if (auto constant = id_to_constant.find(field_id); + mode == ProjectionMode::kRead && constant != id_to_constant.end()) { + child_projection.kind = constant->second.IsNull() + ? FieldProjection::Kind::kNull + : FieldProjection::Kind::kConstant; + child_projection.from = constant->second; + } else if (auto iter = source_field_map.find(field_id); + iter != source_field_map.cend()) { + ICEBERG_ASSIGN_OR_RAISE( + child_projection, + ProjectField(expected_field, *iter->second.field, iter->second.local_index, + prune_source, mode, id_to_constant)); if (mode == ProjectionMode::kWrite) { source_field_map.erase(iter); } @@ -206,7 +217,6 @@ Result ProjectNested(const Type& expected_type, const Type& sou } else if (expected_field.optional()) { child_projection.kind = FieldProjection::Kind::kNull; } else { - // TODO(gangwu): support constant value if (mode == ProjectionMode::kWrite) { return InvalidSchema("Missing required field: {} without a write-default", expected_field.ToString()); @@ -230,28 +240,12 @@ Result ProjectNested(const Type& expected_type, const Type& sou } // namespace -Result ProjectConstant(const SchemaField& field, - const Literal& literal) { - if (field.type() == nullptr || !field.type()->is_primitive() || - literal.type() == nullptr || literal.IsAboveMax() || literal.IsBelowMin()) { - return InvalidSchema("Invalid constant for field {}", field.field_id()); - } - ICEBERG_RETURN_UNEXPECTED(ValidateSchemaEvolution(*field.type(), *literal.type())); - if (literal.IsNull() && !field.optional()) { - return InvalidSchema("Null constant for required field {}", field.field_id()); - } - if (literal.IsNull()) { - return FieldProjection{.kind = FieldProjection::Kind::kNull}; - } - return FieldProjection{.kind = FieldProjection::Kind::kConstant, .from = literal}; -} - -Result Project(const Schema& expected_schema, - const Schema& source_schema, bool prune_source, - ProjectionMode mode) { +Result Project( + const Schema& expected_schema, const Schema& source_schema, bool prune_source, + ProjectionMode mode, const std::unordered_map& id_to_constant) { ICEBERG_ASSIGN_OR_RAISE( auto field_projection, - ProjectNested(expected_schema, source_schema, prune_source, mode)); + ProjectNested(expected_schema, source_schema, prune_source, mode, id_to_constant)); return SchemaProjection{std::move(field_projection.children)}; } diff --git a/src/iceberg/schema_util.h b/src/iceberg/schema_util.h index db8e1dbe48..23933d2af7 100644 --- a/src/iceberg/schema_util.h +++ b/src/iceberg/schema_util.h @@ -24,11 +24,11 @@ #include #include +#include #include #include #include "iceberg/expression/literal.h" -#include "iceberg/file_reader.h" #include "iceberg/iceberg_export.h" #include "iceberg/result.h" #include "iceberg/type_fwd.h" @@ -100,14 +100,14 @@ enum class ProjectionMode { /// field in `FieldProjection` exactly reflects the position (relative to its nesting /// level) to get the column value from the reader. /// \param mode Whether to project for reading or writing. +/// \param id_to_constant Primitive values keyed by source field ID. Constants override +/// physical fields and defaults, including primitive leaves of existing structs. Only +/// applied when `mode` is `ProjectionMode::kRead`. /// \return The projection result. ICEBERG_EXPORT Result Project( const Schema& expected_schema, const Schema& source_schema, bool prune_source, - ProjectionMode mode = ProjectionMode::kRead); - -/// Build a primitive constant projection, validating type promotion and nullability. -ICEBERG_EXPORT Result ProjectConstant(const SchemaField& field, - const Literal& literal); + ProjectionMode mode = ProjectionMode::kRead, + const std::unordered_map& id_to_constant = {}); ICEBERG_EXPORT std::string_view ToString(FieldProjection::Kind kind); ICEBERG_EXPORT std::string ToString(const FieldProjection& projection); diff --git a/src/iceberg/table_scan.cc b/src/iceberg/table_scan.cc index ded076981a..ca3835303e 100644 --- a/src/iceberg/table_scan.cc +++ b/src/iceberg/table_scan.cc @@ -175,7 +175,7 @@ ScanTask::~ScanTask() = default; FileScanTask::FileScanTask(std::shared_ptr data_file, std::vector> delete_files, std::shared_ptr residual_filter, - std::shared_ptr spec) + std::shared_ptr spec) : data_file_(std::move(data_file)), delete_files_(std::move(delete_files)), residual_filter_(std::move(residual_filter)), @@ -186,7 +186,7 @@ FileScanTask::FileScanTask(std::shared_ptr data_file, FileScanTask::FileScanTask(std::shared_ptr data_file, std::vector> delete_files, std::shared_ptr residual_filter, Range range, - std::shared_ptr spec) + std::shared_ptr spec) : FileScanTask(std::move(data_file), std::move(delete_files), std::move(residual_filter), std::move(spec)) { range_ = range; @@ -195,7 +195,7 @@ FileScanTask::FileScanTask(std::shared_ptr data_file, Result> FileScanTask::MakeSplit( std::shared_ptr data_file, int64_t start, int64_t length, std::vector> delete_files, - std::shared_ptr filter, std::shared_ptr spec) { + std::shared_ptr filter, std::shared_ptr spec) { if (data_file == nullptr) { return InvalidArgument("Cannot create a file scan task without a data file"); } diff --git a/src/iceberg/table_scan.h b/src/iceberg/table_scan.h index 10d9274931..7819bf41b1 100644 --- a/src/iceberg/table_scan.h +++ b/src/iceberg/table_scan.h @@ -79,7 +79,7 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { explicit FileScanTask(std::shared_ptr data_file, std::vector> delete_files = {}, std::shared_ptr filter = nullptr, - std::shared_ptr spec = nullptr); + std::shared_ptr spec = nullptr); /// \brief Make a task for a validated half-open byte range [start, start + length). /// @@ -91,7 +91,7 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { std::shared_ptr data_file, int64_t start, int64_t length, std::vector> delete_files = {}, std::shared_ptr filter = nullptr, - std::shared_ptr spec = nullptr); + std::shared_ptr spec = nullptr); /// \brief The inclusive byte offset where this task starts, or zero for a whole file. int64_t start() const { return range_ ? range_->start : 0; } @@ -114,7 +114,8 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { const std::shared_ptr& residual_filter() const { return residual_filter_; } /// The partition spec used to write this file, including historical field IDs. - const std::shared_ptr& spec() const { return spec_; } + /// The shared spec must not be mutated while the task is in use. + const std::shared_ptr& spec() const { return spec_; } Kind kind() const override { return Kind::kFileScanTask; } int64_t size_bytes() const override; @@ -135,13 +136,13 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { FileScanTask(std::shared_ptr data_file, std::vector> delete_files, std::shared_ptr filter, Range range, - std::shared_ptr spec); + std::shared_ptr spec); std::shared_ptr data_file_; std::vector> delete_files_; std::shared_ptr residual_filter_; std::optional range_; - std::shared_ptr spec_; + std::shared_ptr spec_; }; /// \brief Stream of file scan tasks. diff --git a/src/iceberg/test/avro_test.cc b/src/iceberg/test/avro_test.cc index 634ecf3f8d..d4c9954236 100644 --- a/src/iceberg/test/avro_test.cc +++ b/src/iceberg/test/avro_test.cc @@ -575,7 +575,7 @@ TEST_P(AvroReaderParameterizedTest, ReadsPartitionConstants) { SchemaField::MakeOptional(4, "missing", string())}); ReaderOptions options{.path = temp_avro_file_, .io = file_io_, .projection = schema}; options.properties.Set(ReaderProperties::kAvroSkipDatum, skip_datum_); - options.constants = { + options.id_to_constant = { {1, Literal::Int(999)}, {3, Literal::String("CN")}, {4, Literal::Null(string())}}; ICEBERG_UNWRAP_OR_FAIL(auto reader, ReaderFactoryRegistry::Open(FileFormatType::kAvro, options)); diff --git a/src/iceberg/test/parquet_test.cc b/src/iceberg/test/parquet_test.cc index cd70952eec..3639833d39 100644 --- a/src/iceberg/test/parquet_test.cc +++ b/src/iceberg/test/parquet_test.cc @@ -45,6 +45,7 @@ #include "iceberg/arrow/arrow_io_internal.h" #include "iceberg/arrow/arrow_status_internal.h" +#include "iceberg/expression/expressions.h" #include "iceberg/expression/literal.h" #include "iceberg/file_reader.h" #include "iceberg/file_writer.h" @@ -517,19 +518,28 @@ class ParquetReaderTest : public TempFileTestBase { std::string temp_parquet_file_; }; -TEST_F(ParquetReaderTest, ConstantsValidateTypesAndRequiredNulls) { +TEST_F(ParquetReaderTest, PromotesPartitionConstant) { CreateSimpleParquetFile(); auto schema = std::make_shared( std::vector{SchemaField::MakeRequired(3, "constant", int64())}); - for (const auto& value : {Literal::String("7"), Literal::Null(int64())}) { - ReaderOptions options{ - .path = temp_parquet_file_, .io = file_io_, .projection = schema}; - options.constants.emplace(3, value); - EXPECT_FALSE( - ReaderFactoryRegistry::Open(FileFormatType::kParquet, options).has_value()); - } + ReaderOptions options{.path = temp_parquet_file_, .io = file_io_, .projection = schema}; - options.constants.emplace(3, Literal::Int(7)); + options.id_to_constant.emplace(3, Literal::Int(7)); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + ReaderFactoryRegistry::Open(FileFormatType::kParquet, options)); + VerifyNextBatch(*reader, "[[7], [7], [7]]"); + VerifyExhausted(*reader); +} + +TEST_F(ParquetReaderTest, ConstantsDoNotUsePhysicalColumnStatistics) { + CreateSimpleParquetFile(); + auto schema = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int32())}); + ReaderOptions options{.path = temp_parquet_file_, + .io = file_io_, + .projection = schema, + .filter = Expressions::Equal("id", Literal::Int(7))}; + options.id_to_constant.emplace(1, Literal::Int(7)); ICEBERG_UNWRAP_OR_FAIL(auto reader, ReaderFactoryRegistry::Open(FileFormatType::kParquet, options)); VerifyNextBatch(*reader, "[[7], [7], [7]]"); diff --git a/src/iceberg/test/schema_util_test.cc b/src/iceberg/test/schema_util_test.cc index 3cbe7d5be7..90275913cf 100644 --- a/src/iceberg/test/schema_util_test.cc +++ b/src/iceberg/test/schema_util_test.cc @@ -101,10 +101,47 @@ std::shared_ptr CreateMapOfList() { } // namespace -TEST(SchemaUtilTest, ProjectConstantRejectsMissingFieldType) { - auto field = SchemaField::MakeOptional(1, "invalid", nullptr); - ASSERT_THAT(ProjectConstant(field, Literal::Long(7)), - IsError(ErrorKind::kInvalidSchema)); +TEST(SchemaUtilTest, ProjectConstantsOverridePhysicalFieldsAndPruneIndices) { + Schema schema({SchemaField::MakeRequired(1, "region", string()), + SchemaField::MakeRequired(2, "id", int64())}); + for (bool prune_source : {false, true}) { + auto projection = Project(schema, schema, prune_source, ProjectionMode::kRead, + {{1, Literal::String("CN")}}); + ASSERT_THAT(projection, IsOk()); + ASSERT_EQ(projection->fields.size(), 2); + EXPECT_EQ(projection->fields[0].kind, FieldProjection::Kind::kConstant); + EXPECT_EQ(std::get(projection->fields[0].from), Literal::String("CN")); + AssertProjectedField(projection->fields[1], prune_source ? 0 : 1); + } +} + +TEST(SchemaUtilTest, ProjectConstantsFillMissingFields) { + Schema expected({SchemaField::MakeRequired(1, "id", int64()), + SchemaField::MakeOptional(2, "region", string())}); + auto projection = + Project(expected, Schema({}), /*prune_source=*/true, ProjectionMode::kRead, + {{1, Literal::Int(7)}, {2, Literal::Null(string())}}); + ASSERT_THAT(projection, IsOk()); + ASSERT_EQ(projection->fields.size(), 2); + EXPECT_EQ(projection->fields[0].kind, FieldProjection::Kind::kConstant); + EXPECT_EQ(projection->fields[1].kind, FieldProjection::Kind::kNull); +} + +TEST(SchemaUtilTest, ProjectConstantsIntoExistingStruct) { + Schema schema( + {SchemaField::MakeOptional(1, "parent", + std::make_shared(std::vector{ + SchemaField::MakeOptional(2, "region", string()), + SchemaField::MakeRequired(3, "id", int64())}))}); + auto projection = Project(schema, schema, /*prune_source=*/true, ProjectionMode::kRead, + {{2, Literal::String("CN")}}); + ASSERT_THAT(projection, IsOk()); + ASSERT_EQ(projection->fields.size(), 1); + const auto& parent = projection->fields[0]; + AssertProjectedField(parent, 0); + ASSERT_EQ(parent.children.size(), 2); + EXPECT_EQ(parent.children[0].kind, FieldProjection::Kind::kConstant); + AssertProjectedField(parent.children[1], 0); } TEST(SchemaUtilTest, ProjectIdenticalSchemas) { From c7e2ce225588398d3adaeb181d3b57fc0773151d Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Thu, 29 Oct 2026 16:52:16 +0800 Subject: [PATCH 07/11] refactor(read): trust task partition context --- src/iceberg/data/file_scan_task_reader.cc | 8 -------- src/iceberg/test/file_scan_task_reader_test.cc | 10 +--------- 2 files changed, 1 insertion(+), 17 deletions(-) diff --git a/src/iceberg/data/file_scan_task_reader.cc b/src/iceberg/data/file_scan_task_reader.cc index 23c77fcf4e..c189d7b04f 100644 --- a/src/iceberg/data/file_scan_task_reader.cc +++ b/src/iceberg/data/file_scan_task_reader.cc @@ -57,14 +57,6 @@ Result> ConstantsOf(const FileScanTask& tas } return id_to_constant; } - if (file.partition_spec_id.has_value() && *file.partition_spec_id != spec->spec_id()) { - return InvalidArgument("Data file spec ID {} does not match task spec ID {}", - *file.partition_spec_id, spec->spec_id()); - } - if (file.partition.num_fields() != spec->fields().size()) { - return InvalidArgument("Partition value count {} does not match spec field count {}", - file.partition.num_fields(), spec->fields().size()); - } for (size_t i = 0; i < spec->fields().size(); ++i) { const auto& field = spec->fields()[i]; if (field.transform() == nullptr) { diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index 0b21dd6415..a56e3a7f39 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -610,7 +610,7 @@ TEST_F(FileScanTaskReaderTest, ReadsEvolvedSpecsWithoutLeakingConstantsBetweenFi } } -TEST_F(FileScanTaskReaderTest, RejectsMissingOrInconsistentPartitionContext) { +TEST_F(FileScanTaskReaderTest, RejectsMissingPartitionSpec) { ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(table_schema_, R"([[1, "Foo", "blue"]])", 1)); ICEBERG_UNWRAP_OR_FAIL( @@ -620,14 +620,6 @@ TEST_F(FileScanTaskReaderTest, RejectsMissingOrInconsistentPartitionContext) { .projected_schema = projected_schema_})); file->partition = PartitionValues({Literal::String("CN")}); EXPECT_FALSE(reader->Open(FileScanTask(file)).has_value()); - ICEBERG_UNWRAP_OR_FAIL( - auto spec, PartitionSpec::Make(3, {{2, 1000, "name", Transform::Identity()}})); - auto shared_spec = std::shared_ptr(std::move(spec)); - file->partition_spec_id = 9; - EXPECT_FALSE(reader->Open(FileScanTask(file, {}, nullptr, shared_spec)).has_value()); - file->partition_spec_id = 3; - file->partition = PartitionValues{}; - EXPECT_FALSE(reader->Open(FileScanTask(file, {}, nullptr, shared_spec)).has_value()); } TEST_F(FileScanTaskReaderTest, OpenWithoutDeletesReadsProjectedSchema) { From 7ba1fb6281d0427c4ee2a754378fc117bb813e7e Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Thu, 29 Oct 2026 17:11:16 +0800 Subject: [PATCH 08/11] refactor(read): preserve row group filter interface --- .../parquet/parquet_metrics_row_group_filter.cc | 6 ++---- .../parquet_metrics_row_group_filter_internal.h | 4 +--- src/iceberg/parquet/parquet_reader.cc | 5 ++--- src/iceberg/test/parquet_test.cc | 15 --------------- 4 files changed, 5 insertions(+), 25 deletions(-) diff --git a/src/iceberg/parquet/parquet_metrics_row_group_filter.cc b/src/iceberg/parquet/parquet_metrics_row_group_filter.cc index 6aefa02d99..a607bdadbd 100644 --- a/src/iceberg/parquet/parquet_metrics_row_group_filter.cc +++ b/src/iceberg/parquet/parquet_metrics_row_group_filter.cc @@ -291,14 +291,12 @@ class MetricsVisitor : public BoundVisitor { Result> ParquetMetricsRowGroupFilter::Make( const std::shared_ptr& filter, - const ::parquet::SchemaDescriptor& file_schema, - const std::unordered_map& id_to_constant) { + const ::parquet::SchemaDescriptor& file_schema) { auto result = std::unique_ptr(new ParquetMetricsRowGroupFilter()); for (int i = 0; i < file_schema.num_columns(); ++i) { auto id = file_schema.Column(i)->schema_node()->field_id(); - // Footer statistics describe physical values, not substituted constants. - if (id >= 0 && !id_to_constant.contains(id)) { + if (id >= 0) { result->field_id_to_column_idx_.emplace(id, i); } } diff --git a/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h b/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h index b28f7bf4ac..5d80fe3bfe 100644 --- a/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h +++ b/src/iceberg/parquet/parquet_metrics_row_group_filter_internal.h @@ -25,7 +25,6 @@ #include -#include "iceberg/expression/literal.h" #include "iceberg/iceberg_bundle_export.h" #include "iceberg/result.h" #include "iceberg/type_fwd.h" @@ -39,8 +38,7 @@ class ICEBERG_BUNDLE_EXPORT ParquetMetricsRowGroupFilter { public: static Result> Make( const std::shared_ptr& filter, - const ::parquet::SchemaDescriptor& file_schema, - const std::unordered_map& id_to_constant = {}); + const ::parquet::SchemaDescriptor& file_schema); Result ShouldRead(const ::parquet::arrow::SchemaManifest& manifest, const ::parquet::RowGroupMetaData& row_group) const; diff --git a/src/iceberg/parquet/parquet_reader.cc b/src/iceberg/parquet/parquet_reader.cc index 9590e25b88..6b5a325952 100644 --- a/src/iceberg/parquet/parquet_reader.cc +++ b/src/iceberg/parquet/parquet_reader.cc @@ -171,9 +171,8 @@ class ParquetReader::Impl { ICEBERG_ASSIGN_OR_RAISE( filter, Binder::Bind(*options.projection, filter, options.case_sensitive)); } - ICEBERG_ASSIGN_OR_RAISE( - stats_filter_, ParquetMetricsRowGroupFilter::Make( - filter, *reader_->manifest().descr, options.id_to_constant)); + ICEBERG_ASSIGN_OR_RAISE(stats_filter_, ParquetMetricsRowGroupFilter::Make( + filter, *reader_->manifest().descr)); ICEBERG_ASSIGN_OR_RAISE( dictionary_filter_, ParquetDictionaryRowGroupFilter::Make(filter, *reader_->manifest().descr)); diff --git a/src/iceberg/test/parquet_test.cc b/src/iceberg/test/parquet_test.cc index 3639833d39..4edeed1fa7 100644 --- a/src/iceberg/test/parquet_test.cc +++ b/src/iceberg/test/parquet_test.cc @@ -531,21 +531,6 @@ TEST_F(ParquetReaderTest, PromotesPartitionConstant) { VerifyExhausted(*reader); } -TEST_F(ParquetReaderTest, ConstantsDoNotUsePhysicalColumnStatistics) { - CreateSimpleParquetFile(); - auto schema = std::make_shared( - std::vector{SchemaField::MakeRequired(1, "id", int32())}); - ReaderOptions options{.path = temp_parquet_file_, - .io = file_io_, - .projection = schema, - .filter = Expressions::Equal("id", Literal::Int(7))}; - options.id_to_constant.emplace(1, Literal::Int(7)); - ICEBERG_UNWRAP_OR_FAIL(auto reader, - ReaderFactoryRegistry::Open(FileFormatType::kParquet, options)); - VerifyNextBatch(*reader, "[[7], [7], [7]]"); - VerifyExhausted(*reader); -} - TEST_F(ParquetReaderTest, ReadTwoFields) { CreateSimpleParquetFile(); From 71486eea96af373951228107706200ec72ebf2a9 Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Thu, 29 Oct 2026 17:21:15 +0800 Subject: [PATCH 09/11] refactor(read): project null partition values as constants --- src/iceberg/avro/avro_schema_util.cc | 4 +--- src/iceberg/parquet/parquet_schema_util.cc | 4 +--- src/iceberg/schema_util.cc | 4 +--- src/iceberg/test/file_scan_task_reader_test.cc | 3 ++- src/iceberg/test/schema_util_test.cc | 2 +- 5 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/iceberg/avro/avro_schema_util.cc b/src/iceberg/avro/avro_schema_util.cc index e58d1f47a6..819dbf9757 100644 --- a/src/iceberg/avro/avro_schema_util.cc +++ b/src/iceberg/avro/avro_schema_util.cc @@ -753,9 +753,7 @@ Result ProjectStruct( FieldProjection child_projection; if (auto constant = id_to_constant.find(field_id); constant != id_to_constant.end()) { - child_projection.kind = constant->second.IsNull() - ? FieldProjection::Kind::kNull - : FieldProjection::Kind::kConstant; + child_projection.kind = FieldProjection::Kind::kConstant; child_projection.from = constant->second; } else if (auto iter = node_info_map.find(field_id); iter != node_info_map.cend()) { ICEBERG_ASSIGN_OR_RAISE( diff --git a/src/iceberg/parquet/parquet_schema_util.cc b/src/iceberg/parquet/parquet_schema_util.cc index 34ae158cd6..21e1f4b5c1 100644 --- a/src/iceberg/parquet/parquet_schema_util.cc +++ b/src/iceberg/parquet/parquet_schema_util.cc @@ -591,9 +591,7 @@ class ProjectionBuilder { if (auto constant = id_to_constant_.find(field_id); constant != id_to_constant_.end()) { - child_projection.kind = constant->second.IsNull() - ? FieldProjection::Kind::kNull - : FieldProjection::Kind::kConstant; + child_projection.kind = FieldProjection::Kind::kConstant; child_projection.from = constant->second; } else if (auto iter = field_context_map.find(field_id); iter != field_context_map.cend()) { diff --git a/src/iceberg/schema_util.cc b/src/iceberg/schema_util.cc index 2194f3212d..1499aa6311 100644 --- a/src/iceberg/schema_util.cc +++ b/src/iceberg/schema_util.cc @@ -189,9 +189,7 @@ Result ProjectNested( if (auto constant = id_to_constant.find(field_id); mode == ProjectionMode::kRead && constant != id_to_constant.end()) { - child_projection.kind = constant->second.IsNull() - ? FieldProjection::Kind::kNull - : FieldProjection::Kind::kConstant; + child_projection.kind = FieldProjection::Kind::kConstant; child_projection.from = constant->second; } else if (auto iter = source_field_map.find(field_id); iter != source_field_map.cend()) { diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index a56e3a7f39..f70a13dbb4 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -537,7 +537,8 @@ TEST_F(FileScanTaskReaderTest, NullIdentityOverridesInitialDefault) { VerifyStream(&stream, "[[null], [null], [null]]"); } -TEST_F(FileScanTaskReaderTest, ReadsEvolvedSpecsWithoutLeakingConstantsBetweenFiles) { +TEST_F(FileScanTaskReaderTest, + ReadsTaskSpecificSpecsWithoutLeakingConstantsBetweenFiles) { ICEBERG_UNWRAP_OR_FAIL( auto identity, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}})); ICEBERG_UNWRAP_OR_FAIL(auto unpartitioned, PartitionSpec::Make(8, {})); diff --git a/src/iceberg/test/schema_util_test.cc b/src/iceberg/test/schema_util_test.cc index 90275913cf..642aa9e7bf 100644 --- a/src/iceberg/test/schema_util_test.cc +++ b/src/iceberg/test/schema_util_test.cc @@ -124,7 +124,7 @@ TEST(SchemaUtilTest, ProjectConstantsFillMissingFields) { ASSERT_THAT(projection, IsOk()); ASSERT_EQ(projection->fields.size(), 2); EXPECT_EQ(projection->fields[0].kind, FieldProjection::Kind::kConstant); - EXPECT_EQ(projection->fields[1].kind, FieldProjection::Kind::kNull); + EXPECT_EQ(projection->fields[1].kind, FieldProjection::Kind::kConstant); } TEST(SchemaUtilTest, ProjectConstantsIntoExistingStruct) { From de01c10d094471293c2bd6748379972ea437265d Mon Sep 17 00:00:00 2001 From: yinzhengsun Date: Wed, 25 Nov 2026 11:53:04 +0800 Subject: [PATCH 10/11] fix(read): validate partition constants and spec lookup Check partition tuple arity against the spec and use bounds-checked access when reading identity partition constants. Replace the throwing specs_by_id_.at() lookup in ManifestGroup with a checked find. Make the split test use a proper sub-range so the split constructor path is exercised. --- src/iceberg/data/file_scan_task_reader.cc | 9 ++++++- src/iceberg/manifest/manifest_group.cc | 6 ++++- .../test/file_scan_task_reader_test.cc | 24 +++++++++++++++++-- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/iceberg/data/file_scan_task_reader.cc b/src/iceberg/data/file_scan_task_reader.cc index c189d7b04f..1a17f99614 100644 --- a/src/iceberg/data/file_scan_task_reader.cc +++ b/src/iceberg/data/file_scan_task_reader.cc @@ -57,6 +57,12 @@ Result> ConstantsOf(const FileScanTask& tas } return id_to_constant; } + if (file.partition.num_fields() != spec->fields().size()) { + return InvalidArgument( + "Partition of file {} has {} values, but partition spec {} has {} fields", + file.file_path, file.partition.num_fields(), spec->spec_id(), + spec->fields().size()); + } for (size_t i = 0; i < spec->fields().size(); ++i) { const auto& field = spec->fields()[i]; if (field.transform() == nullptr) { @@ -64,7 +70,8 @@ Result> ConstantsOf(const FileScanTask& tas field.field_id()); } if (field.transform()->transform_type() == TransformType::kIdentity) { - id_to_constant.emplace(field.source_id(), file.partition.values()[i]); + ICEBERG_ASSIGN_OR_RAISE(auto value, file.partition.ValueAt(i)); + id_to_constant.emplace(field.source_id(), value.get()); } } return id_to_constant; diff --git a/src/iceberg/manifest/manifest_group.cc b/src/iceberg/manifest/manifest_group.cc index 883fd770ef..1d15e24280 100644 --- a/src/iceberg/manifest/manifest_group.cc +++ b/src/iceberg/manifest/manifest_group.cc @@ -319,9 +319,13 @@ class ManifestGroup::FilePlanningStream final : public FileScanTaskStream { ICEBERG_ASSIGN_OR_RAISE(auto residual, residuals->ResidualFor(value.data_file->partition)); + auto spec_iter = group_->specs_by_id_.find(spec_id); + ICEBERG_CHECK(spec_iter != group_->specs_by_id_.cend(), + "Cannot find partition spec for ID {}", spec_id); + return std::optional>{std::make_shared( std::move(value.data_file), std::move(delete_files), std::move(residual), - group_->specs_by_id_.at(spec_id))}; + spec_iter->second)}; } } diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index f70a13dbb4..09d6c750e2 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -479,9 +479,12 @@ TEST_F(FileScanTaskReaderTest, IdentityPartitionConstantsSurviveJsonAndSplit) { ICEBERG_UNWRAP_OR_FAIL(auto parsed, FileScanTaskFromJson(json)); ASSERT_NE(parsed->spec(), nullptr); EXPECT_EQ(parsed->spec()->spec_id(), 7); + // Use a proper sub-range so the split constructor (not the whole-file path) is tested. + ASSERT_GT(parsed->length(), 1); ICEBERG_UNWRAP_OR_FAIL( - auto split, FileScanTask::MakeSplit(parsed->data_file(), 0, parsed->length(), {}, - nullptr, parsed->spec())); + auto split, FileScanTask::MakeSplit(parsed->data_file(), 0, parsed->length() - 1, + {}, nullptr, parsed->spec())); + ASSERT_TRUE(split->is_split()); EXPECT_EQ(split->spec(), parsed->spec()); ICEBERG_UNWRAP_OR_FAIL( auto reader, FileScanTaskReader::Make({.io = file_io_, @@ -623,6 +626,23 @@ TEST_F(FileScanTaskReaderTest, RejectsMissingPartitionSpec) { EXPECT_FALSE(reader->Open(FileScanTask(file)).has_value()); } +TEST_F(FileScanTaskReaderTest, RejectsPartitionValuesNotMatchingSpec) { + ICEBERG_UNWRAP_OR_FAIL(auto file, + MakeDataFile(table_schema_, R"([[1, "Foo", "blue"]])", 1)); + ICEBERG_UNWRAP_OR_FAIL( + auto spec, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}, + {3, 1001, "category", Transform::Identity()}})); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, FileScanTaskReader::Make({.io = file_io_, + .table_schema = table_schema_, + .schemas = {table_schema_}, + .projected_schema = projected_schema_})); + file->partition_spec_id = 7; + file->partition = PartitionValues({Literal::String("CN")}); + EXPECT_THAT(reader->Open(FileScanTask(file, {}, nullptr, std::move(spec))), + IsError(ErrorKind::kInvalidArgument)); +} + TEST_F(FileScanTaskReaderTest, OpenWithoutDeletesReadsProjectedSchema) { ICEBERG_UNWRAP_OR_FAIL( auto data_file, From 2d73d2f4bbba6646cef40d6fecedc85e4780ee13 Mon Sep 17 00:00:00 2001 From: Gang Wu Date: Tue, 1 Dec 2026 23:07:44 +0800 Subject: [PATCH 11/11] fix(read): use identity partition values only for missing field IDs Read the physical Avro or Parquet column when its native field ID is present, including when the stored value is null. For a missing ID, use the identity partition value before name mapping or the initial default. This keeps Parquet row-group pruning consistent with the values returned by the reader. Pass the file's writing spec to planner-generated splits. Reject a task whose spec ID conflicts with the data file, and preserve physical-column reads for tasks created without a spec. Share Arrow scalar conversion across both formats to handle unknown nulls and decimal precision promotion. Fix Avro field-ID detection for legacy files and publish the read context only after initialization succeeds. Keep partition handling in the format readers and restore the original schema-to-schema Project signature. Cover split planning, task serialization, partition evolution, and equality deletes on identity columns omitted from the output projection. --- src/iceberg/arrow/literal_util.cc | 44 +++-- src/iceberg/arrow/literal_util_internal.h | 7 +- src/iceberg/avro/avro_data_util.cc | 33 +--- src/iceberg/avro/avro_reader.cc | 15 +- src/iceberg/avro/avro_schema_util.cc | 96 +++++----- src/iceberg/avro/avro_schema_util_internal.h | 13 +- src/iceberg/catalog/rest/json_serde.cc | 11 +- src/iceberg/data/file_scan_task_reader.cc | 13 +- src/iceberg/file_reader.h | 7 +- src/iceberg/parquet/parquet_reader.cc | 7 +- src/iceberg/parquet/parquet_schema_util.cc | 29 ++- .../parquet/parquet_schema_util_internal.h | 8 +- src/iceberg/scan_task_planning.cc | 3 +- src/iceberg/schema_util.cc | 46 ++--- src/iceberg/schema_util.h | 7 +- src/iceberg/table_scan.h | 7 +- src/iceberg/test/avro_schema_test.cc | 14 +- src/iceberg/test/avro_test.cc | 89 +++++++-- .../test/file_scan_task_reader_test.cc | 178 +++++------------- src/iceberg/test/json_serde_test.cc | 2 + src/iceberg/test/manifest_group_test.cc | 4 - src/iceberg/test/parquet_schema_test.cc | 10 +- src/iceberg/test/parquet_test.cc | 44 +++-- src/iceberg/test/rest_json_serde_test.cc | 2 - src/iceberg/test/rest_table_scan_test.cc | 1 + src/iceberg/test/schema_util_test.cc | 43 ----- src/iceberg/test/table_scan_test.cc | 28 ++- 27 files changed, 363 insertions(+), 398 deletions(-) diff --git a/src/iceberg/arrow/literal_util.cc b/src/iceberg/arrow/literal_util.cc index e8ee4d6c64..0d21d73dea 100644 --- a/src/iceberg/arrow/literal_util.cc +++ b/src/iceberg/arrow/literal_util.cc @@ -166,29 +166,35 @@ Result> ToArrowScalar(const Literal& literal, } } -Result> MakeDefaultArray( +Result> ToArrowStorageScalar( const Literal& literal, const std::shared_ptr<::arrow::DataType>& type, - int64_t num_rows, ::arrow::MemoryPool* pool) { - // An extension type (e.g. `arrow.uuid` for an Iceberg UUID) is backed by a storage - // type, and compute::Cast has no kernel that casts a storage array into an extension - // type. Materialize the array as the storage type and wrap it in the extension type. - if (type->id() == ::arrow::Type::EXTENSION) { - const auto& extension_type = - internal::checked_cast(*type); - ICEBERG_ASSIGN_OR_RAISE( - std::shared_ptr<::arrow::Array> storage, - MakeDefaultArray(literal, extension_type.storage_type(), num_rows, pool)); - return ::arrow::ExtensionType::WrapArray(type, storage); + ::arrow::MemoryPool* pool) { + const auto& storage_type = + type->id() == ::arrow::Type::EXTENSION + ? internal::checked_cast(*type).storage_type() + : type; + if (literal.IsNull()) { + return ::arrow::MakeNullScalar(storage_type); + } + ICEBERG_ASSIGN_OR_RAISE(auto scalar, ToArrowScalar(literal, pool)); + if (scalar->type->Equals(*storage_type)) { + return scalar; } + ::arrow::compute::ExecContext context(pool); + ICEBERG_ARROW_ASSIGN_OR_RETURN( + auto cast, ::arrow::compute::Cast(scalar, storage_type, + ::arrow::compute::CastOptions::Safe(), &context)); + return cast.scalar(); +} - ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<::arrow::Scalar> scalar, - ToArrowScalar(literal, pool)); - ICEBERG_ARROW_ASSIGN_OR_RETURN(std::shared_ptr<::arrow::Array> array, +Result> MakeDefaultArray( + const Literal& literal, const std::shared_ptr<::arrow::DataType>& type, + int64_t num_rows, ::arrow::MemoryPool* pool) { + ICEBERG_ASSIGN_OR_RAISE(auto scalar, ToArrowStorageScalar(literal, type, pool)); + ICEBERG_ARROW_ASSIGN_OR_RETURN(auto array, ::arrow::MakeArrayFromScalar(*scalar, num_rows, pool)); - if (!array->type()->Equals(*type)) { - ICEBERG_ARROW_ASSIGN_OR_RETURN(::arrow::Datum cast_result, - ::arrow::compute::Cast(array, type)); - return cast_result.make_array(); + if (type->id() == ::arrow::Type::EXTENSION) { + return ::arrow::ExtensionType::WrapArray(type, array); } return array; } diff --git a/src/iceberg/arrow/literal_util_internal.h b/src/iceberg/arrow/literal_util_internal.h index 4de60b5281..5bc358a5a5 100644 --- a/src/iceberg/arrow/literal_util_internal.h +++ b/src/iceberg/arrow/literal_util_internal.h @@ -36,10 +36,15 @@ namespace iceberg::arrow { Result> ToArrowScalar(const Literal& literal, ::arrow::MemoryPool* pool); +/// \brief Convert a literal to the requested Arrow type (storage type for extensions). +Result> ToArrowStorageScalar( + const Literal& literal, const std::shared_ptr<::arrow::DataType>& type, + ::arrow::MemoryPool* pool); + /// \brief Create an Arrow array of `num_rows` rows where every row holds the literal /// value, e.g. to materialize a missing column with a default value. /// -/// The array is cast to `type` when the literal's canonical Arrow type differs. +/// The literal is converted to `type` before it is repeated. Result> MakeDefaultArray( const Literal& literal, const std::shared_ptr<::arrow::DataType>& type, int64_t num_rows, ::arrow::MemoryPool* pool); diff --git a/src/iceberg/avro/avro_data_util.cc b/src/iceberg/avro/avro_data_util.cc index 3be8919022..1ae6d7b1de 100644 --- a/src/iceberg/avro/avro_data_util.cc +++ b/src/iceberg/avro/avro_data_util.cc @@ -516,29 +516,6 @@ Status AppendFieldToBuilder(const ::avro::NodePtr& avro_node, namespace { -Result> MakeDefaultScalar( - const Literal& literal, const std::shared_ptr<::arrow::DataType>& builder_type) { - // The builder's own memory pool is not exposed, so the small scalar buffer uses the - // default pool. - ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<::arrow::Scalar> scalar, - arrow::ToArrowScalar(literal, ::arrow::default_memory_pool())); - - // For an extension builder (e.g. `arrow.uuid`) target its storage type: ToArrowScalar - // yields the storage scalar (fixed_size_binary(16) for uuid) and Scalar::CastTo has no - // kernel that targets an extension type. This mirrors MakeDefaultArray's extension - // handling. - std::shared_ptr<::arrow::DataType> target_type = builder_type; - if (target_type->id() == ::arrow::Type::EXTENSION) { - target_type = internal::checked_cast(*target_type) - .storage_type(); - } - - if (!scalar->type->Equals(*target_type)) { - ICEBERG_ARROW_ASSIGN_OR_RETURN(scalar, scalar->CastTo(target_type)); - } - return scalar; -} - Status PrepareStructDefaultScalars(std::span projections, ::arrow::ArrayBuilder* builder); @@ -616,8 +593,9 @@ Status PrepareStructDefaultScalars(std::span projections, if (attrs->default_scalar == nullptr) { ICEBERG_ASSIGN_OR_RAISE( attrs->default_scalar, - MakeDefaultScalar(std::get(field_projection.from), - field_builder->type())); + arrow::ToArrowStorageScalar(std::get(field_projection.from), + field_builder->type(), + ::arrow::default_memory_pool())); } continue; } @@ -636,8 +614,9 @@ Status PrepareDefaultScalars(SchemaProjection& projection, } Status AppendDefaultToBuilder(const Literal& literal, ::arrow::ArrayBuilder* builder) { - ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<::arrow::Scalar> scalar, - MakeDefaultScalar(literal, builder->type())); + ICEBERG_ASSIGN_OR_RAISE(auto scalar, + arrow::ToArrowStorageScalar(literal, builder->type(), + ::arrow::default_memory_pool())); ICEBERG_ARROW_RETURN_NOT_OK(builder->AppendScalar(*scalar)); return {}; } diff --git a/src/iceberg/avro/avro_reader.cc b/src/iceberg/avro/avro_reader.cc index 95c90ad926..6f254100ce 100644 --- a/src/iceberg/avro/avro_reader.cc +++ b/src/iceberg/avro/avro_reader.cc @@ -351,7 +351,8 @@ class AvroReader::Impl { // Project the read schema on top of the file schema. ICEBERG_ASSIGN_OR_RAISE(projection_, Project(*read_schema_, file_schema.root(), - /*prune_source=*/false, options.id_to_constant)); + /*prune_source=*/false, options.id_to_constant, + /*ids_from_name_mapping=*/has_id_visitor.HasNoIds())); ICEBERG_RETURN_UNEXPECTED(backend_->InitWithSchema(file_schema, options.split)); @@ -435,7 +436,7 @@ class AvroReader::Impl { private: Status InitReadContext() { - context_ = std::make_unique(); + auto context = std::make_unique(); ArrowSchema arrow_schema; ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*read_schema_, &arrow_schema)); @@ -444,21 +445,21 @@ class AvroReader::Impl { return InvalidSchema("Failed to import the arrow schema: {}", import_result.status().message()); } - context_->arrow_schema_ = import_result.MoveValueUnsafe(); + context->arrow_schema_ = import_result.MoveValueUnsafe(); auto arrow_struct_type = internal::checked_pointer_cast<::arrow::StructType>(StorageTypeForBuilder( - std::make_shared<::arrow::StructType>(context_->arrow_schema_->fields()))); + std::make_shared<::arrow::StructType>(context->arrow_schema_->fields()))); auto builder_result = ::arrow::MakeBuilder(arrow_struct_type); if (!builder_result.ok()) { return InvalidSchema("Failed to make the arrow builder: {}", builder_result.status().message()); } - context_->builder_ = builder_result.MoveValueUnsafe(); + context->builder_ = builder_result.MoveValueUnsafe(); ICEBERG_RETURN_UNEXPECTED( - PrepareDefaultScalars(projection_, context_->builder_.get())); + PrepareDefaultScalars(projection_, context->builder_.get())); backend_->InitReadContext(backend_->GetReaderSchema()); - + context_ = std::move(context); return {}; } diff --git a/src/iceberg/avro/avro_schema_util.cc b/src/iceberg/avro/avro_schema_util.cc index 819dbf9757..cf93e0aa5a 100644 --- a/src/iceberg/avro/avro_schema_util.cc +++ b/src/iceberg/avro/avro_schema_util.cc @@ -683,15 +683,21 @@ Status UnwrapUnion(const ::avro::NodePtr& node, ::avro::NodePtr* result) { return {}; } +struct ProjectionOptions { + bool prune_source; + bool ids_from_name_mapping; + const std::unordered_map& id_to_constant; +}; + // Forward declaration -Result ProjectNested( - const Type& expected_type, const ::avro::NodePtr& avro_node, bool prune_source, - const std::unordered_map& id_to_constant); - -Result ProjectField( - const SchemaField& expected_field, const ::avro::NodePtr& avro_node, - size_t source_index, bool prune_source, - const std::unordered_map& id_to_constant) { +Result ProjectNested(const Type& expected_type, + const ::avro::NodePtr& avro_node, + const ProjectionOptions& options); + +Result ProjectField(const SchemaField& expected_field, + const ::avro::NodePtr& avro_node, + size_t source_index, + const ProjectionOptions& options) { const Type& expected_type = *expected_field.type(); ::avro::NodePtr field_node; ICEBERG_RETURN_UNEXPECTED(UnwrapUnion(avro_node, &field_node)); @@ -708,8 +714,8 @@ Result ProjectField( } if (expected_type.is_nested()) { - ICEBERG_ASSIGN_OR_RAISE(projection, ProjectNested(expected_type, field_node, - prune_source, id_to_constant)); + ICEBERG_ASSIGN_OR_RAISE(projection, + ProjectNested(expected_type, field_node, options)); } else { ICEBERG_RETURN_UNEXPECTED(ValidateAvroSchemaEvolution(expected_type, field_node)); } @@ -718,9 +724,9 @@ Result ProjectField( return projection; } -Result ProjectStruct( - const StructType& struct_type, const ::avro::NodePtr& avro_node, bool prune_source, - const std::unordered_map& id_to_constant) { +Result ProjectStruct(const StructType& struct_type, + const ::avro::NodePtr& avro_node, + const ProjectionOptions& options) { if (avro_node->type() != ::avro::AVRO_RECORD) { return InvalidSchema("Expected AVRO_RECORD type, but got {}", ToString(avro_node)); } @@ -736,6 +742,10 @@ Result ProjectStruct( for (size_t i = 0; i < avro_node->leaves(); ++i) { ICEBERG_ASSIGN_OR_RAISE(int32_t field_id, GetFieldId(avro_node, i)); + // A partition value takes precedence over a field ID supplied by name mapping. + if (options.ids_from_name_mapping && options.id_to_constant.contains(field_id)) { + continue; + } ::avro::NodePtr field_node = avro_node->leafAt(i); if (const auto [iter, inserted] = node_info_map.emplace( std::piecewise_construct, std::forward_as_tuple(field_id), @@ -752,14 +762,14 @@ Result ProjectStruct( int32_t field_id = expected_field.field_id(); FieldProjection child_projection; - if (auto constant = id_to_constant.find(field_id); constant != id_to_constant.end()) { + if (auto source = node_info_map.find(field_id); source != node_info_map.end()) { + ICEBERG_ASSIGN_OR_RAISE(child_projection, + ProjectField(expected_field, source->second.field_node, + source->second.local_index, options)); + } else if (auto constant = options.id_to_constant.find(field_id); + constant != options.id_to_constant.end()) { child_projection.kind = FieldProjection::Kind::kConstant; child_projection.from = constant->second; - } else if (auto iter = node_info_map.find(field_id); iter != node_info_map.cend()) { - ICEBERG_ASSIGN_OR_RAISE( - child_projection, - ProjectField(expected_field, iter->second.field_node, iter->second.local_index, - prune_source, id_to_constant)); } else if (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (expected_field.initial_default() != nullptr) { @@ -775,16 +785,16 @@ Result ProjectStruct( result.children.emplace_back(std::move(child_projection)); } - if (prune_source) { + if (options.prune_source) { PruneFieldProjection(result); } return result; } -Result ProjectList( - const ListType& list_type, const ::avro::NodePtr& avro_node, bool prune_source, - const std::unordered_map& id_to_constant) { +Result ProjectList(const ListType& list_type, + const ::avro::NodePtr& avro_node, + const ProjectionOptions& options) { if (avro_node->type() != ::avro::AVRO_ARRAY) { return InvalidSchema("Expected AVRO_ARRAY type, but got {}", ToString(avro_node)); } @@ -801,19 +811,18 @@ Result ProjectList( } FieldProjection element_projection; - ICEBERG_ASSIGN_OR_RAISE( - element_projection, - ProjectField(expected_element_field, avro_node->leafAt(0), - /*source_index*/ size_t{0}, prune_source, id_to_constant)); + ICEBERG_ASSIGN_OR_RAISE(element_projection, + ProjectField(expected_element_field, avro_node->leafAt(0), + /*source_index*/ size_t{0}, options)); FieldProjection result{.kind = FieldProjection::Kind::kProjected}; result.children.emplace_back(std::move(element_projection)); return result; } -Result ProjectMap( - const MapType& map_type, const ::avro::NodePtr& avro_node, bool prune_source, - const std::unordered_map& id_to_constant) { +Result ProjectMap(const MapType& map_type, + const ::avro::NodePtr& avro_node, + const ProjectionOptions& options) { const auto& expected_key_field = map_type.key(); const auto& expected_value_field = map_type.value(); @@ -862,18 +871,18 @@ Result ProjectMap( for (size_t i = 0; i < map_node->leaves(); ++i) { FieldProjection sub_projection; const auto& expected_sub_field = map_type.fields()[i]; - ICEBERG_ASSIGN_OR_RAISE(sub_projection, - ProjectField(expected_sub_field, map_node->leafAt(i), i, - prune_source, id_to_constant)); + ICEBERG_ASSIGN_OR_RAISE( + sub_projection, + ProjectField(expected_sub_field, map_node->leafAt(i), i, options)); result.children.emplace_back(std::move(sub_projection)); } return result; } -Result ProjectNested( - const Type& expected_type, const ::avro::NodePtr& avro_node, bool prune_source, - const std::unordered_map& id_to_constant) { +Result ProjectNested(const Type& expected_type, + const ::avro::NodePtr& avro_node, + const ProjectionOptions& options) { if (!expected_type.is_nested()) { return InvalidSchema("Expected a nested type, but got {}", expected_type); } @@ -881,13 +890,13 @@ Result ProjectNested( switch (expected_type.type_id()) { case TypeId::kStruct: return ProjectStruct(internal::checked_cast(expected_type), - avro_node, prune_source, id_to_constant); + avro_node, options); case TypeId::kList: return ProjectList(internal::checked_cast(expected_type), - avro_node, prune_source, id_to_constant); + avro_node, options); case TypeId::kMap: return ProjectMap(internal::checked_cast(expected_type), avro_node, - prune_source, id_to_constant); + options); default: return InvalidSchema("Unsupported nested type: {}", expected_type); } @@ -903,10 +912,13 @@ bool HasMapLogicalType(const ::avro::NodePtr& node) { Result Project( const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source, - const std::unordered_map& id_to_constant) { + const std::unordered_map& id_to_constant, + bool ids_from_name_mapping) { + const ProjectionOptions options{.prune_source = prune_source, + .ids_from_name_mapping = ids_from_name_mapping, + .id_to_constant = id_to_constant}; ICEBERG_ASSIGN_OR_RAISE(auto field_projection, - ProjectNested(static_cast(expected_schema), - avro_node, prune_source, id_to_constant)); + ProjectNested(expected_schema, avro_node, options)); return SchemaProjection{std::move(field_projection.children)}; } diff --git a/src/iceberg/avro/avro_schema_util_internal.h b/src/iceberg/avro/avro_schema_util_internal.h index 8d5d420ca9..cc669d72d8 100644 --- a/src/iceberg/avro/avro_schema_util_internal.h +++ b/src/iceberg/avro/avro_schema_util_internal.h @@ -20,6 +20,7 @@ #pragma once #include +#include #include @@ -101,9 +102,8 @@ class HasIdVisitor { return total_fields_ == fields_with_id_ && fields_with_id_ != 0; } - /// \brief Check if all fields in the visited schema have field IDs. - /// \return True if all fields have IDs, false otherwise. - bool HasNoIds() const { return total_fields_ == 0; } + /// \brief Whether the schema has no field IDs and may need name mapping. + bool HasNoIds() const { return fields_with_id_ == 0; } private: /// \brief Visit a record node to check for field IDs. @@ -142,11 +142,14 @@ class HasIdVisitor { /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param avro_node The Avro node to read data from. /// \param prune_source Whether the source schema can be pruned. -/// \param id_to_constant File-level values that override physical fields and defaults. +/// \param id_to_constant Identity partition values for fields missing from the file. +/// \param ids_from_name_mapping Whether the supplied Avro field IDs came from name +/// mapping. /// \return The schema projection result. Result Project( const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source, - const std::unordered_map& id_to_constant = {}); + const std::unordered_map& id_to_constant = {}, + bool ids_from_name_mapping = false); std::string ToString(const ::avro::NodePtr& node); std::string ToString(const ::avro::LogicalType& logical_type); diff --git a/src/iceberg/catalog/rest/json_serde.cc b/src/iceberg/catalog/rest/json_serde.cc index 23de188fde..df24be9ebd 100644 --- a/src/iceberg/catalog/rest/json_serde.cc +++ b/src/iceberg/catalog/rest/json_serde.cc @@ -231,16 +231,11 @@ Result>> FileScanTasksFromJson( ICEBERG_ASSIGN_OR_RAISE(residual_filter, ExpressionFromJson(filter_json)); } - std::shared_ptr spec; - if (data_file.partition_spec_id.has_value()) { - auto it = partition_spec_by_id.find(*data_file.partition_spec_id); - if (it != partition_spec_by_id.end()) { - spec = it->second; - } - } + // DataFileFromJson validated the spec ID when decoding the partition tuple. + const auto& spec = partition_spec_by_id.at(data_file.partition_spec_id.value()); auto task = FileScanTask::MakeSplit(std::make_shared(std::move(data_file)), start, length, std::move(task_delete_files), - std::move(residual_filter), std::move(spec)); + std::move(residual_filter), spec); if (!task) { return JsonParseError("Invalid FileScanTask range: {}", task.error().message); } diff --git a/src/iceberg/data/file_scan_task_reader.cc b/src/iceberg/data/file_scan_task_reader.cc index 1a17f99614..78b56e95ba 100644 --- a/src/iceberg/data/file_scan_task_reader.cc +++ b/src/iceberg/data/file_scan_task_reader.cc @@ -47,16 +47,18 @@ namespace iceberg { namespace { -Result> ConstantsOf(const FileScanTask& task) { +Result> IdentityPartitionConstants( + const FileScanTask& task) { const auto& file = *task.data_file(); const auto& spec = task.spec(); std::unordered_map id_to_constant; if (!spec) { - if (file.partition.num_fields() != 0) { - return InvalidArgument("A partition spec is required to read partition values"); - } return id_to_constant; } + if (file.partition_spec_id && *file.partition_spec_id != spec->spec_id()) { + return InvalidArgument("File {} has partition spec ID {}, but task uses spec {}", + file.file_path, *file.partition_spec_id, spec->spec_id()); + } if (file.partition.num_fields() != spec->fields().size()) { return InvalidArgument( "Partition of file {} has {} values, but partition spec {} has {} fields", @@ -84,7 +86,8 @@ Result MakeReaderOptions( ReaderProperties properties, std::optional first_row_id, std::optional data_sequence_number) { const auto& data_file = *task.data_file(); - ICEBERG_ASSIGN_OR_RAISE(auto id_to_constant, ConstantsOf(task)); + ICEBERG_ASSIGN_OR_RAISE(auto id_to_constant, IdentityPartitionConstants(task)); + // TODO(gangwu): Support projection of _spec_id and the table-wide _partition struct. return ReaderOptions{ .path = data_file.file_path, .length = static_cast(data_file.file_size_in_bytes), diff --git a/src/iceberg/file_reader.h b/src/iceberg/file_reader.h index 8768726c3a..a4221b662c 100644 --- a/src/iceberg/file_reader.h +++ b/src/iceberg/file_reader.h @@ -132,10 +132,9 @@ struct ICEBERG_EXPORT ReaderOptions { /// \brief Format-specific or implementation-specific properties. ReaderProperties properties; - /// File-level values keyed by field ID, overriding physical columns, - /// initial defaults and optional-field nulls, matching Iceberg Java. - /// Example: `options.id_to_constant.emplace(2, Literal::String("CN"));` - // TODO(yzsun): Use a nested value representation if struct constants are needed. + /// \brief Identity partition values keyed by Iceberg source field ID. + /// For a field ID absent from the file, a supplied value (including null) + /// takes precedence over name mapping and the field's initial default. std::unordered_map id_to_constant; }; diff --git a/src/iceberg/parquet/parquet_reader.cc b/src/iceberg/parquet/parquet_reader.cc index 6b5a325952..08585653ae 100644 --- a/src/iceberg/parquet/parquet_reader.cc +++ b/src/iceberg/parquet/parquet_reader.cc @@ -79,12 +79,11 @@ Result BuildProjection( metadata->schema(), metadata->key_value_metadata(), reader->properties(), &schema_manifest)); ApplyNameMapping(*name_mapping, &schema_manifest); - return Project(read_schema, schema_manifest, id_to_constant); + return Project(read_schema, schema_manifest, id_to_constant, + /*ids_from_name_mapping=*/true); } - ICEBERG_ASSIGN_OR_RAISE(auto projection, - Project(read_schema, reader->manifest(), id_to_constant)); - return projection; + return Project(read_schema, reader->manifest(), id_to_constant); } // Stored ARROW:schema metadata can override ArrowReaderProperties::set_list_type(). diff --git a/src/iceberg/parquet/parquet_schema_util.cc b/src/iceberg/parquet/parquet_schema_util.cc index 21e1f4b5c1..fa76f49c3a 100644 --- a/src/iceberg/parquet/parquet_schema_util.cc +++ b/src/iceberg/parquet/parquet_schema_util.cc @@ -505,8 +505,11 @@ namespace { class ProjectionBuilder { public: ProjectionBuilder(const ::parquet::SchemaDescriptor* descr, - const std::unordered_map& id_to_constant) - : descr_(descr), id_to_constant_(id_to_constant) {} + const std::unordered_map& id_to_constant, + bool ids_from_name_mapping) + : descr_(descr), + id_to_constant_(id_to_constant), + ids_from_name_mapping_(ids_from_name_mapping) {} Result Project( const Type& nested_type, @@ -573,6 +576,10 @@ class ProjectionBuilder { if (!field_id) { continue; } + // A partition value resolves the missing file ID before name mapping. + if (ids_from_name_mapping_ && id_to_constant_.contains(*field_id)) { + continue; + } if (!field_context_map .emplace(field_id.value(), FieldContext{.local_index = i, .parquet_field = parquet_field}) @@ -589,15 +596,15 @@ class ProjectionBuilder { int32_t field_id = field.field_id(); FieldProjection child_projection; - if (auto constant = id_to_constant_.find(field_id); - constant != id_to_constant_.end()) { - child_projection.kind = FieldProjection::Kind::kConstant; - child_projection.from = constant->second; - } else if (auto iter = field_context_map.find(field_id); - iter != field_context_map.cend()) { + if (auto iter = field_context_map.find(field_id); + iter != field_context_map.cend()) { const auto& parquet_field = iter->second.parquet_field; ICEBERG_ASSIGN_OR_RAISE(child_projection, ProjectField(field, parquet_field, iter->second.local_index)); + } else if (auto constant = id_to_constant_.find(field_id); + constant != id_to_constant_.end()) { + child_projection.kind = FieldProjection::Kind::kConstant; + child_projection.from = constant->second; } else if (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (field.initial_default() != nullptr) { @@ -726,6 +733,7 @@ class ProjectionBuilder { const ::parquet::SchemaDescriptor* descr_; const std::unordered_map& id_to_constant_; + bool ids_from_name_mapping_; }; void CollectColumnIds(const FieldProjection& field_projection, @@ -792,8 +800,9 @@ void ApplyNameMappingToField(const NameMapping& mapping, std::vector Project( const Schema& expected_schema, const ::parquet::arrow::SchemaManifest& parquet_schema, - const std::unordered_map& id_to_constant) { - ProjectionBuilder builder(parquet_schema.descr, id_to_constant); + const std::unordered_map& id_to_constant, + bool ids_from_name_mapping) { + ProjectionBuilder builder(parquet_schema.descr, id_to_constant, ids_from_name_mapping); ICEBERG_ASSIGN_OR_RAISE(auto field_projection, builder.Project(static_cast(expected_schema), parquet_schema.schema_fields)); diff --git a/src/iceberg/parquet/parquet_schema_util_internal.h b/src/iceberg/parquet/parquet_schema_util_internal.h index 18c4ce6307..be209ed362 100644 --- a/src/iceberg/parquet/parquet_schema_util_internal.h +++ b/src/iceberg/parquet/parquet_schema_util_internal.h @@ -20,6 +20,7 @@ #pragma once #include +#include #include #include @@ -54,12 +55,15 @@ Status ValidateParquetTypeCompatibility( /// /// \param expected_schema The Iceberg Schema that defines the expected structure. /// \param parquet_schema The Parquet schema to read data from. -/// \param id_to_constant File-level values that override physical fields and defaults. +/// \param id_to_constant Identity partition values for missing file field IDs. +/// \param ids_from_name_mapping Whether the manifest's field IDs were supplied by a +/// name mapping. Partition values take precedence over mapped fields. /// \return The schema projection result with column indices of projected Parquet columns /// specified via ParquetExtraAttributes. Result Project( const Schema& expected_schema, const ::parquet::arrow::SchemaManifest& parquet_schema, - const std::unordered_map& id_to_constant = {}); + const std::unordered_map& id_to_constant = {}, + bool ids_from_name_mapping = false); /// \brief Get the selected column indices by walking through the projection result. /// diff --git a/src/iceberg/scan_task_planning.cc b/src/iceberg/scan_task_planning.cc index 2a4ec435ba..879cfb4804 100644 --- a/src/iceberg/scan_task_planning.cc +++ b/src/iceberg/scan_task_planning.cc @@ -153,7 +153,8 @@ class FileScanTaskSplitCursor { return task_; } return FileScanTask::MakeSplit(task_->data_file(), start, end - start, - task_->delete_files(), task_->residual_filter()); + task_->delete_files(), task_->residual_filter(), + task_->spec()); } private: diff --git a/src/iceberg/schema_util.cc b/src/iceberg/schema_util.cc index 1499aa6311..d7d261757e 100644 --- a/src/iceberg/schema_util.cc +++ b/src/iceberg/schema_util.cc @@ -82,14 +82,12 @@ Status ValidateSchemaEvolution(const Type& expected_type, const Type& source_typ return NotSupported("Cannot read {} from {}", expected_type, source_type); } -Result ProjectNested( - const Type& expected_type, const Type& source_type, bool prune_source, - ProjectionMode mode, const std::unordered_map& id_to_constant); +Result ProjectNested(const Type& expected_type, const Type& source_type, + bool prune_source, ProjectionMode mode); -Result ProjectField( - const SchemaField& expected_field, const SchemaField& source_field, - size_t source_index, bool prune_source, ProjectionMode mode, - const std::unordered_map& id_to_constant) { +Result ProjectField(const SchemaField& expected_field, + const SchemaField& source_field, size_t source_index, + bool prune_source, ProjectionMode mode) { FieldProjection projection; if (mode == ProjectionMode::kWrite && source_field.optional() && @@ -125,9 +123,9 @@ Result ProjectField( } if (expected_field.type()->is_nested()) { - ICEBERG_ASSIGN_OR_RAISE(projection, - ProjectNested(*expected_field.type(), *source_field.type(), - prune_source, mode, id_to_constant)); + ICEBERG_ASSIGN_OR_RAISE( + projection, + ProjectNested(*expected_field.type(), *source_field.type(), prune_source, mode)); } else if (mode == ProjectionMode::kWrite) { if (*expected_field.type() != *source_field.type()) { return NotSupported("Cannot project {} as {}: type promotion is not allowed", @@ -146,9 +144,8 @@ Result ProjectField( return projection; } -Result ProjectNested( - const Type& expected_type, const Type& source_type, bool prune_source, - ProjectionMode mode, const std::unordered_map& id_to_constant) { +Result ProjectNested(const Type& expected_type, const Type& source_type, + bool prune_source, ProjectionMode mode) { if (!expected_type.is_nested()) { return InvalidSchema("Expected a nested type, but got {}", expected_type); } @@ -187,16 +184,10 @@ Result ProjectNested( int32_t field_id = expected_field.field_id(); FieldProjection child_projection; - if (auto constant = id_to_constant.find(field_id); - mode == ProjectionMode::kRead && constant != id_to_constant.end()) { - child_projection.kind = FieldProjection::Kind::kConstant; - child_projection.from = constant->second; - } else if (auto iter = source_field_map.find(field_id); - iter != source_field_map.cend()) { - ICEBERG_ASSIGN_OR_RAISE( - child_projection, - ProjectField(expected_field, *iter->second.field, iter->second.local_index, - prune_source, mode, id_to_constant)); + if (auto iter = source_field_map.find(field_id); iter != source_field_map.cend()) { + ICEBERG_ASSIGN_OR_RAISE(child_projection, + ProjectField(expected_field, *iter->second.field, + iter->second.local_index, prune_source, mode)); if (mode == ProjectionMode::kWrite) { source_field_map.erase(iter); } @@ -215,6 +206,7 @@ Result ProjectNested( } else if (expected_field.optional()) { child_projection.kind = FieldProjection::Kind::kNull; } else { + // TODO(gangwu): support constant value if (mode == ProjectionMode::kWrite) { return InvalidSchema("Missing required field: {} without a write-default", expected_field.ToString()); @@ -238,12 +230,12 @@ Result ProjectNested( } // namespace -Result Project( - const Schema& expected_schema, const Schema& source_schema, bool prune_source, - ProjectionMode mode, const std::unordered_map& id_to_constant) { +Result Project(const Schema& expected_schema, + const Schema& source_schema, bool prune_source, + ProjectionMode mode) { ICEBERG_ASSIGN_OR_RAISE( auto field_projection, - ProjectNested(expected_schema, source_schema, prune_source, mode, id_to_constant)); + ProjectNested(expected_schema, source_schema, prune_source, mode)); return SchemaProjection{std::move(field_projection.children)}; } diff --git a/src/iceberg/schema_util.h b/src/iceberg/schema_util.h index 23933d2af7..397013f44a 100644 --- a/src/iceberg/schema_util.h +++ b/src/iceberg/schema_util.h @@ -24,7 +24,6 @@ #include #include -#include #include #include @@ -100,14 +99,10 @@ enum class ProjectionMode { /// field in `FieldProjection` exactly reflects the position (relative to its nesting /// level) to get the column value from the reader. /// \param mode Whether to project for reading or writing. -/// \param id_to_constant Primitive values keyed by source field ID. Constants override -/// physical fields and defaults, including primitive leaves of existing structs. Only -/// applied when `mode` is `ProjectionMode::kRead`. /// \return The projection result. ICEBERG_EXPORT Result Project( const Schema& expected_schema, const Schema& source_schema, bool prune_source, - ProjectionMode mode = ProjectionMode::kRead, - const std::unordered_map& id_to_constant = {}); + ProjectionMode mode = ProjectionMode::kRead); ICEBERG_EXPORT std::string_view ToString(FieldProjection::Kind kind); ICEBERG_EXPORT std::string ToString(const FieldProjection& projection); diff --git a/src/iceberg/table_scan.h b/src/iceberg/table_scan.h index 7819bf41b1..31998c182c 100644 --- a/src/iceberg/table_scan.h +++ b/src/iceberg/table_scan.h @@ -73,9 +73,10 @@ class ICEBERG_EXPORT FileScanTask : public ScanTask { /// \param data_file The data file to read. /// \param delete_files Delete files that apply to this data file. /// \param filter Optional residual filter to apply after reading. - /// \param spec Partition spec corresponding to the data file partition tuple. - /// \note The shared data file, delete files, and residual filter must remain - /// unchanged for this task's lifetime. Metadata changes require rebuilding tasks. + /// \param spec Writing spec, which must match the file's partition spec ID if set. + /// Readers derive identity partition values only when a spec is supplied. + /// \note Shared file metadata, the partition spec, and the residual filter must + /// remain unchanged for this task's lifetime. explicit FileScanTask(std::shared_ptr data_file, std::vector> delete_files = {}, std::shared_ptr filter = nullptr, diff --git a/src/iceberg/test/avro_schema_test.cc b/src/iceberg/test/avro_schema_test.cc index f147a607bc..b6eb20087a 100644 --- a/src/iceberg/test/avro_schema_test.cc +++ b/src/iceberg/test/avro_schema_test.cc @@ -615,7 +615,7 @@ TEST(HasIdVisitorTest, ArrayWithoutElementId) { HasIdVisitor visitor; EXPECT_THAT(visitor.Visit(::avro::compileJsonSchemaFromString(schema_json)), IsOk()); - EXPECT_FALSE(visitor.HasNoIds()); + EXPECT_TRUE(visitor.HasNoIds()); EXPECT_FALSE(visitor.AllHaveIds()); } @@ -1202,10 +1202,11 @@ TEST(AvroSchemaProjectionTest, ProjectNestedStructures) { std::make_shared(std::vector{ SchemaField::MakeOptional(/*field_id=*/101, "street", iceberg::string()), SchemaField::MakeOptional(/*field_id=*/102, "city", iceberg::string()), + SchemaField::MakeOptional(/*field_id=*/103, "region", iceberg::string()), })), }); - // Create equivalent avro schema + // The file has street and city; region is supplied by the partition. std::string avro_schema_json = R"({ "type": "record", "name": "iceberg_schema", @@ -1223,8 +1224,8 @@ TEST(AvroSchemaProjectionTest, ProjectNestedStructures) { })"; auto avro_schema = ::avro::compileJsonSchemaFromString(avro_schema_json); - auto projection_result = - Project(expected_schema, avro_schema.root(), /*prune_source=*/true); + auto projection_result = Project(expected_schema, avro_schema.root(), + /*prune_source=*/true, {{103, Literal::String("CA")}}); ASSERT_THAT(projection_result, IsOk()); const auto& projection = *projection_result; @@ -1235,11 +1236,14 @@ TEST(AvroSchemaProjectionTest, ProjectNestedStructures) { ASSERT_EQ(std::get<1>(projection.fields[1].from), 1); // Verify struct field has children correctly mapped - ASSERT_EQ(projection.fields[1].children.size(), 2); + ASSERT_EQ(projection.fields[1].children.size(), 3); ASSERT_EQ(projection.fields[1].children[0].kind, FieldProjection::Kind::kProjected); ASSERT_EQ(std::get<1>(projection.fields[1].children[0].from), 0); ASSERT_EQ(projection.fields[1].children[1].kind, FieldProjection::Kind::kProjected); ASSERT_EQ(std::get<1>(projection.fields[1].children[1].from), 1); + ASSERT_EQ(projection.fields[1].children[2].kind, FieldProjection::Kind::kConstant); + EXPECT_EQ(std::get(projection.fields[1].children[2].from), + Literal::String("CA")); } TEST(AvroSchemaProjectionTest, ProjectListType) { diff --git a/src/iceberg/test/avro_test.cc b/src/iceberg/test/avro_test.cc index d4c9954236..5d04a62517 100644 --- a/src/iceberg/test/avro_test.cc +++ b/src/iceberg/test/avro_test.cc @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -49,6 +50,7 @@ #include "iceberg/expression/literal.h" #include "iceberg/file_reader.h" #include "iceberg/metadata_columns.h" +#include "iceberg/name_mapping.h" #include "iceberg/schema.h" #include "iceberg/schema_internal.h" #include "iceberg/test/matchers.h" @@ -137,7 +139,8 @@ class AvroReaderTest : public TempFileTestBase { bool skip_datum_{true}; - void CreateSimpleAvroFile() { + void CreateSimpleAvroFile( + std::string_view rows = R"([[1, "Alice"], [2, "Bob"], [3, "Charlie"]])") { // Create simple avro file using the writer API instead of direct Avro library auto schema = std::make_shared(std::vector{ SchemaField::MakeRequired(1, "id", std::make_shared()), @@ -147,10 +150,9 @@ class AvroReaderTest : public TempFileTestBase { ASSERT_THAT(ToArrowSchema(*schema, &arrow_c_schema), IsOk()); auto arrow_schema = ::arrow::ImportType(&arrow_c_schema).ValueOrDie(); - auto array = ::arrow::json::ArrayFromJSONString( - ::arrow::struct_(arrow_schema->fields()), - R"([[1, "Alice"], [2, "Bob"], [3, "Charlie"]])") - .ValueOrDie(); + auto array = + ::arrow::json::ArrayFromJSONString(::arrow::struct_(arrow_schema->fields()), rows) + .ValueOrDie(); struct ArrowArray arrow_array; auto export_result = ::arrow::ExportArray(*array, &arrow_array); @@ -565,26 +567,83 @@ class AvroReaderParameterizedTest : public AvroReaderTest, AvroReaderTest::SetUp(); skip_datum_ = GetParam(); } + + Result> OpenWithPartitionValues( + std::vector fields, std::unordered_map values) { + ReaderOptions options{.path = temp_avro_file_, + .io = file_io_, + .projection = std::make_shared(std::move(fields)), + .id_to_constant = std::move(values)}; + options.properties.Set(ReaderProperties::kAvroSkipDatum, skip_datum_); + return ReaderFactoryRegistry::Open(FileFormatType::kAvro, options); + } }; -TEST_P(AvroReaderParameterizedTest, ReadsPartitionConstants) { - CreateSimpleAvroFile(); +TEST_P(AvroReaderParameterizedTest, ReadsPartitionValuesOnlyForMissingFieldIds) { + ASSERT_NO_FATAL_FAILURE(CreateSimpleAvroFile(R"([[1, "Alice"], [2, null]])")); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, + OpenWithPartitionValues( + {SchemaField::MakeOptional(2, "name", string()), + SchemaField(3, "region", string(), /*optional=*/true, /*doc=*/{}, + std::make_shared(Literal::String("default")))}, + {{2, Literal::String("partition-name")}, {3, Literal::Null(unknown())}})); + ASSERT_NO_FATAL_FAILURE(VerifyNextBatch(*reader, R"([["Alice",null], [null,null]])")); + VerifyExhausted(*reader); +} + +TEST_P(AvroReaderParameterizedTest, PromotesDecimalPartitionConstant) { + ASSERT_NO_FATAL_FAILURE(CreateSimpleAvroFile("[[1, null]]")); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, + OpenWithPartitionValues({SchemaField::MakeRequired(3, "amount", decimal(18, 2))}, + {{3, Literal::Decimal(12345, 9, 2)}})); + ASSERT_NO_FATAL_FAILURE(VerifyNextBatch(*reader, R"([["123.45"]])")); + VerifyExhausted(*reader); +} + +TEST_P(AvroReaderParameterizedTest, ReadsMappedFieldAndPartitionConstantWithoutFileIds) { + const auto path = CreateNewTempFilePathWithSuffix(".avro"); + const auto file_schema = ::avro::compileJsonSchemaFromString(R"({ + "type": "record", "name": "row", + "fields": [{"name":"old_id","type":"int"}, {"name":"region","type":"string"}] + })"); + ::avro::DataFileWriter<::avro::GenericDatum> writer(path.c_str(), file_schema); + ::avro::GenericDatum row(file_schema); + row.value<::avro::GenericRecord>().fieldAt(0).value() = 42; + row.value<::avro::GenericRecord>().fieldAt(1).value() = "US"; + writer.write(row); + writer.close(); + auto schema = std::make_shared( std::vector{SchemaField::MakeRequired(1, "id", int32()), - SchemaField::MakeRequired(3, "region", string()), - SchemaField::MakeOptional(4, "missing", string())}); - ReaderOptions options{.path = temp_avro_file_, .io = file_io_, .projection = schema}; + SchemaField::MakeRequired(2, "region", string())}); + ReaderOptions options{.path = path, + .io = arrow::ArrowFileSystemFileIO::MakeLocalFileIO(), + .projection = schema, + .name_mapping = NameMapping::Make( + {MappedField{.names = {"old_id"}, .field_id = 1}, + MappedField{.names = {"region"}, .field_id = 2}}), + .id_to_constant = {{2, Literal::String("CN")}}}; options.properties.Set(ReaderProperties::kAvroSkipDatum, skip_datum_); - options.id_to_constant = { - {1, Literal::Int(999)}, {3, Literal::String("CN")}, {4, Literal::Null(string())}}; ICEBERG_UNWRAP_OR_FAIL(auto reader, ReaderFactoryRegistry::Open(FileFormatType::kAvro, options)); - VerifyNextBatch(*reader, R"([[999,"CN",null], - [999,"CN",null], - [999,"CN",null]])"); + ASSERT_NO_FATAL_FAILURE(VerifyNextBatch(*reader, R"([[42,"CN"]])")); VerifyExhausted(*reader); } +TEST_P(AvroReaderParameterizedTest, RepeatedReadsReportInvalidConstant) { + ASSERT_NO_FATAL_FAILURE(CreateSimpleAvroFile()); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, + OpenWithPartitionValues({SchemaField::MakeRequired(3, "missing", int32())}, + {{3, Literal::String("not an integer")}})); + auto first = reader->Schema(); + ASSERT_FALSE(first.has_value()); + ASSERT_THAT(reader->Schema(), HasErrorMessage(first.error().message)); + EXPECT_THAT(reader->Next(), HasErrorMessage(first.error().message)); +} + TEST_P(AvroReaderParameterizedTest, AvroWriterBasicType) { auto schema = std::make_shared(std::vector{ SchemaField::MakeRequired(1, "name", std::make_shared())}); diff --git a/src/iceberg/test/file_scan_task_reader_test.cc b/src/iceberg/test/file_scan_task_reader_test.cc index 09d6c750e2..131cf0abe3 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -37,7 +37,6 @@ #include #include #include -#include #include #include #include @@ -61,7 +60,6 @@ #include "iceberg/file_format.h" #include "iceberg/file_io.h" #include "iceberg/file_reader.h" -#include "iceberg/json_serde_internal.h" #include "iceberg/manifest/manifest_entry.h" #include "iceberg/metadata_columns.h" #include "iceberg/parquet/parquet_register.h" @@ -464,37 +462,6 @@ class FileScanTaskReaderTest : public TempFileTestBase { std::shared_ptr projected_schema_; }; -TEST_F(FileScanTaskReaderTest, IdentityPartitionConstantsSurviveJsonAndSplit) { - auto physical = std::make_shared( - std::vector{SchemaField::MakeRequired(1, "id", int32())}); - ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(physical, "[[1], [2], [3]]")); - ICEBERG_UNWRAP_OR_FAIL( - auto spec, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}})); - file->partition_spec_id = 7; - file->partition = PartitionValues({Literal::String("CN")}); - FileScanTask task(file, {}, nullptr, std::move(spec)); - ICEBERG_UNWRAP_OR_FAIL( - auto json, ToJson(task, {{7, std::const_pointer_cast(task.spec())}}, - *table_schema_)); - ICEBERG_UNWRAP_OR_FAIL(auto parsed, FileScanTaskFromJson(json)); - ASSERT_NE(parsed->spec(), nullptr); - EXPECT_EQ(parsed->spec()->spec_id(), 7); - // Use a proper sub-range so the split constructor (not the whole-file path) is tested. - ASSERT_GT(parsed->length(), 1); - ICEBERG_UNWRAP_OR_FAIL( - auto split, FileScanTask::MakeSplit(parsed->data_file(), 0, parsed->length() - 1, - {}, nullptr, parsed->spec())); - ASSERT_TRUE(split->is_split()); - EXPECT_EQ(split->spec(), parsed->spec()); - ICEBERG_UNWRAP_OR_FAIL( - auto reader, FileScanTaskReader::Make({.io = file_io_, - .table_schema = table_schema_, - .schemas = {table_schema_}, - .projected_schema = projected_schema_})); - ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*split)); - VerifyStream(&stream, R"([[1, "CN"], [2, "CN"], [3, "CN"]])"); -} - TEST_F(FileScanTaskReaderTest, IdentityConstantsApplyBeforeEqualityDeletes) { auto physical = std::make_shared( std::vector{SchemaField::MakeRequired(1, "id", int32())}); @@ -520,118 +487,61 @@ TEST_F(FileScanTaskReaderTest, IdentityConstantsApplyBeforeEqualityDeletes) { EXPECT_EQ(table->num_rows(), 0); } -TEST_F(FileScanTaskReaderTest, NullIdentityOverridesInitialDefault) { +TEST_F(FileScanTaskReaderTest, ReadsIdentityValuesFromEachFilesSpec) { auto physical = std::make_shared( std::vector{SchemaField::MakeRequired(1, "id", int32())}); - ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(physical, "[[1], [2], [3]]")); - ICEBERG_UNWRAP_OR_FAIL( - auto spec, PartitionSpec::Make(0, {{2, 1000, "name", Transform::Identity()}})); - file->partition = PartitionValues({Literal::Null(string())}); auto projection = std::make_shared(std::vector{ - SchemaField(2, "name", string(), true, {}, + physical->fields()[0], + SchemaField(2, "name", string(), /*optional=*/true, {}, std::make_shared(Literal::String("default")))}); - FileScanTask task(file, {}, nullptr, std::move(spec)); ICEBERG_UNWRAP_OR_FAIL(auto reader, FileScanTaskReader::Make({.io = file_io_, - .table_schema = table_schema_, - .schemas = {table_schema_}, - .projected_schema = projection})); - ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(task)); - VerifyStream(&stream, "[[null], [null], [null]]"); -} + .table_schema = projection, + .projected_schema = projection, + .apply_residuals = true})); + auto open = [&](std::shared_ptr spec, PartitionValues partition, + std::shared_ptr filter = + nullptr) -> Result { + ICEBERG_ASSIGN_OR_RAISE(auto file, MakeDataFile(physical, "[[1], [2]]", 2)); + file->partition_spec_id = spec->spec_id(); + file->partition = std::move(partition); + ICEBERG_ASSIGN_OR_RAISE( + auto stream, reader->Open(FileScanTask(std::move(file), {}, std::move(filter), + std::move(spec)))); + return nanoarrow::UniqueArrayStream(&stream); + }; -TEST_F(FileScanTaskReaderTest, - ReadsTaskSpecificSpecsWithoutLeakingConstantsBetweenFiles) { ICEBERG_UNWRAP_OR_FAIL( - auto identity, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}})); - ICEBERG_UNWRAP_OR_FAIL(auto unpartitioned, PartitionSpec::Make(8, {})); + std::shared_ptr identity, + PartitionSpec::Make(7, {{3, 1000, "retired", Transform::Identity()}, + {2, 1001, "renamed", Transform::Identity()}})); ICEBERG_UNWRAP_OR_FAIL( auto bucket, - PartitionSpec::Make(9, {{2, 1001, "name_bucket", Transform::Bucket(16)}})); - ICEBERG_UNWRAP_OR_FAIL( - auto reordered, - PartitionSpec::Make(10, {{3, 1002, "category", Transform::Identity()}, - {2, 1000, "renamed_name", Transform::Identity()}})); - struct Case { - std::shared_ptr spec; - PartitionValues partition; - std::string expected; - }; - auto identity_spec = std::shared_ptr(std::move(identity)); - const std::vector cases{ - {.spec = identity_spec, - .partition = PartitionValues(Literal::String("CN")), - .expected = R"([[1, "CN"], [2, "CN"], [3, "CN"]])"}, - {.spec = std::move(unpartitioned), - .partition = PartitionValues(), - .expected = R"([[1, "file"], [2, "file"], [3, "file"]])"}, - {.spec = std::move(bucket), - .partition = PartitionValues(Literal::Int(3)), - .expected = R"([[1, "file"], [2, "file"], [3, "file"]])"}, - {.spec = std::move(reordered), - .partition = PartitionValues({Literal::String("retired"), Literal::String("US")}), - .expected = R"([[1, "US"], [2, "US"], [3, "US"]])"}, - {.spec = identity_spec, - .partition = PartitionValues(Literal::Null(string())), - .expected = "[[1, null], [2, null], [3, null]]"}}; - // The current schema omits category, but historical task schemas retain its type. - ICEBERG_UNWRAP_OR_FAIL( - auto reader, FileScanTaskReader::Make({.io = file_io_, - .table_schema = projected_schema_, - .schemas = {table_schema_}, - .projected_schema = projected_schema_})); - std::vector> readers; - for (const auto& test : cases) { - SCOPED_TRACE(test.spec->spec_id()); - ICEBERG_UNWRAP_OR_FAIL( - auto file, - MakeDataFile(projected_schema_, R"([[1, "file"], [2, "file"], [3, "file"]])")); - file->partition_spec_id = test.spec->spec_id(); - file->partition = test.partition; - ICEBERG_UNWRAP_OR_FAIL(auto json, - ToJson(FileScanTask(file, {}, nullptr, test.spec), - {{test.spec->spec_id(), test.spec}}, *table_schema_)); - ICEBERG_UNWRAP_OR_FAIL(auto task, FileScanTaskFromJson(json)); - ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*task)); - auto imported = ::arrow::ImportRecordBatchReader(&stream); - ASSERT_TRUE(imported.ok()) << imported.status().ToString(); - readers.push_back(imported.ValueOrDie()); - } - // Keep all streams alive to detect accidental sharing of per-file constants. - for (size_t i = 0; i < cases.size(); ++i) { - SCOPED_TRACE(i); - auto next = readers[i]->Next(); - ASSERT_TRUE(next.ok()) << next.status().ToString(); - auto batch = next.ValueOrDie(); - ASSERT_NE(batch, nullptr); - ASSERT_TRUE(batch->ValidateFull().ok()); - ICEBERG_UNWRAP_OR_FAIL(auto expected, - MakeRecordBatch(batch->schema(), cases[i].expected)); - EXPECT_TRUE(batch->Equals(*expected)); - next = readers[i]->Next(); - ASSERT_TRUE(next.ok()) << next.status().ToString(); - EXPECT_EQ(next.ValueOrDie(), nullptr); - } -} - -TEST_F(FileScanTaskReaderTest, RejectsMissingPartitionSpec) { - ICEBERG_UNWRAP_OR_FAIL(auto file, - MakeDataFile(table_schema_, R"([[1, "Foo", "blue"]])", 1)); - ICEBERG_UNWRAP_OR_FAIL( - auto reader, FileScanTaskReader::Make({.io = file_io_, - .table_schema = table_schema_, - .schemas = {table_schema_}, - .projected_schema = projected_schema_})); - file->partition = PartitionValues({Literal::String("CN")}); - EXPECT_FALSE(reader->Open(FileScanTask(file)).has_value()); + PartitionSpec::Make(8, {{2, 1002, "name_bucket", Transform::Bucket(16)}})); + auto filter = Expressions::And(Expressions::Equal("name", Literal::String("CN")), + Expressions::Equal("id", Literal::Int(2))); + // Open all three files before consuming any rows to exercise per-file isolation. + ICEBERG_UNWRAP_OR_FAIL( + auto cn, + open(identity, PartitionValues({Literal::String("old"), Literal::String("CN")}), + filter)); + ICEBERG_UNWRAP_OR_FAIL( + auto nulls, + open(identity, PartitionValues({Literal::String("old"), Literal::Null(string())}))); + ICEBERG_UNWRAP_OR_FAIL(auto hashed, + open(std::move(bucket), PartitionValues(Literal::Int(3)))); + VerifyStream(cn.get(), R"([[2, "CN"]])"); + VerifyStream(nulls.get(), "[[1, null], [2, null]]"); + VerifyStream(hashed.get(), R"([[1, "default"], [2, "default"]])"); } TEST_F(FileScanTaskReaderTest, RejectsPartitionValuesNotMatchingSpec) { ICEBERG_UNWRAP_OR_FAIL(auto file, MakeDataFile(table_schema_, R"([[1, "Foo", "blue"]])", 1)); ICEBERG_UNWRAP_OR_FAIL( - auto spec, PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}, - {3, 1001, "category", Transform::Identity()}})); + std::shared_ptr spec, + PartitionSpec::Make(7, {{2, 1000, "name", Transform::Identity()}, + {3, 1001, "category", Transform::Identity()}})); ICEBERG_UNWRAP_OR_FAIL( auto reader, FileScanTaskReader::Make({.io = file_io_, .table_schema = table_schema_, @@ -639,8 +549,13 @@ TEST_F(FileScanTaskReaderTest, RejectsPartitionValuesNotMatchingSpec) { .projected_schema = projected_schema_})); file->partition_spec_id = 7; file->partition = PartitionValues({Literal::String("CN")}); - EXPECT_THAT(reader->Open(FileScanTask(file, {}, nullptr, std::move(spec))), + EXPECT_THAT(reader->Open(FileScanTask(file, {}, nullptr, spec)), IsError(ErrorKind::kInvalidArgument)); + + file->partition_spec_id = 8; + file->partition = PartitionValues({Literal::String("CN"), Literal::String("blue")}); + EXPECT_THAT(reader->Open(FileScanTask(file, {}, nullptr, spec)), + HasErrorMessage("partition spec ID 8, but task uses spec 7")); } TEST_F(FileScanTaskReaderTest, OpenWithoutDeletesReadsProjectedSchema) { @@ -648,6 +563,9 @@ TEST_F(FileScanTaskReaderTest, OpenWithoutDeletesReadsProjectedSchema) { auto data_file, MakeDataFile(table_schema_, R"([[1, "Foo", "blue"], [2, "Bar", "red"], [3, "Baz", "green"]])")); + // Legacy tasks can carry a partition tuple without a spec and read physical columns. + data_file->partition_spec_id = 7; + data_file->partition = PartitionValues(Literal::Int(3)); FileScanTask task(data_file); FileScanTaskReader::Options options{ diff --git a/src/iceberg/test/json_serde_test.cc b/src/iceberg/test/json_serde_test.cc index 7a0aee5e38..ac860921cb 100644 --- a/src/iceberg/test/json_serde_test.cc +++ b/src/iceberg/test/json_serde_test.cc @@ -1902,6 +1902,8 @@ TEST_F(FileScanTaskJsonTest, RoundTripsValidRanges) { EXPECT_EQ(task->start(), test_case.start); EXPECT_EQ(task->length(), test_case.length); EXPECT_EQ(task->is_split(), test_case.is_split); + ASSERT_NE(task->spec(), nullptr); + EXPECT_EQ(*task->spec(), *spec_); ASSERT_NE(task->data_file(), nullptr); EXPECT_EQ(*task->data_file(), DataFileForTask()); ASSERT_EQ(task->delete_files().size(), 1U); diff --git a/src/iceberg/test/manifest_group_test.cc b/src/iceberg/test/manifest_group_test.cc index 84bd971a96..063ce5804b 100644 --- a/src/iceberg/test/manifest_group_test.cc +++ b/src/iceberg/test/manifest_group_test.cc @@ -290,10 +290,6 @@ TEST_P(ManifestGroupTest, CreateAndGetEntries) { ASSERT_EQ(tasks.size(), 2); EXPECT_THAT(GetPaths(tasks), testing::UnorderedElementsAre("/path/to/data1.parquet", "/path/to/data2.parquet")); - for (const auto& task : tasks) { - ASSERT_NE(task->spec(), nullptr); - EXPECT_EQ(task->spec()->spec_id(), task->data_file()->partition_spec_id); - } EXPECT_EQ(tasks[0]->delete_files().size(), 1); EXPECT_EQ(tasks[1]->delete_files()[0]->file_path, "/path/to/delete.parquet"); EXPECT_EQ(tasks[1]->delete_files().size(), 1); diff --git a/src/iceberg/test/parquet_schema_test.cc b/src/iceberg/test/parquet_schema_test.cc index c9f503691c..52709aa665 100644 --- a/src/iceberg/test/parquet_schema_test.cc +++ b/src/iceberg/test/parquet_schema_test.cc @@ -931,6 +931,7 @@ TEST(ParquetSchemaProjectionTest, ProjectNestedStructures) { std::make_shared(std::vector{ SchemaField::MakeOptional(/*field_id=*/101, "street", iceberg::string()), SchemaField::MakeOptional(/*field_id=*/102, "city", iceberg::string()), + SchemaField::MakeOptional(/*field_id=*/103, "region", iceberg::string()), })), }); @@ -947,7 +948,8 @@ TEST(ParquetSchemaProjectionTest, ProjectNestedStructures) { }); auto schema_manifest = MakeSchemaManifest(parquet_schema); - auto projection_result = Project(expected_schema, schema_manifest); + auto projection_result = + Project(expected_schema, schema_manifest, {{103, Literal::String("CN")}}); ASSERT_THAT(projection_result, IsOk()); const auto& projection = *projection_result; @@ -955,11 +957,11 @@ TEST(ParquetSchemaProjectionTest, ProjectNestedStructures) { ASSERT_PROJECTED_FIELD(projection.fields[0], 0); ASSERT_PROJECTED_FIELD(projection.fields[1], 1); - ASSERT_EQ(projection.fields[1].children.size(), 2); + ASSERT_EQ(projection.fields[1].children.size(), 3); ASSERT_PROJECTED_FIELD(projection.fields[1].children[0], 0); ASSERT_PROJECTED_FIELD(projection.fields[1].children[1], 1); - - ASSERT_EQ(SelectedColumnIndices(projection), std::vector({0, 2, 3})); + EXPECT_EQ(projection.fields[1].children[2].kind, FieldProjection::Kind::kConstant); + EXPECT_EQ(SelectedColumnIndices(projection), std::vector({0, 2, 3})); } TEST(ParquetSchemaProjectionTest, ProjectListType) { diff --git a/src/iceberg/test/parquet_test.cc b/src/iceberg/test/parquet_test.cc index 4edeed1fa7..cb59b90994 100644 --- a/src/iceberg/test/parquet_test.cc +++ b/src/iceberg/test/parquet_test.cc @@ -45,7 +45,6 @@ #include "iceberg/arrow/arrow_io_internal.h" #include "iceberg/arrow/arrow_status_internal.h" -#include "iceberg/expression/expressions.h" #include "iceberg/expression/literal.h" #include "iceberg/file_reader.h" #include "iceberg/file_writer.h" @@ -245,7 +244,8 @@ class ParquetReaderTest : public TempFileTestBase { temp_parquet_file_ = "parquet_reader_test.parquet"; } - void CreateSimpleParquetFile() { + void CreateSimpleParquetFile( + std::string_view rows = R"([[1, "Foo"],[2, "Bar"],[3, "Baz"]])") { auto schema = std::make_shared( std::vector{SchemaField::MakeRequired(1, "id", int32()), SchemaField::MakeOptional(2, "name", string())}); @@ -255,8 +255,7 @@ class ParquetReaderTest : public TempFileTestBase { auto arrow_schema = ::arrow::ImportType(&arrow_c_schema).ValueOrDie(); auto array = - ::arrow::json::ArrayFromJSONString(::arrow::struct_(arrow_schema->fields()), - R"([[1, "Foo"],[2, "Bar"],[3, "Baz"]])") + ::arrow::json::ArrayFromJSONString(::arrow::struct_(arrow_schema->fields()), rows) .ValueOrDie(); WriterProperties writer_properties; @@ -518,16 +517,20 @@ class ParquetReaderTest : public TempFileTestBase { std::string temp_parquet_file_; }; -TEST_F(ParquetReaderTest, PromotesPartitionConstant) { - CreateSimpleParquetFile(); +TEST_F(ParquetReaderTest, ReadsPartitionValuesOnlyForMissingFieldIds) { + ASSERT_NO_FATAL_FAILURE(CreateSimpleParquetFile(R"([[1,"Foo"],[2,null],[3,"Baz"]])")); auto schema = std::make_shared( - std::vector{SchemaField::MakeRequired(3, "constant", int64())}); + std::vector{SchemaField::MakeOptional(2, "renamed", string()), + SchemaField::MakeRequired(3, "constant", int64()), + SchemaField::MakeOptional(4, "missing", string())}); ReaderOptions options{.path = temp_parquet_file_, .io = file_io_, .projection = schema}; - options.id_to_constant.emplace(3, Literal::Int(7)); + options.id_to_constant = { + {2, Literal::String("CN")}, {3, Literal::Int(7)}, {4, Literal::Null(unknown())}}; ICEBERG_UNWRAP_OR_FAIL(auto reader, ReaderFactoryRegistry::Open(FileFormatType::kParquet, options)); - VerifyNextBatch(*reader, "[[7], [7], [7]]"); + ASSERT_NO_FATAL_FAILURE( + VerifyNextBatch(*reader, R"([["Foo",7,null],[null,7,null],["Baz",7,null]])")); VerifyExhausted(*reader); } @@ -566,26 +569,31 @@ TEST_F(ParquetReaderTest, ReadWithoutFieldIdsOrNameMapping) { TEST_F(ParquetReaderTest, ReadWithNameMapping) { ASSERT_NO_FATAL_FAILURE(CreateParquetFileWithoutFieldIds( ::arrow::struct_({::arrow::field("id", ::arrow::int32()), - ::arrow::field("name", ::arrow::utf8())}), - R"([[1, "Foo"], [2, "Bar"], [3, "Baz"]])")); + ::arrow::field("name", ::arrow::utf8()), + ::arrow::field("region", ::arrow::utf8())}), + R"([[1, "Foo", "US"], [2, "Bar", "US"]])")); auto schema = std::make_shared(std::vector{ SchemaField::MakeOptional(2, "full_name", string()), SchemaField::MakeOptional(1, "id", int64()), SchemaField::MakeOptional(3, "extra", string()), + SchemaField::MakeOptional(4, "region", string()), }); auto mapping = NameMapping::Make({ MappedField{.names = {"id"}, .field_id = 1}, MappedField{.names = {"name", "full_name"}, .field_id = 2}, + MappedField{.names = {"region"}, .field_id = 4}, }); ICEBERG_UNWRAP_OR_FAIL( - auto reader, ReaderFactoryRegistry::Open(FileFormatType::kParquet, - {.path = temp_parquet_file_, - .io = file_io_, - .projection = schema, - .name_mapping = std::move(mapping)})); - ASSERT_NO_FATAL_FAILURE(VerifyNextBatch( - *reader, R"([["Foo", 1, null], ["Bar", 2, null], ["Baz", 3, null]])")); + auto reader, + ReaderFactoryRegistry::Open(FileFormatType::kParquet, + {.path = temp_parquet_file_, + .io = file_io_, + .projection = schema, + .name_mapping = std::move(mapping), + .id_to_constant = {{4, Literal::String("CN")}}})); + ASSERT_NO_FATAL_FAILURE( + VerifyNextBatch(*reader, R"([["Foo", 1, null, "CN"], ["Bar", 2, null, "CN"]])")); ASSERT_NO_FATAL_FAILURE(VerifyExhausted(*reader)); } diff --git a/src/iceberg/test/rest_json_serde_test.cc b/src/iceberg/test/rest_json_serde_test.cc index 0ef1843769..3470a21936 100644 --- a/src/iceberg/test/rest_json_serde_test.cc +++ b/src/iceberg/test/rest_json_serde_test.cc @@ -2652,8 +2652,6 @@ TEST(FetchScanTasksResponseRoundtripTest, PreservesResidualFilter) { ASSERT_TRUE(result->file_scan_tasks.has_value()); ASSERT_EQ(result->file_scan_tasks->size(), 1); ASSERT_NE(result->file_scan_tasks->at(0)->residual_filter(), nullptr); - ASSERT_NE(result->file_scan_tasks->at(0)->spec(), nullptr); - EXPECT_EQ(result->file_scan_tasks->at(0)->spec()->spec_id(), 0); ICEBERG_UNWRAP_OR_FAIL(auto roundtrip_json, ToJson(*result, UnpartitionedSpecs(), EmptySchema())); diff --git a/src/iceberg/test/rest_table_scan_test.cc b/src/iceberg/test/rest_table_scan_test.cc index 4877ac2556..2b2d96c7d2 100644 --- a/src/iceberg/test/rest_table_scan_test.cc +++ b/src/iceberg/test/rest_table_scan_test.cc @@ -991,6 +991,7 @@ TEST_P(RestScanResidualTest, PreservesSplitRangesFilteringAndDeleteFiles) { EXPECT_TRUE(tasks[0]->is_split()); EXPECT_EQ(tasks[0]->start(), 25); EXPECT_EQ(tasks[0]->length(), 50); + EXPECT_EQ(tasks[0]->spec(), metadata_->partition_specs.front()); ASSERT_EQ(tasks[0]->delete_files().size(), 1); EXPECT_EQ(tasks[0]->delete_files()[0]->file_path, "s3://bucket/delete.parquet"); ASSERT_NE(tasks[0]->residual_filter(), nullptr); diff --git a/src/iceberg/test/schema_util_test.cc b/src/iceberg/test/schema_util_test.cc index 642aa9e7bf..785a903509 100644 --- a/src/iceberg/test/schema_util_test.cc +++ b/src/iceberg/test/schema_util_test.cc @@ -101,49 +101,6 @@ std::shared_ptr CreateMapOfList() { } // namespace -TEST(SchemaUtilTest, ProjectConstantsOverridePhysicalFieldsAndPruneIndices) { - Schema schema({SchemaField::MakeRequired(1, "region", string()), - SchemaField::MakeRequired(2, "id", int64())}); - for (bool prune_source : {false, true}) { - auto projection = Project(schema, schema, prune_source, ProjectionMode::kRead, - {{1, Literal::String("CN")}}); - ASSERT_THAT(projection, IsOk()); - ASSERT_EQ(projection->fields.size(), 2); - EXPECT_EQ(projection->fields[0].kind, FieldProjection::Kind::kConstant); - EXPECT_EQ(std::get(projection->fields[0].from), Literal::String("CN")); - AssertProjectedField(projection->fields[1], prune_source ? 0 : 1); - } -} - -TEST(SchemaUtilTest, ProjectConstantsFillMissingFields) { - Schema expected({SchemaField::MakeRequired(1, "id", int64()), - SchemaField::MakeOptional(2, "region", string())}); - auto projection = - Project(expected, Schema({}), /*prune_source=*/true, ProjectionMode::kRead, - {{1, Literal::Int(7)}, {2, Literal::Null(string())}}); - ASSERT_THAT(projection, IsOk()); - ASSERT_EQ(projection->fields.size(), 2); - EXPECT_EQ(projection->fields[0].kind, FieldProjection::Kind::kConstant); - EXPECT_EQ(projection->fields[1].kind, FieldProjection::Kind::kConstant); -} - -TEST(SchemaUtilTest, ProjectConstantsIntoExistingStruct) { - Schema schema( - {SchemaField::MakeOptional(1, "parent", - std::make_shared(std::vector{ - SchemaField::MakeOptional(2, "region", string()), - SchemaField::MakeRequired(3, "id", int64())}))}); - auto projection = Project(schema, schema, /*prune_source=*/true, ProjectionMode::kRead, - {{2, Literal::String("CN")}}); - ASSERT_THAT(projection, IsOk()); - ASSERT_EQ(projection->fields.size(), 1); - const auto& parent = projection->fields[0]; - AssertProjectedField(parent, 0); - ASSERT_EQ(parent.children.size(), 2); - EXPECT_EQ(parent.children[0].kind, FieldProjection::Kind::kConstant); - AssertProjectedField(parent.children[1], 0); -} - TEST(SchemaUtilTest, ProjectIdenticalSchemas) { Schema schema = CreateFlatSchema(); diff --git a/src/iceberg/test/table_scan_test.cc b/src/iceberg/test/table_scan_test.cc index ecca974622..29e707a2fb 100644 --- a/src/iceberg/test/table_scan_test.cc +++ b/src/iceberg/test/table_scan_test.cc @@ -150,16 +150,17 @@ class TableScanTest : public ScanTestBase { /// single snapshot references them. std::shared_ptr MakeTaskPlanningMetadata( std::vector data_entries, - std::vector delete_entries = {}) { + std::vector delete_entries = {}, + std::shared_ptr file_spec = PartitionSpec::Unpartitioned()) { constexpr int64_t kSnapshotId = 1000L; constexpr int64_t kSequenceNumber = 1L; std::vector manifests; - manifests.push_back(WriteDataManifest(GetParam(), kSnapshotId, - std::move(data_entries), unpartitioned_spec_)); + manifests.push_back( + WriteDataManifest(GetParam(), kSnapshotId, std::move(data_entries), file_spec)); if (!delete_entries.empty()) { - manifests.push_back(WriteDeleteManifest( - GetParam(), kSnapshotId, std::move(delete_entries), unpartitioned_spec_)); + manifests.push_back(WriteDeleteManifest(GetParam(), kSnapshotId, + std::move(delete_entries), file_spec)); } std::string manifest_list_path = WriteManifestList(GetParam(), kSnapshotId, kSequenceNumber, std::move(manifests)); @@ -1139,8 +1140,19 @@ TEST_P(TableScanTest, FixedByteRangesReadEveryParquetRowOnce) { WriteParquetDataFile("planned-data.parquet", kRows, 50)); ASSERT_GT(entry_file->split_offsets.size(), 1); entry_file->split_offsets.clear(); + + // A migrated file stores its region only in the manifest partition tuple. + schema_ = std::make_shared( + std::vector{schema_->fields()[0], schema_->fields()[1], + SchemaField::MakeRequired(3, "region", string())}); + ICEBERG_UNWRAP_OR_FAIL( + partitioned_spec_, + PartitionSpec::Make(1, {{3, 1000, "region", Transform::Identity()}})); + entry_file->partition_spec_id = partitioned_spec_->spec_id(); + entry_file->partition = PartitionValues({Literal::String("CN")}); auto metadata = MakeTaskPlanningMetadata( - {MakeEntry(ManifestStatus::kAdded, 1000L, 1L, entry_file)}); + {MakeEntry(ManifestStatus::kAdded, 1000L, 1L, entry_file)}, {}, partitioned_spec_); + metadata->last_column_id = 3; const int64_t target = entry_file->file_size_in_bytes / 4; ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); @@ -1156,13 +1168,17 @@ TEST_P(TableScanTest, FixedByteRangesReadEveryParquetRowOnce) { std::vector ids; for (const auto& group : groups) { for (const auto& task : group->tasks()) { + ASSERT_TRUE(task->is_split()); ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*task)); auto batches = ::arrow::ImportRecordBatchReader(&stream).ValueOrDie(); for (auto next : *batches) { ASSERT_TRUE(next.ok()) << next.status(); const auto& column = static_cast(*(*next)->column(0)); + const auto& region = + static_cast(*(*next)->column(2)); for (int64_t row = 0; row < column.length(); ++row) { ids.push_back(column.Value(row)); + EXPECT_EQ(region.GetView(row), "CN"); } } }