diff --git a/src/iceberg/arrow/literal_util.cc b/src/iceberg/arrow/literal_util.cc index e8ee4d6c6..0d21d73de 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 4de60b528..5bc358a5a 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 5c6c19dec..1ae6d7b1d 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); } @@ -514,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); @@ -594,7 +573,8 @@ 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) { // 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 @@ -613,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; } @@ -633,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_direct_decoder.cc b/src/iceberg/avro/avro_direct_decoder.cc index c2d0a3c9c..42ae3f13b 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 06d536e7d..6f254100c 100644 --- a/src/iceberg/avro/avro_reader.cc +++ b/src/iceberg/avro/avro_reader.cc @@ -349,8 +349,10 @@ 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.id_to_constant, + /*ids_from_name_mapping=*/has_id_visitor.HasNoIds())); ICEBERG_RETURN_UNEXPECTED(backend_->InitWithSchema(file_schema, options.split)); @@ -434,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)); @@ -443,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 94d0a6116..cf93e0aa5 100644 --- a/src/iceberg/avro/avro_schema_util.cc +++ b/src/iceberg/avro/avro_schema_util.cc @@ -683,14 +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 ProjectionOptions& options); Result ProjectField(const SchemaField& expected_field, const ::avro::NodePtr& avro_node, - size_t source_index, bool prune_source) { + 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,7 +715,7 @@ Result ProjectField(const SchemaField& expected_field, if (expected_type.is_nested()) { ICEBERG_ASSIGN_OR_RAISE(projection, - ProjectNested(expected_type, field_node, prune_source)); + ProjectNested(expected_type, field_node, options)); } else { ICEBERG_RETURN_UNEXPECTED(ValidateAvroSchemaEvolution(expected_type, field_node)); } @@ -719,7 +726,7 @@ Result ProjectField(const SchemaField& expected_field, Result ProjectStruct(const StructType& struct_type, const ::avro::NodePtr& avro_node, - bool prune_source) { + const ProjectionOptions& options) { if (avro_node->type() != ::avro::AVRO_RECORD) { return InvalidSchema("Expected AVRO_RECORD type, but got {}", ToString(avro_node)); } @@ -735,6 +742,10 @@ Result ProjectStruct(const StructType& struct_type, 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), @@ -744,17 +755,21 @@ 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 iter = node_info_map.find(field_id); iter != node_info_map.cend()) { + if (auto source = node_info_map.find(field_id); source != node_info_map.end()) { ICEBERG_ASSIGN_OR_RAISE(child_projection, - ProjectField(expected_field, iter->second.field_node, - iter->second.local_index, prune_source)); + 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 (MetadataColumns::IsMetadataColumn(field_id)) { child_projection.kind = FieldProjection::Kind::kMetadata; } else if (expected_field.initial_default() != nullptr) { @@ -770,7 +785,7 @@ Result ProjectStruct(const StructType& struct_type, result.children.emplace_back(std::move(child_projection)); } - if (prune_source) { + if (options.prune_source) { PruneFieldProjection(result); } @@ -778,7 +793,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, + const ProjectionOptions& options) { if (avro_node->type() != ::avro::AVRO_ARRAY) { return InvalidSchema("Expected AVRO_ARRAY type, but got {}", ToString(avro_node)); } @@ -797,19 +813,20 @@ 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)); + /*source_index*/ size_t{0}, options)); - 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 ::avro::NodePtr& avro_node, + const ProjectionOptions& options) { 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; @@ -856,7 +873,7 @@ 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)); + ProjectField(expected_sub_field, map_node->leafAt(i), i, options)); result.children.emplace_back(std::move(sub_projection)); } @@ -865,7 +882,7 @@ Result ProjectMap(const MapType& map_type, Result ProjectNested(const Type& expected_type, const ::avro::NodePtr& avro_node, - bool prune_source) { + const ProjectionOptions& options) { if (!expected_type.is_nested()) { return InvalidSchema("Expected a nested type, but got {}", expected_type); } @@ -873,13 +890,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, options); case TypeId::kList: return ProjectList(internal::checked_cast(expected_type), - avro_node, prune_source); + avro_node, options); case TypeId::kMap: return ProjectMap(internal::checked_cast(expected_type), avro_node, - prune_source); + options); default: return InvalidSchema("Unsupported nested type: {}", expected_type); } @@ -893,11 +910,15 @@ 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) { - ICEBERG_ASSIGN_OR_RAISE( - auto field_projection, - ProjectNested(static_cast(expected_schema), avro_node, prune_source)); +Result Project( + const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source, + 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(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 342b119a5..cc669d72d 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,9 +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 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); +Result Project( + const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source, + 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 7b862e729..df24be9eb 100644 --- a/src/iceberg/catalog/rest/json_serde.cc +++ b/src/iceberg/catalog/rest/json_serde.cc @@ -231,9 +231,11 @@ Result>> FileScanTasksFromJson( ICEBERG_ASSIGN_OR_RAISE(residual_filter, ExpressionFromJson(filter_json)); } + // 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(residual_filter), 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 fa2bc6737..9ef9cdb74 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 a277f507b..78b56e95b 100644 --- a/src/iceberg/data/file_scan_task_reader.cc +++ b/src/iceberg/data/file_scan_task_reader.cc @@ -36,23 +36,58 @@ #include "iceberg/file_reader.h" #include "iceberg/manifest/manifest_entry.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> IdentityPartitionConstants( + const FileScanTask& task) { + const auto& file = *task.data_file(); + const auto& spec = task.spec(); + std::unordered_map id_to_constant; + if (!spec) { + 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", + 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) { + return InvalidArgument("Missing transform for partition field {}", + field.field_id()); + } + if (field.transform()->transform_type() == TransformType::kIdentity) { + ICEBERG_ASSIGN_OR_RAISE(auto value, file.partition.ValueAt(i)); + id_to_constant.emplace(field.source_id(), value.get()); + } + } + 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) { const auto& data_file = *task.data_file(); + 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), @@ -68,6 +103,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 +325,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 00fc2583d..a4221b662 100644 --- a/src/iceberg/file_reader.h +++ b/src/iceberg/file_reader.h @@ -26,8 +26,10 @@ #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" @@ -129,6 +131,11 @@ struct ICEBERG_EXPORT ReaderOptions { std::optional data_sequence_number; /// \brief Format-specific or implementation-specific properties. ReaderProperties properties; + + /// \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; }; /// \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 1ea146901..b47a35fd8 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 036a71bdc..1d15e2428 100644 --- a/src/iceberg/manifest/manifest_group.cc +++ b/src/iceberg/manifest/manifest_group.cc @@ -319,8 +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))}; + std::move(value.data_file), std::move(delete_files), std::move(residual), + spec_iter->second)}; } } diff --git a/src/iceberg/parquet/parquet_data_util.cc b/src/iceberg/parquet/parquet_data_util.cc index b5024c486..27453dac0 100644 --- a/src/iceberg/parquet/parquet_data_util.cc +++ b/src/iceberg/parquet/parquet_data_util.cc @@ -252,7 +252,8 @@ 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::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 3e5930f10..08585653a 100644 --- a/src/iceberg/parquet/parquet_reader.cc +++ b/src/iceberg/parquet/parquet_reader.cc @@ -63,9 +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) { +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())) { @@ -78,11 +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); + 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())); - return projection; + return Project(read_schema, reader->manifest(), id_to_constant); } // Stored ARROW:schema metadata can override ArrowReaderProperties::set_list_type(). @@ -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.id_to_constant)); 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 d16b8a1ae..fa76f49c3 100644 --- a/src/iceberg/parquet/parquet_schema_util.cc +++ b/src/iceberg/parquet/parquet_schema_util.cc @@ -504,7 +504,12 @@ namespace { class ProjectionBuilder { public: - explicit ProjectionBuilder(const ::parquet::SchemaDescriptor* descr) : descr_(descr) {} + ProjectionBuilder(const ::parquet::SchemaDescriptor* descr, + 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, @@ -571,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}) @@ -592,6 +601,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 = 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) { @@ -719,6 +732,8 @@ class ProjectionBuilder { } const ::parquet::SchemaDescriptor* descr_; + const std::unordered_map& id_to_constant_; + bool ids_from_name_mapping_; }; void CollectColumnIds(const FieldProjection& field_projection, @@ -783,9 +798,11 @@ void ApplyNameMappingToField(const NameMapping& mapping, std::vector Project(const Schema& expected_schema, - const ::parquet::arrow::SchemaManifest& parquet_schema) { - ProjectionBuilder builder(parquet_schema.descr); +Result Project( + const Schema& expected_schema, const ::parquet::arrow::SchemaManifest& parquet_schema, + 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 49c62ff09..be209ed36 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,10 +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 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); +Result Project( + const Schema& expected_schema, const ::parquet::arrow::SchemaManifest& parquet_schema, + 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 2a4ec435b..879cfb480 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/table_scan.cc b/src/iceberg/table_scan.cc index a29ee0043..ca3835303 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 3781d88cf..31998c182 100644 --- a/src/iceberg/table_scan.h +++ b/src/iceberg/table_scan.h @@ -73,11 +73,14 @@ 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. - /// \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); + 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 +91,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 +114,10 @@ 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. + /// 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; int32_t files_count() const override; @@ -128,12 +136,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_schema_test.cc b/src/iceberg/test/avro_schema_test.cc index f147a607b..b6eb20087 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 71062375f..5d04a6251 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,8 +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, 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(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_); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + ReaderFactoryRegistry::Open(FileFormatType::kAvro, options)); + 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 898342d76..131cf0abe 100644 --- a/src/iceberg/test/file_scan_task_reader_test.cc +++ b/src/iceberg/test/file_scan_task_reader_test.cc @@ -72,6 +72,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,11 +462,110 @@ class FileScanTaskReaderTest : public TempFileTestBase { std::shared_ptr projected_schema_; }; +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, ReadsIdentityValuesFromEachFilesSpec) { + auto physical = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int32())}); + auto projection = std::make_shared(std::vector{ + physical->fields()[0], + SchemaField(2, "name", string(), /*optional=*/true, {}, + std::make_shared(Literal::String("default")))}); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + FileScanTaskReader::Make({.io = file_io_, + .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); + }; + + ICEBERG_UNWRAP_OR_FAIL( + 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(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( + 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_, + .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, 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) { ICEBERG_UNWRAP_OR_FAIL( 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 7a0aee5e3..ac860921c 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/parquet_schema_test.cc b/src/iceberg/test/parquet_schema_test.cc index c9f503691..52709aa66 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 e7642dbe0..cb59b9099 100644 --- a/src/iceberg/test/parquet_test.cc +++ b/src/iceberg/test/parquet_test.cc @@ -244,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())}); @@ -254,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; @@ -517,6 +517,23 @@ class ParquetReaderTest : public TempFileTestBase { std::string temp_parquet_file_; }; +TEST_F(ParquetReaderTest, ReadsPartitionValuesOnlyForMissingFieldIds) { + ASSERT_NO_FATAL_FAILURE(CreateSimpleParquetFile(R"([[1,"Foo"],[2,null],[3,"Baz"]])")); + auto schema = std::make_shared( + 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 = { + {2, Literal::String("CN")}, {3, Literal::Int(7)}, {4, Literal::Null(unknown())}}; + ICEBERG_UNWRAP_OR_FAIL(auto reader, + ReaderFactoryRegistry::Open(FileFormatType::kParquet, options)); + ASSERT_NO_FATAL_FAILURE( + VerifyNextBatch(*reader, R"([["Foo",7,null],[null,7,null],["Baz",7,null]])")); + VerifyExhausted(*reader); +} + TEST_F(ParquetReaderTest, ReadTwoFields) { CreateSimpleParquetFile(); @@ -552,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_table_scan_test.cc b/src/iceberg/test/rest_table_scan_test.cc index 4877ac255..2b2d96c7d 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/table_scan_test.cc b/src/iceberg/test/table_scan_test.cc index ecca97462..29e707a2f 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"); } } }