From 7917eed7e9a33f2c817b65a924b3e858e6df2370 Mon Sep 17 00:00:00 2001 From: Andrey Zvonov <32552679+zvonand@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:48:39 +0100 Subject: [PATCH] Support aggregate function states in Parquet and Iceberg Parquet files and Iceberg tables can now store `AggregateFunction` states and `SimpleAggregateFunction` columns, and ClickHouse reads them back with their original types. A state is stored as binary, and the ClickHouse type is recorded in the `clickhouse.column_types` Parquet file metadata or in the `clickhouse.type..` Iceberg table properties. Writing and reading `AggregateFunction` states requires the new setting `allow_aggregate_function_states_in_open_formats`, disabled by default. A table can also set it in the `SETTINGS` clause of its engine. Closes: https://github.com/Altinity/ClickHouse/issues/2206 --- src/Client/ClientBase.cpp | 1 + src/Core/FormatFactorySettings.h | 15 + src/Core/SettingsChangesHistory.cpp | 4 + src/DataTypes/DataTypeAggregateFunction.cpp | 71 ++- src/DataTypes/DataTypeAggregateFunction.h | 12 + src/DataTypes/DataTypeFactory.cpp | 28 +- src/DataTypes/DataTypeFactory.h | 2 + ...est_resolve_clickhouse_type_annotation.cpp | 29 ++ src/Databases/DataLake/GlueCatalog.cpp | 1 + src/Databases/DataLake/GlueCatalog.h | 1 + src/Databases/DataLake/ICatalog.cpp | 1 + src/Databases/DataLake/ICatalog.h | 2 + src/Databases/DataLake/RestCatalog.cpp | 90 +++- src/Databases/DataLake/RestCatalog.h | 7 +- src/Databases/DataLake/UnityV2Catalog.cpp | 4 +- src/Databases/DataLake/UnityV2Catalog.h | 1 + .../gtest_rest_catalog_update_metadata.cpp | 22 + src/Formats/FormatFactory.cpp | 29 ++ src/Formats/FormatFactory.h | 10 + src/Formats/FormatSettings.h | 1 + .../Impl/ClickHouseColumnTypesMetadata.cpp | 94 ++++ .../Impl/ClickHouseColumnTypesMetadata.h | 21 + .../Formats/Impl/Parquet/Decoding.cpp | 30 ++ .../Formats/Impl/Parquet/Decoding.h | 15 + .../Formats/Impl/Parquet/PrepareForWrite.cpp | 163 ++++++ .../Formats/Impl/Parquet/SchemaConverter.cpp | 88 +++- .../Formats/Impl/Parquet/SchemaConverter.h | 5 + src/Processors/Formats/Impl/Parquet/Write.cpp | 22 +- src/Processors/Formats/Impl/Parquet/Write.h | 7 + .../gtest_annotated_type_matches_derived.cpp | 70 +++ .../Formats/Impl/ParquetBlockOutputFormat.cpp | 1 + .../Impl/ParquetV3BlockInputFormat.cpp | 35 +- ...portReplicatedMergeTreePartitionManifest.h | 8 + .../ExportPartitionTaskScheduler.cpp | 8 +- .../MergeTree/ExportPartitionUtils.cpp | 4 + .../MergeTree/MergeTreePartitionExportTask.h | 5 + .../tests/gtest_export_partition_ordering.cpp | 64 +++ .../DataLakes/DataLakeConfiguration.h | 17 +- .../DataLakes/IDataLakeMetadata.cpp | 4 +- .../DataLakes/Iceberg/AddFilesExecute.cpp | 3 +- .../DataLakes/Iceberg/BinPackRewrite.cpp | 13 +- .../DataLakes/Iceberg/BinPackRewrite.h | 1 + .../DataLakes/Iceberg/Compaction.cpp | 12 +- .../DataLakes/Iceberg/Constant.h | 1 + .../DataLakes/Iceberg/DataFileStatistics.cpp | 36 +- .../DataLakes/Iceberg/DataFileStatistics.h | 1 + .../Iceberg/ExpireSnapshotsExecute.cpp | 3 + .../DataLakes/Iceberg/IcebergMetadata.cpp | 90 +++- .../DataLakes/Iceberg/IcebergMetadata.h | 25 +- .../Iceberg/ManifestFileIterator.cpp | 3 +- .../Iceberg/ManifestFilesPruning.cpp | 7 + .../DataLakes/Iceberg/MetadataGenerator.cpp | 211 ++++---- .../DataLakes/Iceberg/MetadataGenerator.h | 11 +- .../DataLakes/Iceberg/Mutations.cpp | 18 +- .../Iceberg/RemoveOrphanFilesExecute.cpp | 3 + .../DataLakes/Iceberg/SchemaProcessor.cpp | 191 +++++-- .../DataLakes/Iceberg/SchemaProcessor.h | 48 +- .../ObjectStorage/DataLakes/Iceberg/Utils.cpp | 473 +++++++++++++----- .../ObjectStorage/DataLakes/Iceberg/Utils.h | 37 +- .../gtest_iceberg_metadata_generator.cpp | 93 +++- .../tests/gtest_iceberg_schema_processor.cpp | 291 +++++++++-- .../tests/gtest_iceberg_type_mapping.cpp | 27 + .../ObjectStorage/StorageObjectStorage.cpp | 52 +- .../ObjectStorage/StorageObjectStorage.h | 5 +- .../StorageObjectStorageCluster.cpp | 14 +- .../StorageObjectStorageCluster.h | 3 +- .../registerStorageObjectStorage.cpp | 55 +- src/Storages/StorageFile.cpp | 23 +- src/Storages/StorageFile.h | 4 + src/Storages/StorageMergeTree.cpp | 3 + src/Storages/StorageReplicatedMergeTree.cpp | 3 + src/Storages/StorageURL.cpp | 39 +- src/Storages/StorageURL.h | 8 +- src/TableFunctions/TableFunctionFile.cpp | 1 + .../TableFunctionFileCluster.cpp | 3 +- .../helpers/export_partition_helpers.py | 4 +- .../integration/test_database_iceberg/test.py | 63 +++ .../test.py | 37 ++ .../configs/users.d/profile.xml | 2 + .../test_schema_match.py | 46 ++ .../test_aggregate_function_states.py | 183 +++++++ ...902_topKGeneric_deserialization_memory.sql | 3 +- ...parquet_aggregate_function_state.reference | 78 +++ .../04673_parquet_aggregate_function_state.sh | 186 +++++++ ...tion_state_annotation_per_schema.reference | 18 + ...te_function_state_annotation_per_schema.sh | 46 ++ ..._function_state_annotated_bounds.reference | 2 + ...gregate_function_state_annotated_bounds.sh | 28 ++ ...te_function_states_table_setting.reference | 24 + ...aggregate_function_states_table_setting.sh | 112 +++++ ..._states_table_setting_on_cluster.reference | 3 + ...unction_states_table_setting_on_cluster.sh | 43 ++ ...aggregate_function_state_version.reference | 9 + ...column_aggregate_function_state_version.sh | 52 ++ ...nction_state_annotated_partition.reference | 3 + ...gate_function_state_annotated_partition.sh | 45 ++ 96 files changed, 3325 insertions(+), 465 deletions(-) create mode 100644 src/DataTypes/tests/gtest_resolve_clickhouse_type_annotation.cpp create mode 100644 src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.cpp create mode 100644 src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.h create mode 100644 src/Processors/Formats/Impl/Parquet/tests/gtest_annotated_type_matches_derived.cpp create mode 100644 tests/integration/test_storage_iceberg_with_spark/test_aggregate_function_states.py create mode 100644 tests/queries/0_stateless/04673_parquet_aggregate_function_state.reference create mode 100755 tests/queries/0_stateless/04673_parquet_aggregate_function_state.sh create mode 100644 tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.reference create mode 100755 tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.sh create mode 100644 tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.reference create mode 100755 tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.sh create mode 100644 tests/queries/0_stateless/05814_aggregate_function_states_table_setting.reference create mode 100755 tests/queries/0_stateless/05814_aggregate_function_states_table_setting.sh create mode 100644 tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.reference create mode 100755 tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.sh create mode 100644 tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.reference create mode 100755 tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.sh create mode 100644 tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.reference create mode 100755 tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.sh diff --git a/src/Client/ClientBase.cpp b/src/Client/ClientBase.cpp index 925b73cb464a0..17470c0b11239 100644 --- a/src/Client/ClientBase.cpp +++ b/src/Client/ClientBase.cpp @@ -2546,6 +2546,7 @@ void ClientBase::sendData(Block & sample, const ColumnsDescription & columns_des ConstraintsDescription{}, String{}, {}, + std::nullopt /*table_allow_aggregate_function_states*/, }; StoragePtr storage = std::make_shared(StorageFile::FileSource::parse(in_file, client_context), args); storage->startup(); diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 4951eda47549b..ddec7e2fff317 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -1742,6 +1742,21 @@ Use geo column parser to convert Array(UInt8) into Point/MultiPoint/Linestring/P )", 0) \ DECLARE(Bool, input_format_parquet_detect_variant_by_structure, true, R"( Read a Parquet group that has no `VARIANT` logical type, but has the layout of an unshredded variant (a `metadata` and a `value` field of type `BYTE_ARRAY`), as a variant, i.e. as `Dynamic`, instead of `Tuple`. Spark 4.0 writes variant columns this way. Groups annotated with the `VARIANT` logical type are always read as a variant. +)", 0) \ + DECLARE(Bool, allow_aggregate_function_states_in_open_formats, false, R"( +Allow `AggregateFunction` states in Parquet files and Iceberg tables. A state is stored as binary, with its ClickHouse +type recorded in `clickhouse.column_types` (Parquet file metadata) or `clickhouse.type..` +(Iceberg table properties). The recorded type chooses the deserializer for the stored bytes, so enable the setting +only for trusted sources. + +When disabled, writing a state throws `SUPPORT_IS_DISABLED`. On read, a Parquet state column reads as `String`, and a +query on an Iceberg table with a state column throws `SUPPORT_IS_DISABLED`. `SimpleAggregateFunction` columns are not +affected. + +A table can also set it in the `SETTINGS` clause of its engine (for example `S3` or `IcebergS3`). That value is stored +with the table and applies to every query on it, whatever the query sets. +More [in Parquet](/reference/formats/Parquet/Parquet#aggregate-function-states) and +[in Iceberg](/reference/engines/table-engines/integrations/iceberg#aggregate-function-states). )", 0) \ DECLARE(Bool, output_format_parquet_geometadata, true, R"( Allow to write information about geo columns in parquet metadata and encode columns in WKB format. diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 8e78da86f52b3..7db960b7bb38f 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -50,6 +50,10 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() { {"azure_validate_etag_on_read", false, true, "New setting to detect concurrent in-place overwrites of Azure blobs during a read by pinning every `GET` to the listed `ETag` with `If-Match` and validating the `ETag` of the response, like `s3_validate_etag_on_read` does for S3. `compatibility` with versions before 26.10 restores the previous behavior (no validation)."}, }); + addSettingsChanges(settings_changes_history, "26.8.39.20001.altinityantalya", + { + {"allow_aggregate_function_states_in_open_formats", false, false, "New setting allowing aggregate function states in Parquet files and Iceberg tables. With it disabled, writing a state throws `SUPPORT_IS_DISABLED`, a Parquet state column reads as `String`, and a query on an Iceberg table with a state column throws `SUPPORT_IS_DISABLED`."}, + }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { {"delta_lake_clustering_predicate_fallback", false, true, "New setting to enable clustering-aware predicate fallback for Delta Lake tables with Liquid Clustering."}, diff --git a/src/DataTypes/DataTypeAggregateFunction.cpp b/src/DataTypes/DataTypeAggregateFunction.cpp index e2bfc0240759a..4ee433d99833f 100644 --- a/src/DataTypes/DataTypeAggregateFunction.cpp +++ b/src/DataTypes/DataTypeAggregateFunction.cpp @@ -22,7 +22,9 @@ #include #include +#include #include +#include #include #include @@ -534,12 +536,16 @@ combinator. }); } -bool hasAggregateFunctionType(const DataTypePtr & type) +namespace +{ + +template +bool hasTypeMatching(const DataTypePtr & type, Predicate && predicate) { auto result = false; auto check = [&](const IDataType & t) { - result |= WhichDataType(t).isAggregateFunction(); + result |= predicate(t); }; check(*type); @@ -548,3 +554,64 @@ bool hasAggregateFunctionType(const DataTypePtr & type) } } + +bool hasAggregateFunctionType(const DataTypePtr & type) +{ + return hasTypeMatching(type, [](const IDataType & t) { return WhichDataType(t).isAggregateFunction(); }); +} + +bool hasAggregateFunctionOrSimpleAggregateFunctionType(const DataTypePtr & type) +{ + return hasTypeMatching( + type, + [](const IDataType & t) + { + return WhichDataType(t).isAggregateFunction() + || typeid_cast(t.getCustomName()) != nullptr; + }); +} + +String getClickHouseTypeAnnotation(const DataTypePtr & type) +{ + return hasAggregateFunctionOrSimpleAggregateFunctionType(type) ? type->getName() : String{}; +} + +namespace +{ + +/// Checks a parsed type name without resolving aggregate functions through `DataTypeFactory`. +bool astHasAggregateFunctionType(const ASTPtr & ast) +{ + std::string_view name; + if (const auto * data_type = ast->as()) + name = data_type->name; + else if (const auto * identifier = ast->as()) + name = identifier->name(); + + if (name == "AggregateFunction") + return true; + + for (const auto & child : ast->children) + if (astHasAggregateFunctionType(child)) + return true; + + return false; +} + +} + +DataTypePtr resolveClickHouseTypeAnnotation(const String & type_name, bool allow_aggregate_function_states) +{ + const auto ast = DataTypeFactory::parse(type_name); + + /// Checked before `DataTypeFactory` resolves the aggregate function named by the annotation. + if (!allow_aggregate_function_states && astHasAggregateFunctionType(ast)) + return nullptr; + + auto type = DataTypeFactory::instance().get(ast); + /// As in stored table metadata, a state without an explicit version has version 0. + setVersionToAggregateFunctions(type, /*if_empty=*/ true); + return type; +} + +} diff --git a/src/DataTypes/DataTypeAggregateFunction.h b/src/DataTypes/DataTypeAggregateFunction.h index 6774c89ae812b..3e20ed115a615 100644 --- a/src/DataTypes/DataTypeAggregateFunction.h +++ b/src/DataTypes/DataTypeAggregateFunction.h @@ -102,4 +102,16 @@ void pinCurrentStateVersionToAggregateFunctions(DataTypePtr & type); /// Checks type of any nested type is DataTypeAggregateFunction. bool hasAggregateFunctionType(const DataTypePtr & type); +/// Checks type or any nested type is `AggregateFunction` or `SimpleAggregateFunction`. +bool hasAggregateFunctionOrSimpleAggregateFunctionType(const DataTypePtr & type); + +/// The ClickHouse type name recorded for `type` in the metadata of a Parquet file or an Iceberg table, +/// empty if the file or table schema represents the type itself. +String getClickHouseTypeAnnotation(const DataTypePtr & type); + +/// Resolves a ClickHouse type name recorded in the metadata of a Parquet file or an Iceberg table. +/// Returns nullptr, without resolving any aggregate function, if the name has an `AggregateFunction` +/// and `allow_aggregate_function_states` is false. A state without an explicit version has version 0. +DataTypePtr resolveClickHouseTypeAnnotation(const String & type_name, bool allow_aggregate_function_states); + } diff --git a/src/DataTypes/DataTypeFactory.cpp b/src/DataTypes/DataTypeFactory.cpp index e8a9d430fc210..6528037bf1a6f 100644 --- a/src/DataTypes/DataTypeFactory.cpp +++ b/src/DataTypes/DataTypeFactory.cpp @@ -116,24 +116,34 @@ DataTypePtr DataTypeFactory::tryGet(const String & full_name) const return getImpl(full_name); } -template -DataTypePtr DataTypeFactory::getImpl(const String & full_name) const +namespace { - /// Data type parser can be invoked from coroutines with small stack. - /// Value 315 is known to cause stack overflow in some test configurations (debug build, sanitizers) - /// let's make the threshold significantly lower. - /// It is impractical for user to have complex data types with this depth. +/// Data type parser can be invoked from coroutines with small stack. +/// Value 315 is known to cause stack overflow in some test configurations (debug build, sanitizers) +/// let's make the threshold significantly lower. +/// It is impractical for user to have complex data types with this depth. #if defined(SANITIZER) || !defined(NDEBUG) - static constexpr size_t data_type_max_parse_depth = 150; +constexpr size_t data_type_max_parse_depth = 150; #else - static constexpr size_t data_type_max_parse_depth = 300; +constexpr size_t data_type_max_parse_depth = 300; #endif +} + +ASTPtr DataTypeFactory::parse(const String & full_name) +{ ParserDataType parser; + return parseQuery(parser, full_name.data(), full_name.data() + full_name.size(), "data type", false, data_type_max_parse_depth, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); +} + +template +DataTypePtr DataTypeFactory::getImpl(const String & full_name) const +{ ASTPtr ast; if constexpr (nullptr_on_error) { + ParserDataType parser; String out_err; const char * start = full_name.data(); ast = tryParseQuery(parser, start, start + full_name.size(), out_err, false, "data type", false, @@ -143,7 +153,7 @@ DataTypePtr DataTypeFactory::getImpl(const String & full_name) const } else { - ast = parseQuery(parser, full_name.data(), full_name.data() + full_name.size(), "data type", false, data_type_max_parse_depth, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + ast = parse(full_name); } return getImpl(ast); diff --git a/src/DataTypes/DataTypeFactory.h b/src/DataTypes/DataTypeFactory.h index d4a948bf0717a..5fd684976cf30 100644 --- a/src/DataTypes/DataTypeFactory.h +++ b/src/DataTypes/DataTypeFactory.h @@ -34,6 +34,8 @@ class DataTypeFactory final : private boost::noncopyable, public IFactoryWithAli DataTypePtr get(const String & full_name) const; DataTypePtr get(const String & family_name, const ASTPtr & parameters) const; DataTypePtr get(const ASTPtr & ast) const; + /// Parses a type name with the nesting depth limit that `get` applies, without resolving it. + static ASTPtr parse(const String & full_name); DataTypePtr getCustom(DataTypeCustomDescPtr customization) const; DataTypePtr getCustom(const String & base_name, DataTypeCustomDescPtr customization) const; diff --git a/src/DataTypes/tests/gtest_resolve_clickhouse_type_annotation.cpp b/src/DataTypes/tests/gtest_resolve_clickhouse_type_annotation.cpp new file mode 100644 index 0000000000000..a6c0e15ca35d6 --- /dev/null +++ b/src/DataTypes/tests/gtest_resolve_clickhouse_type_annotation.cpp @@ -0,0 +1,29 @@ +#include + +#include +#include + +using namespace DB; + +/// With states disabled, a name with an `AggregateFunction` is not resolved, so its aggregate function is never looked up. +TEST(ResolveClickHouseTypeAnnotation, SkipsOnlyAggregateFunctionStatesWhenDisabled) +{ + tryRegisterAggregateFunctions(); + + for (const auto * name : { + "AggregateFunction(uniq, UInt64)", + "AggregateFunction(0, sumMap, Array(UInt8), Array(UInt32))", + "Array(AggregateFunction(no_such_aggregate_function, UInt64))", + "Map(String, AggregateFunction(uniq, UInt64))", + "Tuple(a UInt64, b Array(AggregateFunction(uniq, UInt64)))"}) + EXPECT_EQ(resolveClickHouseTypeAnnotation(name, /*allow_aggregate_function_states=*/ false), nullptr) << name; + + for (const auto * name : { + "UInt64", + "SimpleAggregateFunction(sum, UInt64)", + "Array(SimpleAggregateFunction(max, String))", + "Tuple(a UInt64, b Array(Nullable(String)))", + "Enum8('AggregateFunction' = 1)", + "Tuple(`AggregateFunction` String)"}) + EXPECT_NE(resolveClickHouseTypeAnnotation(name, /*allow_aggregate_function_states=*/ false), nullptr) << name; +} diff --git a/src/Databases/DataLake/GlueCatalog.cpp b/src/Databases/DataLake/GlueCatalog.cpp index 0a3b4dc16334c..a30fc3fce124f 100644 --- a/src/Databases/DataLake/GlueCatalog.cpp +++ b/src/Databases/DataLake/GlueCatalog.cpp @@ -1341,6 +1341,7 @@ bool GlueCatalog::updateSchema( Int32 /*previous_schema_id*/, Int32 /*new_last_column_id*/, Poco::JSON::Object::Ptr /*metadata*/, + Poco::JSON::Object::Ptr /*previous_properties*/, const DB::ForwardedAuthTokenPtr & auth_token) const { std::vector columns; diff --git a/src/Databases/DataLake/GlueCatalog.h b/src/Databases/DataLake/GlueCatalog.h index 4d07981c257e4..c8889d1c46184 100644 --- a/src/Databases/DataLake/GlueCatalog.h +++ b/src/Databases/DataLake/GlueCatalog.h @@ -103,6 +103,7 @@ class GlueCatalog final : public ICatalog, private DB::WithContext Int32 previous_schema_id, Int32 new_last_column_id, Poco::JSON::Object::Ptr metadata, + Poco::JSON::Object::Ptr previous_properties, const DB::ForwardedAuthTokenPtr & auth_token) const override; void dropTable( diff --git a/src/Databases/DataLake/ICatalog.cpp b/src/Databases/DataLake/ICatalog.cpp index f17fad1f7ef9e..b18d844bada20 100644 --- a/src/Databases/DataLake/ICatalog.cpp +++ b/src/Databases/DataLake/ICatalog.cpp @@ -556,6 +556,7 @@ bool ICatalog::updateSchema( Int32 /*previous_schema_id*/, Int32 /*new_last_column_id*/, Poco::JSON::Object::Ptr /*metadata*/, + Poco::JSON::Object::Ptr /*previous_properties*/, const DB::ForwardedAuthTokenPtr & /*auth_token*/) const { throw DB::Exception(DB::ErrorCodes::NOT_IMPLEMENTED, "updateSchema is not implemented"); diff --git a/src/Databases/DataLake/ICatalog.h b/src/Databases/DataLake/ICatalog.h index dac82db64d9e2..97b76e125adb9 100644 --- a/src/Databases/DataLake/ICatalog.h +++ b/src/Databases/DataLake/ICatalog.h @@ -365,6 +365,7 @@ class ICatalog /// `new_schema` is the full new schema object and `previous_schema_id` is the schema id that the /// catalog is expected to currently have - used to build the optimistic-concurrency requirement /// (`assert-current-schema-id`) on transactional catalogs (e.g. Iceberg REST). + /// `previous_properties` are the table properties before the change. /// Returns `false` on a recoverable conflict so the caller can retry, throws otherwise. virtual bool updateSchema( const String & namespace_name, @@ -374,6 +375,7 @@ class ICatalog Int32 previous_schema_id, Int32 new_last_column_id, Poco::JSON::Object::Ptr metadata, + Poco::JSON::Object::Ptr previous_properties, const DB::ForwardedAuthTokenPtr & auth_token) const; /// Drop table from catalog. diff --git a/src/Databases/DataLake/RestCatalog.cpp b/src/Databases/DataLake/RestCatalog.cpp index 8c7a6d0d1f529..58e4cff0fb8e0 100644 --- a/src/Databases/DataLake/RestCatalog.cpp +++ b/src/Databases/DataLake/RestCatalog.cpp @@ -353,7 +353,8 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody( Poco::JSON::Object::Ptr metadata, Poco::JSON::Object::Ptr new_schema, Int32 previous_schema_id, - Int32 new_last_column_id) + Int32 new_last_column_id, + Poco::JSON::Object::Ptr previous_properties) { Poco::JSON::Object::Ptr request_body = new Poco::JSON::Object; { @@ -381,11 +382,14 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody( schema_for_rest->set(IDENTIFIER_FIELD_IDS, empty_identifier_field_ids); } + const auto new_schema_id = new_schema->getValue(DB::Iceberg::f_schema_id); + /// The change keeps the current schema and touches only the table properties. + const bool schema_unchanged = new_schema_id == previous_schema_id; + std::optional existing_equivalent_schema_id; - if (metadata && metadata->has(DB::Iceberg::f_schemas)) + if (!schema_unchanged && metadata && metadata->has(DB::Iceberg::f_schemas)) { auto schemas = metadata->getArray(DB::Iceberg::f_schemas); - auto new_schema_id = new_schema->getValue(DB::Iceberg::f_schema_id); for (UInt32 i = 0; i < schemas->size(); ++i) { auto existing_schema = schemas->getObject(i); @@ -399,6 +403,36 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody( } } + /// The catalog keeps the id of the equivalent schema, so the ClickHouse type annotations recorded for the new id + /// are not sent and the ones in effect for the equivalent schema must already be the same. + std::unordered_set skipped_properties; + if (existing_equivalent_schema_id.has_value()) + { + const auto fields = DB::Iceberg::IcebergSchemaProcessor::traverseSchema(new_schema->getArray(DB::Iceberg::f_fields)); + const auto existing_annotations = DB::Iceberg::getClickHouseTypeAnnotations(metadata, *existing_equivalent_schema_id); + const auto new_annotations = DB::Iceberg::getClickHouseTypeAnnotations(metadata, new_schema_id); + for (const auto & [name, field_id] : fields) + { + const auto existing_it = existing_annotations.find(static_cast(field_id)); + const auto new_it = new_annotations.find(static_cast(field_id)); + const String existing_annotation = existing_it == existing_annotations.end() ? String{} : existing_it->second.type_name; + const String new_annotation = new_it == new_annotations.end() ? String{} : new_it->second.type_name; + if (existing_annotation != new_annotation) + throw DB::Exception( + DB::ErrorCodes::NOT_IMPLEMENTED, + "Cannot commit schema {} of table {}.{}: the catalog reuses the equivalent schema {} for it, " + "where column '{}' has ClickHouse type annotation '{}' instead of '{}'", + new_schema_id, + namespace_name, + table_name, + *existing_equivalent_schema_id, + name, + existing_annotation, + new_annotation); + skipped_properties.insert(DB::Iceberg::getClickHouseTypePropertyKey(static_cast(field_id), new_schema_id)); + } + } + Poco::JSON::Array::Ptr updates = new Poco::JSON::Array; if (existing_equivalent_schema_id.has_value()) { @@ -407,7 +441,7 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody( set_current_schema->set("schema-id", *existing_equivalent_schema_id); updates->add(set_current_schema); } - else + else if (!schema_unchanged) { { Poco::JSON::Object::Ptr add_schema = new Poco::JSON::Object; @@ -424,6 +458,45 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody( } } + if (previous_properties && metadata) + { + Poco::JSON::Object::Ptr properties + = metadata->has(DB::Iceberg::f_properties) ? metadata->getObject(DB::Iceberg::f_properties) : nullptr; + + Poco::JSON::Object::Ptr changed = new Poco::JSON::Object; + if (properties) + { + for (const auto & [key, value] : *properties) + { + if (skipped_properties.contains(key)) + continue; + if (!previous_properties->has(key) || previous_properties->get(key).toString() != value.toString()) + changed->set(key, value); + } + } + if (changed->size() > 0) + { + Poco::JSON::Object::Ptr set_properties = new Poco::JSON::Object; + set_properties->set("action", "set-properties"); + set_properties->set("updates", changed); + updates->add(set_properties); + } + + Poco::JSON::Array::Ptr removed = new Poco::JSON::Array; + for (const auto & [key, value] : *previous_properties) + { + if (!properties || !properties->has(key)) + removed->add(key); + } + if (removed->size() > 0) + { + Poco::JSON::Object::Ptr remove_properties = new Poco::JSON::Object; + remove_properties->set("action", "remove-properties"); + remove_properties->set("removals", removed); + updates->add(remove_properties); + } + } + request_body->set("updates", updates); return request_body; } @@ -2743,6 +2816,12 @@ bool RestCatalog::createTable( if (metadata_content->has("format-version")) properties->set("format-version", std::to_string(metadata_content->getValue("format-version"))); + if (metadata_content->has(DB::Iceberg::f_properties)) + { + for (const auto & [key, value] : *metadata_content->getObject(DB::Iceberg::f_properties)) + properties->set(key, value); + } + request_body->set("properties", properties); try @@ -2826,6 +2905,7 @@ bool RestCatalog::updateSchema( Int32 previous_schema_id, Int32 new_last_column_id, Poco::JSON::Object::Ptr metadata, + Poco::JSON::Object::Ptr previous_properties, const DB::ForwardedAuthTokenPtr & auth_token) const { fiu_do_on(DB::FailPoints::iceberg_alter_catalog_update_schema_fail, { return false; }); @@ -2836,7 +2916,7 @@ bool RestCatalog::updateSchema( const std::string endpoint = (base_url / state_snapshot->config.prefix / NAMESPACES_ENDPOINT / encodeNamespaceForURI(namespace_name) / "tables" / table_name).generic_string(); auto request_body = buildUpdateSchemaRequestBody( - namespace_name, table_name, metadata, new_schema, previous_schema_id, new_last_column_id); + namespace_name, table_name, metadata, new_schema, previous_schema_id, new_last_column_id, previous_properties); try { diff --git a/src/Databases/DataLake/RestCatalog.h b/src/Databases/DataLake/RestCatalog.h index 1d3bccf5ddf17..23b68cb8d589a 100644 --- a/src/Databases/DataLake/RestCatalog.h +++ b/src/Databases/DataLake/RestCatalog.h @@ -137,6 +137,7 @@ class RestCatalog : public ICatalog, public DB::WithContext Int32 previous_schema_id, Int32 new_last_column_id, Poco::JSON::Object::Ptr metadata, + Poco::JSON::Object::Ptr previous_properties, const DB::ForwardedAuthTokenPtr & auth_token) const override; bool isTransactional() const override { return true; } @@ -608,14 +609,16 @@ class HorizonCatalog : public RestCatalog /// Builds the JSON body for a schema-update commit via the Iceberg REST catalog. /// Includes an assert-current-schema-id requirement (when previous_schema_id >= 0), /// schema deduplication against existing schemas in metadata, and last-column-id -/// propagation when adding a new schema. +/// propagation when adding a new schema, and property changes since `previous_properties`. +/// No schema update is sent when `new_schema` is the schema `previous_schema_id`. Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody( const String & namespace_name, const String & table_name, Poco::JSON::Object::Ptr metadata, Poco::JSON::Object::Ptr new_schema, Int32 previous_schema_id, - Int32 new_last_column_id); + Int32 new_last_column_id, + Poco::JSON::Object::Ptr previous_properties = nullptr); /// Builds the JSON body that commits `new_snapshot` (and sets `properties_to_set` in the same commit) /// via the Iceberg REST catalog. diff --git a/src/Databases/DataLake/UnityV2Catalog.cpp b/src/Databases/DataLake/UnityV2Catalog.cpp index 33facbb7ef837..86a8801aa3dd0 100644 --- a/src/Databases/DataLake/UnityV2Catalog.cpp +++ b/src/Databases/DataLake/UnityV2Catalog.cpp @@ -462,12 +462,14 @@ bool UnityV2Catalog::updateSchema( Int32 previous_schema_id, Int32 new_last_column_id, Poco::JSON::Object::Ptr metadata, + Poco::JSON::Object::Ptr previous_properties, const DB::ForwardedAuthTokenPtr & auth_token) const { return requestWithRetry([&](bool force_refresh) { return getIcebergRestCatalog(force_refresh)->updateSchema( - namespace_name, table_name, new_metadata_path, new_schema, previous_schema_id, new_last_column_id, metadata, auth_token); + namespace_name, table_name, new_metadata_path, new_schema, previous_schema_id, new_last_column_id, metadata, + previous_properties, auth_token); }); } diff --git a/src/Databases/DataLake/UnityV2Catalog.h b/src/Databases/DataLake/UnityV2Catalog.h index 672741699a65c..80d3aa4255baa 100644 --- a/src/Databases/DataLake/UnityV2Catalog.h +++ b/src/Databases/DataLake/UnityV2Catalog.h @@ -107,6 +107,7 @@ class UnityV2Catalog final : public ICatalog, private DB::WithContext Int32 previous_schema_id, Int32 new_last_column_id, Poco::JSON::Object::Ptr metadata, + Poco::JSON::Object::Ptr previous_properties, const DB::ForwardedAuthTokenPtr & auth_token) const override; private: diff --git a/src/Databases/DataLake/tests/gtest_rest_catalog_update_metadata.cpp b/src/Databases/DataLake/tests/gtest_rest_catalog_update_metadata.cpp index 50541508dd6c5..20a2762fcc737 100644 --- a/src/Databases/DataLake/tests/gtest_rest_catalog_update_metadata.cpp +++ b/src/Databases/DataLake/tests/gtest_rest_catalog_update_metadata.cpp @@ -250,6 +250,28 @@ TEST(RestCatalogUpdateSchemaBody, NonEmptyIdentifierFieldIdsPreventDeduplication EXPECT_EQ(set_schema->getValue("schema-id"), -1); } +TEST(RestCatalogUpdateSchemaBody, UnchangedSchemaSendsOnlyThePropertyChanges) +{ + /// A `MODIFY COLUMN` that changes only the ClickHouse type annotation keeps the current schema. + auto schema = makeSingleColumnSchema(0, std::nullopt); + auto metadata = makeMetadataWithSchemas({schema}); + Poco::JSON::Object::Ptr properties = new Poco::JSON::Object; + properties->set("clickhouse.type.1.0", "SimpleAggregateFunction(max, Int32)"); + metadata->set(Iceberg::f_properties, properties); + Poco::JSON::Object::Ptr previous_properties = new Poco::JSON::Object; + previous_properties->set("clickhouse.type.1.0", "SimpleAggregateFunction(sum, Int32)"); + + auto body = DataLake::buildUpdateSchemaRequestBody("ns", "t", metadata, schema, 0, 1, previous_properties); + ASSERT_TRUE(body); + + auto updates = body->getArray("updates"); + ASSERT_EQ(updates->size(), 1u); + auto set_properties = findUpdateByAction(updates, "set-properties"); + ASSERT_TRUE(set_properties); + EXPECT_EQ( + set_properties->getObject("updates")->getValue("clickhouse.type.1.0"), "SimpleAggregateFunction(max, Int32)"); +} + TEST(RestCatalogUpdateSchemaBody, NormalPathEmitsAddSchema) { Poco::JSON::Object::Ptr metadata = new Poco::JSON::Object; diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index c169db9af1df1..58d865603e1aa 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -105,6 +105,34 @@ FormatSettings getFormatSettings(const ContextPtr & context) return getFormatSettings(context, settings); } +std::optional extractTableAllowAggregateFunctionStates(FormatSettings & table_format_settings, const SettingsChanges * table_settings) +{ + std::optional table_allow; + if (table_settings) + { + if (const auto * value = table_settings->tryGet("allow_aggregate_function_states_in_open_formats")) + table_allow = SettingFieldBool(*value).value; + } + table_format_settings.parquet.allow_aggregate_function_states = table_allow.value_or(false); + return table_allow; +} + +bool allowAggregateFunctionStates(std::optional table_allow, const ContextPtr & context) +{ + return table_allow.value_or(context->getSettingsRef()[Setting::allow_aggregate_function_states_in_open_formats]); +} + +std::optional withAllowAggregateFunctionStatesForQuery( + const std::optional & table_format_settings, std::optional table_allow, const ContextPtr & context) +{ + if (!table_format_settings) + return std::nullopt; + + auto result = table_format_settings; + result->parquet.allow_aggregate_function_states = allowAggregateFunctionStates(table_allow, context); + return result; +} + FormatSettings getFormatSettings(const ContextPtr & context, const Settings & settings) { FormatSettings format_settings; @@ -265,6 +293,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se format_settings.parquet.verify_checksums = settings[Setting::input_format_parquet_verify_checksums]; format_settings.parquet.local_time_as_utc = settings[Setting::input_format_parquet_local_time_as_utc]; format_settings.parquet.allow_geoparquet_parser = settings[Setting::input_format_parquet_allow_geoparquet_parser]; + format_settings.parquet.allow_aggregate_function_states = settings[Setting::allow_aggregate_function_states_in_open_formats]; format_settings.parquet.detect_variant_by_structure = settings[Setting::input_format_parquet_detect_variant_by_structure]; format_settings.parquet.write_geometadata = settings[Setting::output_format_parquet_geometadata]; if (auto memory_limit = total_memory_tracker.getHardLimit(); memory_limit > 0) diff --git a/src/Formats/FormatFactory.h b/src/Formats/FormatFactory.h index abd855c159456..bf3510deeec00 100644 --- a/src/Formats/FormatFactory.h +++ b/src/Formats/FormatFactory.h @@ -63,6 +63,16 @@ using BucketSplitter = std::shared_ptr; FormatSettings getFormatSettings(const ContextPtr & context); FormatSettings getFormatSettings(const ContextPtr & context, const Settings & settings); +/// Returns the table's own `allow_aggregate_function_states_in_open_formats` from its `SETTINGS` (`table_settings`), if they give one. +/// `table_format_settings` stores that value, or `false` without one: which value applies then depends on the query. +std::optional extractTableAllowAggregateFunctionStates(FormatSettings & table_format_settings, const SettingsChanges * table_settings); +/// `allow_aggregate_function_states_in_open_formats` for a query on a table: the table's own value (`table_allow`) +/// when its `SETTINGS` give one, and the query's otherwise. +bool allowAggregateFunctionStates(std::optional table_allow, const ContextPtr & context); +/// A table's stored format settings for a query on it. `allow_aggregate_function_states_in_open_formats` is the table's +/// own value (`table_allow`) when its `SETTINGS` give one, and the query's otherwise. +std::optional withAllowAggregateFunctionStatesForQuery( + const std::optional & table_format_settings, std::optional table_allow, const ContextPtr & context); /// For the `Native` blocks of the native protocol. A secondary query carries type names in both directions, /// because a server-side `Connection` never takes format settings. FormatSettings getNativeWireFormatSettings(const ContextPtr & context); diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index 315bf7ab8cf05..fbb0478bb3146 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -430,6 +430,7 @@ struct FormatSettings bool allow_geoparquet_parser = true; bool detect_variant_by_structure = true; bool spatial_filter_push_down = true; + bool allow_aggregate_function_states = false; bool write_geometadata = true; size_t max_dictionary_size = 1024 * 1024; } parquet{}; diff --git a/src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.cpp b/src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.cpp new file mode 100644 index 0000000000000..12443f513c712 --- /dev/null +++ b/src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.cpp @@ -0,0 +1,94 @@ +#include + +#include +#include + +#include +#include +#include + +#include + +namespace DB +{ + +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} + +namespace +{ + +constexpr auto KEY_VERSION = "version"; +constexpr auto KEY_COLUMNS = "columns"; +constexpr Int64 VERSION = 1; + +} + +String serializeClickHouseColumnTypesMetadata(const NamesAndTypesList & columns) +{ + Poco::JSON::Object::Ptr column_types = new Poco::JSON::Object; + for (const auto & [column_name, type] : columns) + { + if (auto annotation = getClickHouseTypeAnnotation(type); !annotation.empty()) + column_types->set(column_name, annotation); + } + + if (column_types->size() == 0) + return {}; + + Poco::JSON::Object::Ptr metadata = new Poco::JSON::Object; + metadata->set(KEY_VERSION, VERSION); + metadata->set(KEY_COLUMNS, column_types); + + std::ostringstream // STYLE_CHECK_ALLOW_STD_STRING_STREAM + oss; + Poco::JSON::Stringifier::stringify(metadata, oss); + return oss.str(); +} + +std::unordered_map parseClickHouseColumnTypesMetadata(const String & value) +{ + std::unordered_map result; + try + { + Poco::JSON::Parser parser; + const auto object = parser.parse(value).extract(); + const auto version = object->getValue(KEY_VERSION); + if (version != VERSION) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Unsupported version {} of the `{}` key-value metadata of the file, supported version is {}", + version, + clickhouse_column_types_key, + VERSION); + + const auto columns = object->getObject(KEY_COLUMNS); + if (!columns) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "The `{}` key-value metadata of the file has no `{}` object", + clickhouse_column_types_key, + KEY_COLUMNS); + + for (const auto & name : columns->getNames()) + result[name] = columns->getValue(name); + } + catch (Exception & e) + { + e.addMessage("while parsing the `{}` key-value metadata of the file", clickhouse_column_types_key); + throw; + } + catch (const Poco::Exception & e) + { + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Cannot parse the `{}` key-value metadata of the file: {}", + clickhouse_column_types_key, + e.displayText()); + } + return result; +} + +} diff --git a/src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.h b/src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.h new file mode 100644 index 0000000000000..54f6c1e009052 --- /dev/null +++ b/src/Processors/Formats/Impl/ClickHouseColumnTypesMetadata.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +#include + +namespace DB +{ + +/// Key of the file-level key-value metadata that records ClickHouse types the file schema cannot represent, +/// as JSON `{"version": 1, "columns": {"": "", ...}}`. +constexpr const char * clickhouse_column_types_key = "clickhouse.column_types"; + +/// The value of the `clickhouse_column_types_key` metadata for `columns`, empty if none of them needs it. +String serializeClickHouseColumnTypesMetadata(const NamesAndTypesList & columns); + +/// Column names and type names recorded in a `clickhouse_column_types_key` metadata value. +std::unordered_map parseClickHouseColumnTypesMetadata(const String & value); + +} diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.cpp b/src/Processors/Formats/Impl/Parquet/Decoding.cpp index 47b19e67c323f..4098a6b14c762 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.cpp +++ b/src/Processors/Formats/Impl/Parquet/Decoding.cpp @@ -1,10 +1,14 @@ #include #include +#include #include +#include +#include #include #include #include +#include #include #include @@ -2119,6 +2123,32 @@ void Int96Converter::convertColumn(std::span data, size_t num_values } } +void AggregateFunctionStateConverter::convertColumn(std::span chars, const UInt64 * offsets, size_t separator_bytes, size_t num_values, IColumn & col) const +{ + auto & column = assert_cast(col); + + /// Plain pages may follow a dictionary page whose states are shared through `src`. + column.ensureOwnership(); + + chassert(chars.size() >= offsets[num_values - 1]); + const FormatSettings format_settings; + for (ssize_t i = 0; i < ssize_t(num_values); ++i) + { + const char * ptr = chars.data() + offsets[i - 1]; + const size_t length = offsets[i] - offsets[i - 1] - separator_bytes; + ReadBufferFromMemory in(ptr, length); + serialization->deserializeBinary(column, in, format_settings); + if (!in.eof()) + { + column.popBack(1); + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Aggregate function state has {} trailing byte(s) after deserialization", + in.available()); + } + } +} + void GeoConverter::convertColumn(std::span chars, const UInt64 * offsets, size_t separator_bytes, size_t num_values, IColumn & col) const { col.reserve(col.size() + num_values); diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.h b/src/Processors/Formats/Impl/Parquet/Decoding.h index fb07191c0beca..633c59cfcb208 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.h +++ b/src/Processors/Formats/Impl/Parquet/Decoding.h @@ -4,6 +4,11 @@ #include #include +namespace DB +{ +class ISerialization; +} + namespace DB::ErrorCodes { extern const int INCORRECT_DATA; @@ -433,6 +438,16 @@ struct GeoConverter : public StringConverter void convertColumn(std::span chars, const UInt64 * offsets, size_t separator_bytes, size_t num_values, IColumn & col) const override; }; +struct AggregateFunctionStateConverter : public StringConverter +{ + std::shared_ptr serialization; + + explicit AggregateFunctionStateConverter(std::shared_ptr serialization_) + : serialization(std::move(serialization_)) {} + + void convertColumn(std::span chars, const UInt64 * offsets, size_t separator_bytes, size_t num_values, IColumn & col) const override; +}; + void decodeRepOrDefLevels(parq::Encoding::type encoding, UInt8 max, size_t num_values, std::span data, PaddedPODArray & out); diff --git a/src/Processors/Formats/Impl/Parquet/PrepareForWrite.cpp b/src/Processors/Formats/Impl/Parquet/PrepareForWrite.cpp index ad23da3dc50d6..ff5f4427e8dde 100644 --- a/src/Processors/Formats/Impl/Parquet/PrepareForWrite.cpp +++ b/src/Processors/Formats/Impl/Parquet/PrepareForWrite.cpp @@ -27,6 +27,9 @@ #include #include #include +#include +#include +#include /// This file deals with schema conversion and with repetition and definition levels. @@ -66,6 +69,7 @@ namespace DB::ErrorCodes extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; extern const int INCORRECT_DATA; + extern const int SUPPORT_IS_DISABLED; } namespace DB::Parquet @@ -908,6 +912,28 @@ void validateIcebergFieldIds( } } +void convertAggregateFunctionColumnToString(ColumnPtr & column, DataTypePtr & type) +{ + auto serialization = type->getDefaultSerialization(); + auto result = ColumnString::create(); + auto & chars = result->getChars(); + auto & offsets = result->getOffsets(); + offsets.reserve(column->size()); + { + WriteBufferFromVector buffer(chars); + const FormatSettings format_settings; + for (size_t i = 0; i < column->size(); ++i) + { + serialization->serializeBinary(*column, i, buffer, format_settings); + offsets.push_back(buffer.count()); + } + buffer.finalize(); + } + + column = std::move(result); + type = std::make_shared(); +} + void prepareColumnRecursive( ColumnPtr column, DataTypePtr type, const std::string & name, const WriteOptions & options, ColumnChunkWriteStates & states, SchemaElements & schemas, const std::optional> & column_field_ids, @@ -934,6 +960,25 @@ void prepareColumnRecursive( preparePrimitiveColumn(column, nested_type, name, options, states, schemas, lookupLeafFieldId(column_field_ids, name)); break; } + case TypeIndex::AggregateFunction: + { + if (!options.allow_aggregate_function_states) + throw Exception( + ErrorCodes::SUPPORT_IS_DISABLED, + "Writing aggregate function states of column '{}' into Parquet data format is disabled. " + "Enable setting allow_aggregate_function_states_in_open_formats to write the " + "serialized states", + name); + + convertAggregateFunctionColumnToString(column, type); + /// Serialized states are binary even when Parquet strings use the UTF8 logical type. + WriteOptions binary_options = options; + binary_options.output_string_as_string = false; + preparePrimitiveColumn( + column, type, name, binary_options, states, schemas, lookupLeafFieldId(column_field_ids, name)); + states.back().write_statistics = false; + break; + } default: preparePrimitiveColumn(column, type, name, options, states, schemas, lookupLeafFieldId(column_field_ids, name)); break; @@ -1088,4 +1133,122 @@ void prepareColumnForWrite( states.clear(); } + +namespace +{ + +bool isFixedStringOfSize(const DataTypePtr & type, size_t size) +{ + const auto * fixed_string = typeid_cast(type.get()); + return fixed_string && fixed_string->getN() == size; +} + +bool isDateTime64WithScale(const DataTypePtr & type, UInt32 scale) +{ + const auto * date_time64 = typeid_cast(type.get()); + return date_time64 && date_time64->getScale() == scale; +} + +/// Mirrors the non-injective mappings in `preparePrimitiveColumn`. +bool parquetWriterCouldProduce(const DataTypePtr & annotated, const DataTypePtr & derived) +{ + if (annotated->equals(*derived)) + return true; + + auto next_timestamp_unit = [](UInt32 scale) -> UInt32 + { + if (scale <= 3) + return 3; + if (scale <= 6) + return 6; + return 9; + }; + + switch (annotated->getTypeId()) + { + case TypeIndex::Date: + return WhichDataType(derived).isDate32() || WhichDataType(derived).isUInt16(); + case TypeIndex::DateTime: + return isDateTime64WithScale(derived, 3) || WhichDataType(derived).isUInt32(); + case TypeIndex::DateTime64: + return isDateTime64WithScale( + derived, next_timestamp_unit(assert_cast(*annotated).getScale())); + case TypeIndex::Time: + return isDateTime64WithScale(derived, 6); + case TypeIndex::Time64: + return isDateTime64WithScale( + derived, assert_cast(*annotated).getScale() <= 6 ? 6 : 9); + case TypeIndex::Enum8: + return isString(derived) || WhichDataType(derived).isInt8(); + case TypeIndex::Enum16: + return isString(derived) || WhichDataType(derived).isInt16(); + case TypeIndex::IPv4: + return WhichDataType(derived).isUInt32(); + case TypeIndex::IPv6: + return isFixedStringOfSize(derived, 16); + case TypeIndex::UInt128: + case TypeIndex::Int128: + { + /// With `output_format_parquet_wide_integer_as_decimal` it is written as `DECIMAL(39, 0)`. + const auto * decimal = checkDecimal(*derived); + return isFixedStringOfSize(derived, 16) + || (decimal && decimal->getPrecision() == 39 && decimal->getScale() == 0); + } + case TypeIndex::UInt256: + case TypeIndex::Int256: + return isFixedStringOfSize(derived, 32); + case TypeIndex::FixedString: + return isString(derived); + case TypeIndex::Object: + return isString(derived); + default: + return false; + } +} + +} + +bool annotatedTypeMatchesDerived(const DataTypePtr & annotated_type, const DataTypePtr & derived_type) +{ + auto annotated = removeLowCardinalityAndNullable(annotated_type); + auto derived = removeLowCardinalityAndNullable(derived_type); + + if (annotated->getTypeId() == TypeIndex::AggregateFunction) + return isString(derived); + + switch (annotated->getTypeId()) + { + case TypeIndex::Array: + { + const auto * derived_array = typeid_cast(derived.get()); + if (!derived_array) + return false; + return annotatedTypeMatchesDerived( + assert_cast(*annotated).getNestedType(), derived_array->getNestedType()); + } + case TypeIndex::Tuple: + { + const auto & annotated_tuple = assert_cast(*annotated); + const auto * derived_tuple = typeid_cast(derived.get()); + if (!derived_tuple || derived_tuple->getElements().size() != annotated_tuple.getElements().size()) + return false; + for (size_t i = 0; i < annotated_tuple.getElements().size(); ++i) + if (!annotatedTypeMatchesDerived(annotated_tuple.getElement(i), derived_tuple->getElement(i))) + return false; + return true; + } + case TypeIndex::Map: + { + const auto & annotated_map = assert_cast(*annotated); + const auto * derived_map = typeid_cast(derived.get()); + if (!derived_map) + return false; + return annotatedTypeMatchesDerived(annotated_map.getKeyType(), derived_map->getKeyType()) + && annotatedTypeMatchesDerived(annotated_map.getValueType(), derived_map->getValueType()); + } + default: + return parquetWriterCouldProduce(annotated, derived); + } +} + } diff --git a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp index 03b22e80c06d4..14c2bbad839aa 100644 --- a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp +++ b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp @@ -20,6 +20,9 @@ #include #include #include +#include +#include +#include #include #include @@ -58,6 +61,19 @@ SchemaConverter::SchemaConverter( } } } + + /// An explicit structure takes precedence over type annotations in the footer. + if (!sample_block) + { + for (const auto & kv : file_metadata.key_value_metadata) + { + if (kv.key == clickhouse_column_types_key) + { + annotated_column_type_names = parseClickHouseColumnTypesMetadata(kv.value); + break; + } + } + } } void SchemaConverter::checkHasColumns() @@ -128,6 +144,36 @@ void SchemaConverter::prepareForReading() } +DataTypePtr SchemaConverter::resolveAnnotatedType(const String & column_name, const String & type_name, const DataTypePtr & derived_type) const +{ + DataTypePtr annotated_type; + try + { + annotated_type = resolveClickHouseTypeAnnotation(type_name, options.format.parquet.allow_aggregate_function_states); + } + catch (Exception & e) + { + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Parquet file records ClickHouse type {} for column {} in its `{}` metadata, which this " + "server cannot resolve: {}", + type_name, column_name, clickhouse_column_types_key, e.message()); + } + + /// With aggregate function states disabled, a recorded type that has one is ignored. + if (!annotated_type) + return derived_type; + + if (!annotatedTypeMatchesDerived(annotated_type, derived_type)) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Parquet file records ClickHouse type {} for column {} in its `{}` metadata, but the " + "parquet schema for that column reads as {}", + annotated_type->getName(), column_name, clickhouse_column_types_key, derived_type->getName()); + + return annotated_type; +} + NamesAndTypesList SchemaConverter::inferSchema() { chassert(!sample_block); @@ -142,7 +188,27 @@ NamesAndTypesList SchemaConverter::inferSchema() if (node.output_idx.has_value()) { const OutputColumnInfo & col = output_columns.at(node.output_idx.value()); - res.emplace_back(col.name, col.output_type); + auto it = annotated_column_type_names.find(col.name); + if (it == annotated_column_type_names.end()) + { + res.emplace_back(col.name, col.output_type); + continue; + } + + DataTypePtr annotated_type; + try + { + annotated_type = resolveAnnotatedType(col.name, it->second, col.output_type); + } + catch (Exception & e) + { + if (options.format.parquet.skip_columns_with_unsupported_types_in_schema_inference + && (e.code() == ErrorCodes::INCORRECT_DATA || e.code() == ErrorCodes::NOT_IMPLEMENTED)) + continue; + throw; + } + + res.emplace_back(col.name, annotated_type); } } return res; @@ -445,11 +511,11 @@ bool SchemaConverter::processSubtreePrimitive(TraversalNode & node) } } - /// GeoParquet types like Point or Polygon can't be inside Nullable. - /// Geometry (Variant) is also not Nullable-compatible. + /// These types cannot be nested in `Nullable`. if (typeid_cast(inferred_type.get()) || typeid_cast(inferred_type.get()) - || typeid_cast(inferred_type.get())) + || typeid_cast(inferred_type.get()) + || typeid_cast(inferred_type.get())) { output_nullable = false; output_nullable_if_not_json = false; @@ -1209,6 +1275,20 @@ void SchemaConverter::processPrimitiveColumn( } } + if (typeid_cast(type_hint.get())) + { + if (type != parq::Type::BYTE_ARRAY) + throw Exception( + ErrorCodes::TYPE_MISMATCH, + "Column is requested as {} but its parquet physical type is {}, not BYTE_ARRAY", + type_hint->getName(), thriftToString(type)); + + out_inferred_type = type_hint; + out_decoder.allow_stats = false; + out_decoder.string_converter = std::make_shared(type_hint->getDefaultSerialization()); + return; + } + /// GeoParquet. /// Spec says "Geometry columns MUST be at the root of the schema", but we allow them to be /// nested in tuples etc, why not. (Though nesting in arrays/maps probably currently wouldn't diff --git a/src/Processors/Formats/Impl/Parquet/SchemaConverter.h b/src/Processors/Formats/Impl/Parquet/SchemaConverter.h index f2e382dccc5dc..fe5819161d071 100644 --- a/src/Processors/Formats/Impl/Parquet/SchemaConverter.h +++ b/src/Processors/Formats/Impl/Parquet/SchemaConverter.h @@ -44,6 +44,9 @@ struct SchemaConverter /// The key is the parquet column name, without ColumnMapper. std::unordered_map geo_columns; + /// Type names from the `clickhouse.column_types` footer metadata. + std::unordered_map annotated_column_type_names; + /// If precomputed_geo_columns has a value it is used directly (including the empty-map case) /// and the constructor skips parsing the "geo" key-value metadata. This ensures that a /// failed parse caught by the caller (which leaves an empty map) does not cause @@ -134,6 +137,8 @@ struct SchemaConverter void checkHasColumns(); + DataTypePtr resolveAnnotatedType(const String & column_name, const String & type_name, const DataTypePtr & derived_type) const; + void processSubtree(TraversalNode & node); /// These functions are used by processSubtree for different kinds of SchemaElement. diff --git a/src/Processors/Formats/Impl/Parquet/Write.cpp b/src/Processors/Formats/Impl/Parquet/Write.cpp index 9b93f7599fb33..864754f2c34ce 100644 --- a/src/Processors/Formats/Impl/Parquet/Write.cpp +++ b/src/Processors/Formats/Impl/Parquet/Write.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #if USE_SNAPPY #include @@ -1301,8 +1302,17 @@ void writeColumnImpl( } void writeColumnChunkBody( - ColumnChunkWriteState & s, const WriteOptions & options, const FormatSettings & format_settings, WriteBuffer & out) + ColumnChunkWriteState & s, const WriteOptions & file_options, const FormatSettings & format_settings, WriteBuffer & out) { + /// Without page statistics the column index is not written either. + WriteOptions options = file_options; + if (!s.write_statistics) + { + options.write_column_chunk_statistics = false; + options.write_page_statistics = false; + options.write_bloom_filter = false; + } + s.column_chunk.meta_data.__set_num_values(s.max_def > 0 ? s.def.size() : s.primitive_column->size()); /// We'll be updating these as we go. @@ -1693,6 +1703,16 @@ void writeFileFooter(FileWriteState & file, } } + if (auto column_types = serializeClickHouseColumnTypesMetadata(header.getNamesAndTypesList()); !column_types.empty()) + { + parquet::format::KeyValue key_value; + key_value.__set_key(clickhouse_column_types_key); + key_value.__set_value(std::move(column_types)); + + meta.key_value_metadata.push_back(std::move(key_value)); + meta.__isset.key_value_metadata = true; + } + size_t footer_size = serializeThriftStruct(meta, out); if (footer_size > INT32_MAX) diff --git a/src/Processors/Formats/Impl/Parquet/Write.h b/src/Processors/Formats/Impl/Parquet/Write.h index 0eef9bc59d482..8e36e63f6863f 100644 --- a/src/Processors/Formats/Impl/Parquet/Write.h +++ b/src/Processors/Formats/Impl/Parquet/Write.h @@ -28,6 +28,7 @@ struct WriteOptions bool output_date_as_uint16 = false; bool output_enum_as_byte_array = false; bool output_timestamp_adjusted_to_utc_from_timezone = false; + bool allow_aggregate_function_states = false; /// Note: the meaning of some compression methods here is different from /// wrapReadBufferWithCompressionMethod: @@ -114,6 +115,8 @@ struct ColumnChunkWriteState int compression_level = 3; Int64 datetime_multiplier = 1; // for converting e.g. seconds to milliseconds bool is_bool = false; // bool vs UInt8 have the same column type but are encoded differently + /// False for aggregate function states: disables statistics and bloom filter. + bool write_statistics = true; /// Repetition and definition levels. Produced by prepareColumnForWrite(). /// def is empty iff max_def == 0, which means no arrays or nullables. @@ -188,6 +191,10 @@ using ColumnChunkWriteStates = std::vector; /// groupings of those columns, e.g. tuples or structs. SchemaElements convertSchema(const Block & sample, const WriteOptions & options, const std::optional> & column_field_ids, const IcebergOptionality & iceberg_optionality = {}); +/// Whether `annotated`, a ClickHouse type recorded in the file metadata, may describe a column whose Parquet schema +/// reads as `derived`, given the type mappings of `preparePrimitiveColumn`. +bool annotatedTypeMatchesDerived(const DataTypePtr & annotated, const DataTypePtr & derived); + /// `iceberg_optionality` must be passed identically on the schema and the data path: the reader /// derives its max definition level from the schema while the writer derives the level bit width /// from the state produced here, so a schema-only change would desynchronize them. diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_annotated_type_matches_derived.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_annotated_type_matches_derived.cpp new file mode 100644 index 0000000000000..ecd19aa48c542 --- /dev/null +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_annotated_type_matches_derived.cpp @@ -0,0 +1,70 @@ +#include + +#include +#include +#include + +using namespace DB; +using namespace DB::Parquet; + +namespace +{ + +DataTypePtr typeFromString(const String & name) +{ + tryRegisterAggregateFunctions(); + return DataTypeFactory::instance().get(name); +} + +bool matches(const String & annotated, const String & derived) +{ + return annotatedTypeMatchesDerived(typeFromString(annotated), typeFromString(derived)); +} + +} + +TEST(AnnotatedTypeMatchesDerived, AcceptsWhatTheParquetWriterProduces) +{ + EXPECT_TRUE(matches("Map(String, AggregateFunction(uniq, UInt64))", "Map(String, String)")); + EXPECT_TRUE(matches( + "SimpleAggregateFunction(anyLast, LowCardinality(Nullable(String)))", "Nullable(String)")); + + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, Date)", "UInt16")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, DateTime)", "UInt32")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, DateTime64(9))", "DateTime64(9, 'UTC')")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, DateTime64(0))", "DateTime64(3, 'UTC')")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, DateTime64(7))", "DateTime64(9, 'UTC')")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, Time)", "DateTime64(6, 'UTC')")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, Time64(3))", "DateTime64(6, 'UTC')")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, Time64(9))", "DateTime64(9, 'UTC')")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, Enum8('a' = 1))", "Int8")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, Enum16('a' = 1))", "String")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, Enum16('a' = 1))", "Int16")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, UInt256)", "FixedString(32)")); + EXPECT_TRUE(matches("SimpleAggregateFunction(anyLast, FixedString(16))", "String")); +} + +TEST(AnnotatedTypeMatchesDerived, RefusesAnAnnotationThatRetypesTheColumn) +{ + EXPECT_FALSE(matches("AggregateFunction(uniq, UInt64)", "Int64")); + EXPECT_FALSE(matches("AggregateFunction(uniq, UInt64)", "FixedString(16)")); + EXPECT_FALSE(matches("AggregateFunction(uniq, UInt64)", "Array(String)")); + + EXPECT_FALSE(matches("Array(AggregateFunction(uniq, UInt64))", "String")); + EXPECT_FALSE(matches("Array(AggregateFunction(uniq, UInt64))", "Array(Int64)")); + EXPECT_FALSE(matches("Map(String, AggregateFunction(uniq, UInt64))", "Map(String, Int64)")); + EXPECT_FALSE(matches("Map(String, AggregateFunction(uniq, UInt64))", "Array(Tuple(String, String))")); + EXPECT_FALSE(matches("Tuple(a AggregateFunction(uniq, UInt64), b UInt64)", "String")); + EXPECT_FALSE(matches("Tuple(a AggregateFunction(uniq, UInt64), b UInt64)", "Tuple(a String)")); + EXPECT_FALSE(matches("Tuple(a AggregateFunction(uniq, UInt64), b UInt64)", "Tuple(a Int64, b String)")); + + EXPECT_FALSE(matches("SimpleAggregateFunction(sum, UInt64)", "Int64")); + EXPECT_FALSE(matches("Array(SimpleAggregateFunction(sum, UInt64))", "Array(Int64)")); + EXPECT_FALSE(matches("SimpleAggregateFunction(anyLast, Date)", "Int32")); + EXPECT_FALSE(matches("SimpleAggregateFunction(anyLast, IPv4)", "Int32")); + EXPECT_FALSE(matches("SimpleAggregateFunction(anyLast, Float64)", "Int64")); + EXPECT_FALSE(matches("SimpleAggregateFunction(anyLast, String)", "FixedString(16)")); + EXPECT_FALSE(matches("SimpleAggregateFunction(anyLast, Decimal(18, 4))", "Decimal(18, 2)")); + EXPECT_FALSE(matches("SimpleAggregateFunction(anyLast, DateTime64(4))", "DateTime64(3)")); + EXPECT_FALSE(matches("SimpleAggregateFunction(anyLast, DateTime64(4))", "DateTime64(9)")); +} diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp index 485a5dc179662..afa89d1b78c5d 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp @@ -51,6 +51,7 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea options.output_date_as_uint16 = format_settings.parquet.output_date_as_uint16; options.output_enum_as_byte_array = format_settings.parquet.output_enum_as_byte_array; options.output_timestamp_adjusted_to_utc_from_timezone = format_settings.parquet.output_timestamp_adjusted_to_utc_from_timezone; + options.allow_aggregate_function_states = format_settings.parquet.allow_aggregate_function_states; options.data_page_size = format_settings.parquet.data_page_size; options.write_batch_size = format_settings.parquet.write_batch_size; options.write_page_index = format_settings.parquet.write_page_index; diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp index 9aecc0ffcd696..3d3b010d6bf2c 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -593,6 +593,37 @@ On write, top-level columns of type `Point`, `MultiPoint`, `LineString`, `Polygo Geometry columns must appear at the root of the schema or nested inside `Tuple` (`struct`); nesting them inside `Array` or `Map` is not supported. `Nullable` is not supported for geo columns either. +## Aggregate function states {#aggregate-function-states} + +Parquet has no aggregate-state type. ClickHouse writes an [`AggregateFunction`](/reference/data-types/aggregatefunction) column as `BYTE_ARRAY` without a logical type, holding the serialized state (the bytes the `-State` combinator produces). A [`SimpleAggregateFunction(f, T)`](/reference/data-types/simpleaggregatefunction) column is written as a plain value of type `T`. + +To restore both types on read, ClickHouse records them in the file-level key-value metadata under `clickhouse.column_types`, as JSON `{"version": 1, "columns": {"": ""}}`. A recorded state type without an explicit version reads as version 0. Other query engines ignore the key. + +```sql +SET allow_aggregate_function_states_in_open_formats = 1; + +INSERT INTO FUNCTION file('states.parquet') +SELECT k, uniqState(v) AS u, sumSimpleState(v) AS s FROM source GROUP BY k; + +DESCRIBE file('states.parquet'); +-- k UInt64 +-- u AggregateFunction(uniq, UInt64) +-- s SimpleAggregateFunction(sum, UInt64) + +SELECT k, uniqMerge(u), sum(s) FROM file('states.parquet') GROUP BY k; +``` + +States are controlled by [`allow_aggregate_function_states_in_open_formats`](/reference/settings/formats/other#allow_aggregate_function_states_in_open_formats), disabled by default. The recorded type chooses the deserializer for the stored bytes, so enable the setting only for files from trusted sources. When it is disabled, writing a state throws `SUPPORT_IS_DISABLED`, and a state column reads as `String`. `SimpleAggregateFunction` is not affected: its type is always recorded on write and restored by schema inference, so a file written with it describes the column as `SimpleAggregateFunction(f, T)`, not `T`. Files without the `clickhouse.column_types` key read as before. A table, such as one with the `File`, `URL` or `S3` engine, can set it in its `SETTINGS` clause, and that value then applies to every query on the table. + +An explicit structure overrides the recorded types, whatever the setting: + +```sql +SELECT uniqMerge(CAST(u AS AggregateFunction(uniq, UInt64))) +FROM file('states.parquet', Parquet, 'u String'); +``` + +Reading fails if a recorded type does not match the column's Parquet type. State columns are written without statistics, column index or bloom filter. + ## Example usage {#example-usage} ### Inserting data {#inserting-data} @@ -698,13 +729,15 @@ void registerParquetSchemaReader(FormatFactory & factory) return fmt::format( "schema_inference_make_columns_nullable={};schema_inference_make_json_columns_nullable={};" "enable_json_parsing={};max_parser_depth={};" - "local_time_as_utc={};allow_geoparquet_parser={};skip_columns_with_unsupported_types={}", + "local_time_as_utc={};allow_geoparquet_parser={};allow_aggregate_function_states={};" + "skip_columns_with_unsupported_types={}", settings.schema_inference_make_columns_nullable, settings.schema_inference_make_json_columns_nullable, settings.parquet.enable_json_parsing, settings.max_parser_depth, settings.parquet.local_time_as_utc, settings.parquet.allow_geoparquet_parser, + settings.parquet.allow_aggregate_function_states, settings.parquet.skip_columns_with_unsupported_types_in_schema_inference); }); } diff --git a/src/Storages/ExportReplicatedMergeTreePartitionManifest.h b/src/Storages/ExportReplicatedMergeTreePartitionManifest.h index c77c78895c331..2a784353fd49e 100644 --- a/src/Storages/ExportReplicatedMergeTreePartitionManifest.h +++ b/src/Storages/ExportReplicatedMergeTreePartitionManifest.h @@ -174,6 +174,7 @@ struct ExportReplicatedMergeTreePartitionManifest String filename_pattern; bool write_full_path_in_iceberg_metadata = false; bool allow_lossy_cast = false; + std::optional allow_aggregate_function_states_in_open_formats; String iceberg_metadata_json; /// Optional because of backwards compatibility @@ -223,6 +224,8 @@ struct ExportReplicatedMergeTreePartitionManifest json.set("task_timeout_seconds", task_timeout_seconds); json.set("write_full_path_in_iceberg_metadata", write_full_path_in_iceberg_metadata); json.set("allow_lossy_cast", allow_lossy_cast); + if (allow_aggregate_function_states_in_open_formats) + json.set("allow_aggregate_function_states_in_open_formats", *allow_aggregate_function_states_in_open_formats); if (parquet_compression_method) json.set("parquet_compression_method", *parquet_compression_method); if (output_format_compression_level) @@ -306,6 +309,11 @@ struct ExportReplicatedMergeTreePartitionManifest /// on upgrade. New tasks always persist the initiator's actual choice. manifest.allow_lossy_cast = json->has("allow_lossy_cast") ? json->getValue("allow_lossy_cast") : true; + if (json->has("allow_aggregate_function_states_in_open_formats")) + { + manifest.allow_aggregate_function_states_in_open_formats = json->getValue("allow_aggregate_function_states_in_open_formats"); + } + /// Left unset (nullopt) for tasks created before these fields existed - such tasks were /// always scheduled under the old, strict column-matching check (a mismatch could never /// reach scheduling in the first place), so callers should treat an absent value as diff --git a/src/Storages/MergeTree/ExportPartitionTaskScheduler.cpp b/src/Storages/MergeTree/ExportPartitionTaskScheduler.cpp index f491c565fad14..d92ce6f2de64c 100644 --- a/src/Storages/MergeTree/ExportPartitionTaskScheduler.cpp +++ b/src/Storages/MergeTree/ExportPartitionTaskScheduler.cpp @@ -110,12 +110,16 @@ std::optional ExportPartitionTaskScheduler::run() const auto & manifest = entry.manifest; const auto key = entry.getCompositeKey(); - const auto database = storage.getContext()->resolveDatabase(manifest.destination_database); + + /// Catalog destinations must be resolved with the settings persisted by the initiating query. + const auto destination_resolution_context = ExportPartitionUtils::getContextCopyWithTaskSettings(storage.getContext(), manifest); + + const auto database = destination_resolution_context->resolveDatabase(manifest.destination_database); const auto & table = manifest.destination_table; const auto destination_storage_id = StorageID(QualifiedTableName {database, table}); - const auto destination_storage = DatabaseCatalog::instance().tryGetTable(destination_storage_id, storage.getContext()); + const auto destination_storage = DatabaseCatalog::instance().tryGetTable(destination_storage_id, destination_resolution_context); if (!destination_storage) { diff --git a/src/Storages/MergeTree/ExportPartitionUtils.cpp b/src/Storages/MergeTree/ExportPartitionUtils.cpp index 511f02efd67a6..6e30479ccf7be 100644 --- a/src/Storages/MergeTree/ExportPartitionUtils.cpp +++ b/src/Storages/MergeTree/ExportPartitionUtils.cpp @@ -310,6 +310,10 @@ namespace ExportPartitionUtils /// schema drifts to a lossy target between scheduling and execution. context_copy->setSetting("export_merge_tree_part_allow_lossy_cast", manifest.allow_lossy_cast); + if (manifest.allow_aggregate_function_states_in_open_formats) + context_copy->setSetting( + "allow_aggregate_function_states_in_open_formats", *manifest.allow_aggregate_function_states_in_open_formats); + if (manifest.iceberg_partition_timezone) { context_copy->setSetting("iceberg_partition_timezone", *manifest.iceberg_partition_timezone); diff --git a/src/Storages/MergeTree/MergeTreePartitionExportTask.h b/src/Storages/MergeTree/MergeTreePartitionExportTask.h index ace342253881a..87f02f3a5f4d6 100644 --- a/src/Storages/MergeTree/MergeTreePartitionExportTask.h +++ b/src/Storages/MergeTree/MergeTreePartitionExportTask.h @@ -82,6 +82,7 @@ struct MergeTreePartitionExportTask String filename_pattern; bool write_full_path_in_iceberg_metadata = false; bool allow_lossy_cast = false; + std::optional allow_aggregate_function_states_in_open_formats; String iceberg_metadata_json; /// Optional for backwards compatibility with descriptors written before these @@ -190,6 +191,8 @@ struct MergeTreePartitionExportTask json.set("filename_pattern", filename_pattern); json.set("write_full_path_in_iceberg_metadata", write_full_path_in_iceberg_metadata); json.set("allow_lossy_cast", allow_lossy_cast); + if (allow_aggregate_function_states_in_open_formats) + json.set("allow_aggregate_function_states_in_open_formats", *allow_aggregate_function_states_in_open_formats); if (!iceberg_metadata_json.empty()) json.set("iceberg_metadata_json", iceberg_metadata_json); if (parquet_compression_method) @@ -284,6 +287,8 @@ struct MergeTreePartitionExportTask task.filename_pattern = json->getValue("filename_pattern"); task.write_full_path_in_iceberg_metadata = json->getValue("write_full_path_in_iceberg_metadata"); task.allow_lossy_cast = json->getValue("allow_lossy_cast"); + if (json->has("allow_aggregate_function_states_in_open_formats")) + task.allow_aggregate_function_states_in_open_formats = json->getValue("allow_aggregate_function_states_in_open_formats"); if (json->has("iceberg_metadata_json")) task.iceberg_metadata_json = json->getValue("iceberg_metadata_json"); if (json->has("parquet_compression_method")) diff --git a/src/Storages/MergeTree/tests/gtest_export_partition_ordering.cpp b/src/Storages/MergeTree/tests/gtest_export_partition_ordering.cpp index e77ab1c3a639e..5557ca975d819 100644 --- a/src/Storages/MergeTree/tests/gtest_export_partition_ordering.cpp +++ b/src/Storages/MergeTree/tests/gtest_export_partition_ordering.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -16,6 +17,7 @@ namespace Setting { extern const SettingsMergeTreePartExportSchemaMatchMode export_merge_tree_part_schema_match_mode; extern const SettingsBool export_merge_tree_part_ignore_extra_source_columns; + extern const SettingsBool allow_aggregate_function_states_in_open_formats; } namespace ErrorCodes @@ -49,6 +51,29 @@ namespace manifest.filename_pattern = "{part_name}"; return manifest; } + + MergeTreePartitionExportTask makeValidPlainTask() + { + MergeTreePartitionExportTask task; + task.transaction_id = "tx1"; + task.query_id = "query1"; + task.partition_id = "2020"; + task.source_database = "db1"; + task.source_table = "source1"; + task.destination_database = "db1"; + task.destination_table = "table1"; + task.create_time = 1000; + task.parts.push_back({"part1", false, {}}); + task.task_timeout_seconds = 60; + task.max_threads = 1; + task.parallel_formatting = true; + task.parquet_parallel_encoding = true; + task.max_bytes_per_file = 1000000; + task.max_rows_per_file = 1000; + task.file_already_exists_policy = MergeTreePartExportManifest::FileAlreadyExistsPolicy::error; + task.filename_pattern = "{part_name}"; + return task; + } } class ExportPartitionOrderingTest : public ::testing::Test @@ -230,6 +255,45 @@ TEST_F(ExportPartitionManifestBackCompatTest, IgnoreExtraSourceColumnsAppliedToW } } +namespace +{ + template + void expectAggregateFunctionStatesGateAppliedToWorkerContext(Task task) + { + const auto & setting = Setting::allow_aggregate_function_states_in_open_formats; + + /// A task written before the key existed leaves the worker its own setting. + task.allow_aggregate_function_states_in_open_formats = true; + Poco::JSON::Parser parser; + auto json = parser.parse(task.toJsonString()).template extract(); + json->remove("allow_aggregate_function_states_in_open_formats"); + std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM + oss.exceptions(std::ios::failbit); + Poco::JSON::Stringifier::stringify(json, oss); + + auto parsed = Task::fromJsonString(oss.str()); + EXPECT_FALSE(parsed.allow_aggregate_function_states_in_open_formats.has_value()); + EXPECT_EQ( + ExportPartitionUtils::getContextCopyWithTaskSettings(getContext().context, parsed)->getSettingsRef()[setting].value, + getContext().context->getSettingsRef()[setting].value); + + for (const bool value : {false, true}) + { + task.allow_aggregate_function_states_in_open_formats = value; + parsed = Task::fromJsonString(task.toJsonString()); + EXPECT_EQ( + ExportPartitionUtils::getContextCopyWithTaskSettings(getContext().context, parsed)->getSettingsRef()[setting].value, + value) << "value=" << value; + } + } +} + +TEST_F(ExportPartitionManifestBackCompatTest, AggregateFunctionStatesGateAppliedToWorkerContext) +{ + expectAggregateFunctionStatesGateAppliedToWorkerContext(makeValidManifest()); + expectAggregateFunctionStatesGateAppliedToWorkerContext(makeValidPlainTask()); +} + TEST(ExportPartitionRetryClassification, MissingPartIsFatalOnlyOnPlainPath) { EXPECT_FALSE(ExportPartitionUtils::isNonRetryableExportError(ErrorCodes::NO_SUCH_DATA_PART)); diff --git a/src/Storages/ObjectStorage/DataLakes/DataLakeConfiguration.h b/src/Storages/ObjectStorage/DataLakes/DataLakeConfiguration.h index 3221c47ee4835..8398f83f9e614 100644 --- a/src/Storages/ObjectStorage/DataLakes/DataLakeConfiguration.h +++ b/src/Storages/ObjectStorage/DataLakes/DataLakeConfiguration.h @@ -75,6 +75,7 @@ namespace DataLakeStorageSetting extern const DataLakeStorageSettingsString storage_oauth_server_uri; extern const DataLakeStorageSettingsBool storage_oauth_server_use_request_body; extern const DataLakeStorageSettingsString iceberg_metadata_file_path; + extern const DataLakeStorageSettingsBool allow_aggregate_function_states_in_open_formats; } struct FormatParserSharedResources; @@ -481,9 +482,16 @@ class DataLakeConfiguration : public BaseStorageConfiguration, public std::enabl { auto res = BaseStorageConfiguration::createArgsWithAccessData(); - auto iceberg_metadata_file_path = (*settings)[DataLakeStorageSetting::iceberg_metadata_file_path]; + /// The table's own settings that the table function on other nodes has to apply too. + SettingsChanges table_settings; + if (const auto & iceberg_metadata_file_path = (*settings)[DataLakeStorageSetting::iceberg_metadata_file_path]; + iceberg_metadata_file_path.changed) + table_settings.setSetting("iceberg_metadata_file_path", iceberg_metadata_file_path.value); + if (const auto & allow_aggregate_function_states = (*settings)[DataLakeStorageSetting::allow_aggregate_function_states_in_open_formats]; + allow_aggregate_function_states.changed) + table_settings.setSetting("allow_aggregate_function_states_in_open_formats", allow_aggregate_function_states.value); - if (iceberg_metadata_file_path.changed) + if (!table_settings.empty()) { auto * arguments = res->template as(); if (!arguments) @@ -496,7 +504,8 @@ class DataLakeConfiguration : public BaseStorageConfiguration, public std::enabl if (auto * settings_ast = arg->template as()) { has_settings = true; - settings_ast->changes.setSetting("iceberg_metadata_file_path", iceberg_metadata_file_path.value); + for (const auto & change : table_settings) + settings_ast->changes.setSetting(change.name, change.value); break; } } @@ -505,7 +514,7 @@ class DataLakeConfiguration : public BaseStorageConfiguration, public std::enabl { boost::intrusive_ptr settings_ast = make_intrusive(); settings_ast->is_standalone = false; - settings_ast->changes.setSetting("iceberg_metadata_file_path", iceberg_metadata_file_path.value); + settings_ast->changes = std::move(table_settings); arguments->children.push_back(settings_ast); } } diff --git a/src/Storages/ObjectStorage/DataLakes/IDataLakeMetadata.cpp b/src/Storages/ObjectStorage/DataLakes/IDataLakeMetadata.cpp index a3f6898562874..751be03a5f42a 100644 --- a/src/Storages/ObjectStorage/DataLakes/IDataLakeMetadata.cpp +++ b/src/Storages/ObjectStorage/DataLakes/IDataLakeMetadata.cpp @@ -145,7 +145,9 @@ DataFileMetaInfo::DataFileMetaInfo( auto i_bounds = value_bounds_.find(column.first); auto i_type = type_by_index.find(column.first); - if (i_bounds != value_bounds_.end() && i_type != type_by_index.end()) + /// Bounds use the Iceberg encoding of the field, which an annotated type does not necessarily share. + if (i_bounds != value_bounds_.end() && i_type != type_by_index.end() + && !schema_processor.hasClickHouseTypeAnnotation(file_schema_id, column.first)) { const auto & type = i_type->second; if (const auto type_id = type->getTypeId(); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/AddFilesExecute.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/AddFilesExecute.cpp index a56f7e716a494..3e4fd978cb273 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/AddFilesExecute.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/AddFilesExecute.cpp @@ -1047,7 +1047,8 @@ AddFilesResult addFiles( /// created table this add_files call may be the first operation, so register the current /// schema ourselves first. if (!persistent_components.schema_processor->hasClickHouseTableSchemaById(static_cast(original_schema_id))) - persistent_components.schema_processor->addIcebergTableSchema(current_schema, context); + persistent_components.schema_processor->addIcebergTableSchema( + current_schema, context, getClickHouseTypeAnnotations(metadata, static_cast(original_schema_id))); auto clickhouse_schema = persistent_components.schema_processor->getClickHouseTableSchemaById(static_cast(original_schema_id)); Block sample_block; for (const auto & name_and_type : *clickhouse_schema) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.cpp index e76f2c0b54c04..68efdb855eac4 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.cpp @@ -392,8 +392,7 @@ BinPackPlan buildBinPackPlan( current_schema_id); /// Build partition types from the partitioner. - for (UInt32 i = 0; i < schemas->size(); ++i) - persistent_table_components.schema_processor->addIcebergTableSchema(schemas->getObject(i), context); + addIcebergTableSchemasFromMetadata(metadata_object, *persistent_table_components.schema_processor, context); auto fields_characteristics = persistent_table_components.schema_processor->tryGetFieldsCharacteristics( static_cast(current_schema_id), partition_source_ids); @@ -774,9 +773,7 @@ bool hasLivePositionDeletes( return false; const auto current_schema_id = metadata_object->getValue(f_current_schema_id); - auto schemas = metadata_object->getArray(f_schemas); - for (UInt32 i = 0; i < schemas->size(); ++i) - persistent_table_components.schema_processor->addIcebergTableSchema(schemas->getObject(i), context); + addIcebergTableSchemasFromMetadata(metadata_object, *persistent_table_components.schema_processor, context); auto manifest_list = getManifestList( object_storage, persistent_table_components, context, @@ -841,6 +838,7 @@ RewriteResult rewriteBins( FileNamesGenerator & generator, const IcebergPathResolver & path_resolver, const String & write_format, + const std::optional & format_settings, UInt64 target_size, std::vector & new_data_file_paths, LoggerPtr log) @@ -864,7 +862,7 @@ RewriteResult rewriteBins( path_resolver, object_storage, context, - std::nullopt, /// format_settings + format_settings, write_format, sample_block, [&](const std::string & path) @@ -1424,6 +1422,7 @@ BinPackCommitResult executeBinPackCompaction( const DataLakeStorageSettings & data_lake_settings, ContextPtr context, const String & write_format, + const std::optional & format_settings, std::shared_ptr catalog, const StorageID & storage_id) { @@ -1520,7 +1519,7 @@ BinPackCommitResult executeBinPackCompaction( auto rewrite = rewriteBins( plan, persistent_table_components, object_storage, secondary_storages, context, current_schema, schema_processor, current_schema_id_int, sample_block, - current_schema_column_mapper, generator, path_resolver, write_format, + current_schema_column_mapper, generator, path_resolver, write_format, format_settings, target_size, new_data_file_paths, log); if (rewrite.bin_results.empty()) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.h index 69cdd069bb849..bc008aadf0d87 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.h @@ -55,6 +55,7 @@ BinPackCommitResult executeBinPackCompaction( const DataLakeStorageSettings & data_lake_settings, ContextPtr context, const String & write_format, + const std::optional & format_settings, std::shared_ptr catalog, const StorageID & storage_id); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp index a68d4e8508a4e..b8fbe90a4a397 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp @@ -249,6 +249,9 @@ static Plan getPlan( plan.initial_metadata_object = initial_metadata_object; plan.initial_metadata_path = metadata_file_path; + /// Register the metadata.json schemas before the manifest headers carry copies of them without the type annotations. + addIcebergTableSchemasFromMetadata(initial_metadata_object, *persistent_table_components.schema_processor, context); + std::vector all_positional_delete_files; std::unordered_map> manifest_files; std::unordered_set referenced_file_paths; @@ -543,6 +546,10 @@ static bool writeConsolidatedManifestFile( "Iceberg metadata does not contain a schema entry matching current-schema-id {}", current_schema_id); + /// Register the metadata.json schemas before the manifest headers carry copies of them without the type annotations, + /// and so that the partition spec resolution below can query any of them by id. + addIcebergTableSchemasFromMetadata(metadata_object, *persistent_table_components.schema_processor, context); + auto partitions_specs = metadata_object->getArray(f_partition_specs); /// After partition evolution each manifest must be rewritten under the spec its source files used; resolve and cache spec info per spec-id. @@ -588,10 +595,7 @@ static bool writeConsolidatedManifestFile( source_ids.push_back(spec_field->getValue(Iceberg::f_source_id)); } - /// Derive partition value types from a schema that defines every source column the spec references, preferring the current schema then any historical one; register all schemas first so they can be queried by id. - for (UInt32 i = 0; i < schemas->size(); ++i) - persistent_table_components.schema_processor->addIcebergTableSchema(schemas->getObject(i), context); - + /// Derive partition value types from a schema that defines every source column the spec references, preferring the current schema then any historical one. auto build_sample_block = [&](Int32 schema_id) -> std::optional { auto fields_characteristics diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Constant.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/Constant.h index 48a48cf4d669f..0d4e9f5631e6b 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Constant.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Constant.h @@ -181,6 +181,7 @@ DEFINE_ICEBERG_FIELD_ALIAS(ref_min_snapshots_to_keep, min-snapshots-to-keep); DEFINE_ICEBERG_FIELD_ALIAS(ref_max_snapshot_age_ms, max-snapshot-age-ms); DEFINE_ICEBERG_FIELD_ALIAS(ref_max_ref_age_ms, max-ref-age-ms); DEFINE_ICEBERG_FIELD_ALIAS(clickhouse_export_partition_transaction_id, clickhouse.export-partition-transaction-id); +DEFINE_ICEBERG_FIELD_ALIAS(clickhouse_type, clickhouse.type); /// These are compound fields like `data_file.file_path`, we use prefix 'c_' to distinguish them. DEFINE_ICEBERG_FIELD_COMPOUND(data_file, file_path); DEFINE_ICEBERG_FIELD_COMPOUND(data_file, file_format); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.cpp index 88494c3233055..8b0bb4e25198c 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -34,6 +35,19 @@ static Range getExtremeRangeFromColumn(const ColumnPtr & column) return Range(min_val, true, max_val, true); } +static bool supportsExtremeRange(const IColumn & column) +{ + if (checkAndGetColumn(&column)) + return false; + + bool result = true; + column.forEachSubcolumnRecursively([&](const IColumn & subcolumn) + { + result &= checkAndGetColumn(&subcolumn) == nullptr; + }); + return result; +} + void DataFileStatistics::update(const Chunk & chunk) { if (!chunk.hasRows()) @@ -42,9 +56,12 @@ void DataFileStatistics::update(const Chunk & chunk) if (null_counts.empty()) { null_counts.resize(num_columns, 0); + track_ranges.resize(num_columns); for (size_t i = 0; i < num_columns; ++i) { - ranges.push_back(getExtremeRangeFromColumn(chunk.getColumns()[i])); + const auto & col = chunk.getColumns()[i]; + track_ranges[i] = supportsExtremeRange(*col); + ranges.push_back(track_ranges[i] ? getExtremeRangeFromColumn(col) : Range::createWholeUniverse()); } } @@ -58,7 +75,8 @@ void DataFileStatistics::update(const Chunk & chunk) for (UInt8 v : nullable_col->getNullMapData()) null_counts[i] += v; } - ranges[i] = uniteRanges(ranges[i], getExtremeRangeFromColumn(col)); + if (track_ranges[i]) + ranges[i] = uniteRanges(ranges[i], getExtremeRangeFromColumn(col)); } } @@ -127,6 +145,7 @@ void DataFileStatistics::merge(const DataFileStatistics & other) { null_counts = other.null_counts; ranges = other.ranges; + track_ranges = other.track_ranges; return; } @@ -134,7 +153,8 @@ void DataFileStatistics::merge(const DataFileStatistics & other) for (size_t i = 0; i < null_counts.size(); ++i) { null_counts[i] += other.null_counts[i]; - ranges[i] = uniteRanges(ranges[i], other.ranges[i]); + if (track_ranges[i]) + ranges[i] = uniteRanges(ranges[i], other.ranges[i]); } } @@ -175,8 +195,9 @@ std::vector> DataFileStatistics::getLowerBounds() const std::vector> result; for (size_t i = 0; i < ranges.size(); ++i) { - if (!isExcluded(i)) - result.push_back({field_ids[i], ranges[i].left}); + if (isExcluded(i) || !track_ranges[i]) + continue; + result.push_back({field_ids[i], ranges[i].left}); } return result; } @@ -186,8 +207,9 @@ std::vector> DataFileStatistics::getUpperBounds() const std::vector> result; for (size_t i = 0; i < ranges.size(); ++i) { - if (!isExcluded(i)) - result.push_back({field_ids[i], ranges[i].right}); + if (isExcluded(i) || !track_ranges[i]) + continue; + result.push_back({field_ids[i], ranges[i].right}); } return result; } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.h index cf78c9e1d6522..6172cb8237a04 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.h @@ -48,6 +48,7 @@ class DataFileStatistics std::vector column_sizes; std::vector null_counts; Ranges ranges; + std::vector track_ranges; }; using DataFileStatisticsPtr = std::shared_ptr; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/ExpireSnapshotsExecute.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/ExpireSnapshotsExecute.cpp index 69cc6ce8d14df..00fa804743478 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/ExpireSnapshotsExecute.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/ExpireSnapshotsExecute.cpp @@ -908,6 +908,9 @@ ExpireSnapshotsResult expireSnapshots( Int32 current_schema_id = metadata->getValue(Iceberg::f_current_schema_id); + /// Register the metadata.json schemas before the manifest headers carry copies of them without the type annotations. + addIcebergTableSchemasFromMetadata(metadata, *persistent_table_components.schema_processor, context); + std::set retained_manifest_paths; std::set retained_data_file_paths; std::set retained_manifest_list_paths; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp index 9aca0923cdd3f..ed960aed71069 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include "config.h" @@ -289,7 +290,9 @@ std::pair Ice auto root_derivation = IcebergPathResolver::deriveTableRoot(table_location, table_path, metadata_file_path); PersistentTableComponents persistent_components{ .schema_processor = std::make_shared( - context_, context_->getSettingsRef()[Setting::allow_experimental_geo_types_in_iceberg]), + context_, + context_->getSettingsRef()[Setting::allow_experimental_geo_types_in_iceberg], + getTableAllowAggregateFunctionStates(configuration->getDataLakeSettings())), .metadata_cache = cache_ptr, .format_version = format_version, .table_location = table_location, @@ -325,7 +328,7 @@ Iceberg::MetadataFileWithInfo IcebergMetadata::fetchLatestMetadata(const Context } std::pair IcebergMetadata::getRelevantState( - const ContextPtr & context, bool force_fetch_latest_metadata) const + const ContextPtr & context, bool force_fetch_latest_metadata, SchemaParsing schema_parsing) const { if (!force_fetch_latest_metadata && !data_lake_settings[DataLakeStorageSetting::iceberg_metadata_file_path].changed) { @@ -335,11 +338,11 @@ std::pair IcebergMetadata::getReleva latest_metadata = cached_latest_metadata; } if (latest_metadata) - return getState(context, latest_metadata->path, latest_metadata->version); + return getState(context, latest_metadata->path, latest_metadata->version, schema_parsing); } const auto latest_metadata = fetchLatestMetadata(context, force_fetch_latest_metadata); - return getState(context, latest_metadata.path, latest_metadata.version); + return getState(context, latest_metadata.path, latest_metadata.version, schema_parsing); } IcebergMetadata::IcebergMetadata( @@ -405,8 +408,10 @@ void IcebergMetadata::backgroundMetadataPrefetcherThread() /// first, we fetch the latest metadata version and cache it; /// as a part of the same method, we download metadata.json of the latest metadata version /// and after parsing it, we fetch manifest lists, parse and cache them + /// + /// Schema parsing depends on query settings, which a background prefetch has no authority to apply. auto ctx = Context::createCopy(Context::getGlobalContextInstance()); - auto [actual_data_snapshot, actual_table_state_snapshot] = getRelevantState(ctx, true); + auto [actual_data_snapshot, actual_table_state_snapshot] = getRelevantState(ctx, true, SchemaParsing::Skip); if (actual_data_snapshot) { for (const auto & entry : actual_data_snapshot->manifest_list_entries) @@ -437,19 +442,27 @@ Int32 IcebergMetadata::parseTableSchema( const Poco::JSON::Object::Ptr & metadata_object, IcebergSchemaProcessor & schema_processor, ContextPtr context_, - LoggerPtr metadata_logger) + LoggerPtr metadata_logger, + SchemaParsing schema_parsing) { const auto format_version = metadata_object->getValue(f_format_version); if (metadata_object->has(f_last_column_id) && !metadata_object->isNull(f_last_column_id)) schema_processor.updateLastColumnId(metadata_object->getValue(f_last_column_id)); + auto add_schema = [&](const Poco::JSON::Object::Ptr & schema) + { + if (schema_parsing == SchemaParsing::Parse) + schema_processor.addIcebergTableSchema( + schema, context_, getClickHouseTypeAnnotations(metadata_object, schema->getValue(f_schema_id))); + }; + /// v2 and v3 (and later) store schemas in the `schemas` array. Only v1 has a top-level `schema`. /// Using the v1 parser first for v3 looks like a spec violation and logs a false warning. if (format_version >= 2) { auto [schema, current_schema_id] = parseTableSchemaV2Method(metadata_object); - schema_processor.addIcebergTableSchema(schema, context_); + add_schema(schema); return current_schema_id; } else @@ -457,7 +470,7 @@ Int32 IcebergMetadata::parseTableSchema( try { auto [schema, current_schema_id] = parseTableSchemaV1Method(metadata_object); - schema_processor.addIcebergTableSchema(schema, context_); + add_schema(schema); return current_schema_id; } catch (const Exception & first_error) @@ -467,7 +480,7 @@ Int32 IcebergMetadata::parseTableSchema( try { auto [schema, current_schema_id] = parseTableSchemaV2Method(metadata_object); - schema_processor.addIcebergTableSchema(schema, context_); + add_schema(schema); LOG_WARNING( metadata_logger, "Iceberg table schema was parsed using v2 specification, but it was impossible to parse it using v1 " @@ -494,18 +507,15 @@ static Poco::JSON::Object::Ptr traverseMetadataAndFindNecessarySnapshotObject( Poco::JSON::Object::Ptr metadata_object, Int64 snapshot_id, IcebergSchemaProcessorPtr schema_processor, - ContextPtr local_context) + ContextPtr local_context, + IcebergMetadata::SchemaParsing schema_parsing) { if (!metadata_object->has(f_snapshots)) throw Exception(ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, "No snapshot set found in metadata for iceberg file"); if (metadata_object->has(f_last_column_id) && !metadata_object->isNull(f_last_column_id)) schema_processor->updateLastColumnId(metadata_object->getValue(f_last_column_id)); - auto schemas = metadata_object->get(f_schemas).extract(); - for (UInt32 j = 0; j < schemas->size(); ++j) - { - auto schema = schemas->getObject(j); - schema_processor->addIcebergTableSchema(schema, local_context); - } + if (schema_parsing == IcebergMetadata::SchemaParsing::Parse) + addIcebergTableSchemasFromMetadata(metadata_object, *schema_processor, local_context); Poco::JSON::Object::Ptr current_snapshot = nullptr; auto snapshots = metadata_object->get(f_snapshots).extract(); for (size_t i = 0; i < snapshots->size(); ++i) @@ -571,14 +581,15 @@ IcebergDataSnapshotPtr IcebergMetadata::createIcebergDataSnapshotFromSnapshotJSO metadata_object->has(f_partition_specs) ? metadata_object->get(f_partition_specs).extract() : nullptr); } -IcebergDataSnapshotPtr -IcebergMetadata::getIcebergDataSnapshot(Poco::JSON::Object::Ptr metadata_object, Int64 snapshot_id, ContextPtr local_context) const +IcebergDataSnapshotPtr IcebergMetadata::getIcebergDataSnapshot( + Poco::JSON::Object::Ptr metadata_object, Int64 snapshot_id, ContextPtr local_context, SchemaParsing schema_parsing) const { auto object = traverseMetadataAndFindNecessarySnapshotObject( metadata_object, snapshot_id, persistent_components.schema_processor, - local_context); + local_context, + schema_parsing); if (!object) throw Exception(ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, "No snapshot found for id `{}`", snapshot_id); @@ -666,6 +677,7 @@ bool IcebergMetadata::optimize( data_lake_settings, context, write_format, + format_settings, catalog, storage_id); @@ -722,7 +734,7 @@ bool IcebergMetadata::optimizeManifestFiles( } std::pair -IcebergMetadata::getStateImpl(const ContextPtr & local_context, Poco::JSON::Object::Ptr metadata_object) const +IcebergMetadata::getStateImpl(const ContextPtr & local_context, Poco::JSON::Object::Ptr metadata_object, SchemaParsing schema_parsing) const { std::optional manifest_list_file; @@ -763,18 +775,18 @@ IcebergMetadata::getStateImpl(const ContextPtr & local_context, Poco::JSON::Obje ErrorCodes::BAD_ARGUMENTS, "No snapshot found in snapshot log before requested timestamp for iceberg table {}", persistent_components.table_path); - auto data_snapshot = getIcebergDataSnapshot(metadata_object, *current_snapshot_id, local_context); + auto data_snapshot = getIcebergDataSnapshot(metadata_object, *current_snapshot_id, local_context, schema_parsing); return {data_snapshot, static_cast(data_snapshot->schema_id_on_snapshot_commit)}; } else if (snapshot_id_changed) { Int64 current_snapshot_id = local_context->getSettingsRef()[Setting::iceberg_snapshot_id]; - auto data_snapshot = getIcebergDataSnapshot(metadata_object, current_snapshot_id, local_context); + auto data_snapshot = getIcebergDataSnapshot(metadata_object, current_snapshot_id, local_context, schema_parsing); return {data_snapshot, static_cast(data_snapshot->schema_id_on_snapshot_commit)}; } else { - auto schema_id = parseTableSchema(metadata_object, *persistent_components.schema_processor, local_context, log); + auto schema_id = parseTableSchema(metadata_object, *persistent_components.schema_processor, local_context, log, schema_parsing); if (!metadata_object->has(f_current_snapshot_id)) { return {nullptr, schema_id}; @@ -786,13 +798,14 @@ IcebergMetadata::getStateImpl(const ContextPtr & local_context, Poco::JSON::Obje { return {nullptr, schema_id}; } - auto data_snapshot = getIcebergDataSnapshot(metadata_object, current_snapshot_id, local_context); + auto data_snapshot = getIcebergDataSnapshot(metadata_object, current_snapshot_id, local_context, schema_parsing); return {data_snapshot, schema_id}; } } std::pair -IcebergMetadata::getState(const ContextPtr & local_context, const String & metadata_path, Int32 metadata_version) const +IcebergMetadata::getState( + const ContextPtr & local_context, const String & metadata_path, Int32 metadata_version, SchemaParsing schema_parsing) const { IcebergDataSnapshotPtr data_snapshot; TableStateSnapshot table_state_snapshot; @@ -809,7 +822,7 @@ IcebergMetadata::getState(const ContextPtr & local_context, const String & metad std::nullopt, std::nullopt); - std::tie(data_snapshot, table_state_snapshot.schema_id) = getStateImpl(local_context, metadata_object); + std::tie(data_snapshot, table_state_snapshot.schema_id) = getStateImpl(local_context, metadata_object, schema_parsing); table_state_snapshot.snapshot_id = data_snapshot ? std::optional{data_snapshot->snapshot_id} : std::nullopt; table_state_snapshot.metadata_version = metadata_version; table_state_snapshot.metadata_file_path = metadata_path; @@ -1091,6 +1104,23 @@ void IcebergMetadata::alterPartitionDropImpl( executor.run(); } +static void checkAggregateFunctionStatesAllowed( + const String & column_name, const DataTypePtr & type, const DataLakeStorageSettings & data_lake_settings, const ContextPtr & context) +{ + if (!type || !hasAggregateFunctionType(type)) + return; + if (allowAggregateFunctionStates(Iceberg::getTableAllowAggregateFunctionStates(data_lake_settings), context)) + return; + + throw Exception( + ErrorCodes::SUPPORT_IS_DISABLED, + "Column '{}' has type {}, which Iceberg cannot express natively: the aggregate state is stored as " + "binary and its ClickHouse type is recorded in the table properties. To allow this, enable setting " + "allow_aggregate_function_states_in_open_formats in the table's SETTINGS or, if the table does not set it, in the query", + column_name, + type->getName()); +} + void IcebergMetadata::alter( const AlterCommands & params, ContextPtr context, @@ -1105,6 +1135,9 @@ void IcebergMetadata::alter( "To allow its usage, enable setting allow_insert_into_iceberg"); } + for (const auto & command : params) + checkAggregateFunctionStatesAllowed(command.column_name, command.data_type, data_lake_settings, context); + Iceberg::alter(params, context, storage_id, object_storage, data_lake_settings, persistent_components, write_format, catalog); } @@ -1245,6 +1278,9 @@ void IcebergMetadata::createInitial( } } + for (const auto & column : columns->getAll()) + checkAggregateFunctionStatesAllowed(column.name, column.type, configuration_ptr->getDataLakeSettings(), local_context); + String location_path = configuration_ptr->getRawPath().path; if (!location_path.contains("://") && !location_path.starts_with('/')) location_path = "/" + location_path; @@ -1365,7 +1401,7 @@ Iceberg::IcebergDataSnapshotPtr IcebergMetadata::getRelevantDataSnapshotFromTabl if (!table_state_snapshot.snapshot_id.has_value()) return nullptr; Poco::JSON::Object::Ptr snapshot_object = traverseMetadataAndFindNecessarySnapshotObject( - metadata_object, *table_state_snapshot.snapshot_id, persistent_components.schema_processor, local_context); + metadata_object, *table_state_snapshot.snapshot_id, persistent_components.schema_processor, local_context, SchemaParsing::Parse); return createIcebergDataSnapshotFromSnapshotJSON(metadata_object, snapshot_object, *table_state_snapshot.snapshot_id, local_context); } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.h index d9718b0453b43..366e60ca79ac5 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.h @@ -108,11 +108,18 @@ class IcebergMetadata : public IDataLakeMetadata std::shared_ptr getInitialSchemaByPath(ContextPtr local_context, ObjectInfoPtr object_info) const override; std::shared_ptr getSchemaTransformer(ContextPtr local_context, ObjectInfoPtr object_info) const override; + enum class SchemaParsing + { + Parse, + Skip, + }; + static Int32 parseTableSchema( const Poco::JSON::Object::Ptr & metadata_object, Iceberg::IcebergSchemaProcessor & schema_processor, ContextPtr context_, - LoggerPtr metadata_logger); + LoggerPtr metadata_logger, + SchemaParsing schema_parsing = SchemaParsing::Parse); bool supportsUpdate() const override { return true; } @@ -255,10 +262,14 @@ class IcebergMetadata : public IDataLakeMetadata std::pair getRelevantState( const ContextPtr & context, - bool force_fetch_latest_metadata = false) const; + bool force_fetch_latest_metadata = false, + SchemaParsing schema_parsing = SchemaParsing::Parse) const; - std::pair - getState(const ContextPtr & local_context, const String & metadata_path, Int32 metadata_version) const; + std::pair getState( + const ContextPtr & local_context, + const String & metadata_path, + Int32 metadata_version, + SchemaParsing schema_parsing = SchemaParsing::Parse) const; const DB::Iceberg::PersistentTableComponents & getPersistentComponents() const { @@ -278,12 +289,12 @@ class IcebergMetadata : public IDataLakeMetadata ContextPtr context_, LoggerPtr log); - Iceberg::IcebergDataSnapshotPtr - getIcebergDataSnapshot(Poco::JSON::Object::Ptr metadata_object, Int64 snapshot_id, ContextPtr local_context) const; + Iceberg::IcebergDataSnapshotPtr getIcebergDataSnapshot( + Poco::JSON::Object::Ptr metadata_object, Int64 snapshot_id, ContextPtr local_context, SchemaParsing schema_parsing) const; Iceberg::IcebergDataSnapshotPtr createIcebergDataSnapshotFromSnapshotJSON(Poco::JSON::Object::Ptr metadata_object, Poco::JSON::Object::Ptr snapshot_object, Int64 snapshot_id, ContextPtr local_context) const; std::pair - getStateImpl(const ContextPtr & local_context, Poco::JSON::Object::Ptr metadata_object) const; + getStateImpl(const ContextPtr & local_context, Poco::JSON::Object::Ptr metadata_object, SchemaParsing schema_parsing) const; Iceberg::IcebergDataSnapshotPtr getRelevantDataSnapshotFromTableStateSnapshot(Iceberg::TableStateSnapshot table_state_snapshot, ContextPtr local_context) const; StorageObjectStorageConfigurationPtr getConfiguration() const; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp index 79ed87e5fc8a6..770164f7d3616 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp @@ -309,8 +309,9 @@ std::shared_ptr ManifestFileIterator::create( f_schema); manifest_schema_id = embedded_schema_id; + /// The table metadata properties are not available here, so the header schema gets no ClickHouse type annotations. schema_processor.addIcebergTableSchema( - schema_object, context_, IcebergSchemaProcessor::SchemaSource::ManifestFile, tolerate_conflicting_manifest_schemas); + schema_object, context_, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, tolerate_conflicting_manifest_schemas); } /// Every entry of this manifest carries one partition value per spec field, including the diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp index 7d7a66942bf5c..9551cbf7f2476 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp @@ -219,6 +219,10 @@ ManifestFilesPruner::ManifestFilesPruner( if (!name_and_type.has_value()) continue; + /// Bounds use the Iceberg encoding of the field, which an annotated type does not necessarily share. + if (schema_processor.hasClickHouseTypeAnnotation(initial_schema_id, used_column_id)) + continue; + min_max_column_types.emplace(used_column_id, name_and_type->type); name_and_type->name = DB::backQuote(DB::toString(used_column_id)); } @@ -304,6 +308,9 @@ PartitionKeyFromSpec buildPartitionKeyFromSpec( std::optional column_characteristics = schema_processor.tryGetFieldCharacteristics(schema_id, source_id); if (!column_characteristics.has_value()) continue; + /// Partition values use the Iceberg encoding of the field, which an annotated type does not necessarily share. + if (schema_processor.hasClickHouseTypeAnnotation(schema_id, source_id)) + continue; auto partition_ast = getASTFromTransform(transform_name, numeric_column_name, context->getSettingsRef()[Setting::iceberg_partition_timezone]); /// Unsupported partition key expression if (partition_ast == nullptr) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp index 794f1153c128d..8ceb92519d81e 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include #include @@ -11,7 +13,6 @@ #include #include -#include #include #include @@ -150,99 +151,6 @@ bool checkValidSchemaEvolution(Poco::Dynamic::Var old_type, Poco::Dynamic::Var n return false; } - -String removeASCIIWhitespace(const String & s) -{ - String result; - result.reserve(s.size()); - for (char c : s) - { - if (!isWhitespaceASCII(c)) - result.push_back(c); - } - return result; -} - -/// A missing key matches only a missing key. -bool optionalBoolsEqual(const Poco::JSON::Object::Ptr & first, const Poco::JSON::Object::Ptr & second, const char * key) -{ - const bool first_has = first->has(key); - if (first_has != second->has(key)) - return false; - return !first_has || first->getValue(key) == second->getValue(key); -} - -/// Whether two Iceberg type descriptors denote the same type. -/// Only the properties that define the type are compared. Field ids are ignored because -/// `getIcebergType` allocates them from a running counter, so a previous attempt may have written -/// the very same type with lower ids. Other keys (`doc`, defaults, the `required` that -/// `getIcebergType` puts on a list) are ignored because other writers emit or omit them freely. -bool icebergTypesEqualIgnoringIds(Poco::Dynamic::Var old_type, Poco::Dynamic::Var new_type) -{ - if (old_type.isString() || new_type.isString()) - { - if (!old_type.isString() || !new_type.isString()) - return false; - /// Writers differ in spacing, e.g. `decimal(10,2)` and `decimal(10, 2)`. - return removeASCIIWhitespace(old_type.extract()) == removeASCIIWhitespace(new_type.extract()); - } - - if (old_type.type() != typeid(Poco::JSON::Object::Ptr) || new_type.type() != typeid(Poco::JSON::Object::Ptr)) - return false; - - auto old_object = old_type.extract(); - auto new_object = new_type.extract(); - if (!old_object || !new_object) - return false; - - if (old_object->has("precision") || new_object->has("precision")) - { - return old_object->has("precision") && new_object->has("precision") - && old_object->getValue("precision") == new_object->getValue("precision") - && old_object->getValue("scale") == new_object->getValue("scale"); - } - - if (!old_object->has(Iceberg::f_type) || !new_object->has(Iceberg::f_type)) - return false; - const auto kind = old_object->getValue(Iceberg::f_type); - if (kind != new_object->getValue(Iceberg::f_type)) - return false; - - if (kind == Iceberg::f_list) - { - return optionalBoolsEqual(old_object, new_object, Iceberg::f_element_required) - && icebergTypesEqualIgnoringIds(old_object->get(Iceberg::f_element), new_object->get(Iceberg::f_element)); - } - - if (kind == Iceberg::f_map) - { - return optionalBoolsEqual(old_object, new_object, Iceberg::f_value_required) - && icebergTypesEqualIgnoringIds(old_object->get(Iceberg::f_key), new_object->get(Iceberg::f_key)) - && icebergTypesEqualIgnoringIds(old_object->get(Iceberg::f_value), new_object->get(Iceberg::f_value)); - } - - if (kind == Iceberg::f_struct) - { - auto old_fields = old_object->getArray(Iceberg::f_fields); - auto new_fields = new_object->getArray(Iceberg::f_fields); - if (!old_fields || !new_fields || old_fields->size() != new_fields->size()) - return false; - for (UInt32 i = 0; i < old_fields->size(); ++i) - { - auto old_field = old_fields->getObject(i); - auto new_field = new_fields->getObject(i); - if (!old_field || !new_field - || old_field->getValue(Iceberg::f_name) != new_field->getValue(Iceberg::f_name) - || !optionalBoolsEqual(old_field, new_field, Iceberg::f_required) - || !icebergTypesEqualIgnoringIds(old_field->get(Iceberg::f_type), new_field->get(Iceberg::f_type))) - return false; - } - return true; - } - - return false; -} - /// The Iceberg spec marks `snapshots`, `metadata-log` and `snapshot-log` as optional, so table /// metadata written by another engine may omit any of them - typically for a table that has never /// been written to. Return the array, creating an empty one when the field is absent, so that @@ -269,6 +177,23 @@ Int32 getNextSchemaId(Poco::JSON::Object::Ptr metadata_object) return max_id + 1; } +/// Appends `schema` as the current schema `schema_id`. Its fields keep the ClickHouse type annotations they had +/// in the previous current schema, which need not be the one with the highest id. +void addCurrentSchema(Poco::JSON::Object::Ptr metadata_object, Poco::JSON::Object::Ptr schema, Int32 schema_id) +{ + const auto previous_annotations + = Iceberg::getClickHouseTypeAnnotations(metadata_object, metadata_object->getValue(Iceberg::f_current_schema_id)); + schema->set(Iceberg::f_schema_id, schema_id); + metadata_object->set(Iceberg::f_current_schema_id, schema_id); + metadata_object->getArray(Iceberg::f_schemas)->add(schema); + for (const auto & [name, field_id] : Iceberg::IcebergSchemaProcessor::traverseSchema(schema->getArray(Iceberg::f_fields))) + { + const auto it = previous_annotations.find(static_cast(field_id)); + Iceberg::setClickHouseTypeAnnotation( + metadata_object, static_cast(field_id), schema_id, it == previous_annotations.end() ? String{} : it->second.type_name); + } +} + /// Whether the field at `index` of `fields` satisfies the `FIRST` / `AFTER after_column` clause of an ALTER. /// `AFTER` the column itself does not move it, so any position satisfies it. bool isFieldAtRequestedPosition( @@ -345,6 +270,28 @@ Poco::JSON::Object::Ptr MetadataGenerator::getCurrentSchema() const return current_schema; } +/// Whether the annotation of `field` in the current schema is the one recorded for `type`. +static bool clickHouseTypeAnnotationMatches( + const Poco::JSON::Object::Ptr & metadata_object, const Poco::JSON::Object::Ptr & field, const DataTypePtr & type) +{ + const auto annotations + = Iceberg::getClickHouseTypeAnnotations(metadata_object, metadata_object->getValue(Iceberg::f_current_schema_id)); + const auto it = annotations.find(field->getValue(Iceberg::f_id)); + return (it == annotations.end() ? String{} : it->second.type_name) == getClickHouseTypeAnnotation(type); +} + +/// The state versions of the aggregate functions nested in `type`, in traversal order. +static std::vector getAggregateFunctionStateVersions(DataTypePtr type) +{ + std::vector versions; + callOnNestedSimpleTypes(type, [&versions](DataTypePtr & nested_type) + { + if (const auto * aggregate_function_type = typeid_cast(nested_type.get())) + versions.push_back(aggregate_function_type->getVersion()); + }); + return versions; +} + bool MetadataGenerator::isAddColumnApplied(const String & column_name, DataTypePtr type, bool first, const String & after_column) const { auto current_schema = findCurrentSchema(); @@ -364,7 +311,8 @@ bool MetadataGenerator::isAddColumnApplied(const String & column_name, DataTypeP /// The stored descriptor was produced from a lower `last-column-id` than the one we /// just used, so the ids of nested elements differ even for the very same type. return field->getValue(Iceberg::f_required) == expected_type.second - && icebergTypesEqualIgnoringIds(field->get(Iceberg::f_type), expected_type.first) + && Iceberg::icebergTypesEqualIgnoringIds(field->get(Iceberg::f_type), expected_type.first) + && clickHouseTypeAnnotationMatches(metadata_object, field, type) && isFieldAtRequestedPosition(fields, i, column_name, first, after_column); } return false; @@ -424,7 +372,8 @@ bool MetadataGenerator::isModifyColumnApplied(const String & column_name, DataTy auto format_version = metadata_object->getValue(Iceberg::f_format_version); auto expected_type = Iceberg::getIcebergType(type, unused_field_id, format_version); if (field->getValue(Iceberg::f_required) != expected_type.second - || !icebergTypesEqualIgnoringIds(field->get(Iceberg::f_type), expected_type.first)) + || !Iceberg::icebergTypesEqualIgnoringIds(field->get(Iceberg::f_type), expected_type.first) + || !clickHouseTypeAnnotationMatches(metadata_object, field, type)) return false; } @@ -876,9 +825,7 @@ void MetadataGenerator::generateDropColumnMetadata(const String & column_name) } current_schema->getArray(Iceberg::f_fields)->remove(index_to_drop); - current_schema->set(Iceberg::f_schema_id, next_schema_id); - metadata_object->set(Iceberg::f_current_schema_id, next_schema_id); - metadata_object->getArray(Iceberg::f_schemas)->add(current_schema); + addCurrentSchema(metadata_object, current_schema, next_schema_id); } void MetadataGenerator::generateAddColumnMetadata(const String & column_name, DataTypePtr type, bool first, const String & after_column) @@ -943,12 +890,17 @@ void MetadataGenerator::generateAddColumnMetadata(const String & column_name, Da existing_fields->add(new_field); } - current_schema->set(Iceberg::f_schema_id, next_schema_id); - metadata_object->set(Iceberg::f_current_schema_id, next_schema_id); - metadata_object->getArray(Iceberg::f_schemas)->add(current_schema); + addCurrentSchema(metadata_object, current_schema, next_schema_id); + Iceberg::setClickHouseTypeAnnotation(metadata_object, new_field_id, next_schema_id, getClickHouseTypeAnnotation(type)); } -bool MetadataGenerator::generateModifyColumnMetadata(const String & column_name, DataTypePtr type, ContextPtr context, bool first, const String & after_column) +bool MetadataGenerator::generateModifyColumnMetadata( + const String & column_name, + DataTypePtr type, + ContextPtr context, + bool first, + const String & after_column, + std::optional table_allow_aggregate_function_states) { if (type) Iceberg::checkUnknownTypeAllowed(column_name, type, metadata_object->getValue(Iceberg::f_format_version)); @@ -961,6 +913,8 @@ bool MetadataGenerator::generateModifyColumnMetadata(const String & column_name, /// `AFTER` the column itself keeps its position, as in `ColumnsDescription::modifyColumnOrder`. bool needs_reposition = first || (!after_column.empty() && after_column != column_name); bool type_changed = false; + /// The Iceberg type stays, only the ClickHouse type annotation changes. + bool annotation_changed = false; if (type) { @@ -973,11 +927,15 @@ bool MetadataGenerator::generateModifyColumnMetadata(const String & column_name, continue; if (current_field->getValue(Iceberg::f_required) == new_type.second - && icebergTypesEqualIgnoringIds(current_field->get(Iceberg::f_type), new_type.first)) + && Iceberg::icebergTypesEqualIgnoringIds(current_field->get(Iceberg::f_type), new_type.first)) { + const auto annotations = Iceberg::getClickHouseTypeAnnotations( + metadata_object, metadata_object->getValue(Iceberg::f_current_schema_id)); Iceberg::IcebergSchemaProcessor schema_processor( - context, context->getSettingsRef()[Setting::allow_experimental_geo_types_in_iceberg]); - auto current_ch_type = schema_processor.getClickHouseFieldType(current_field, context); + context, + context->getSettingsRef()[Setting::allow_experimental_geo_types_in_iceberg], + table_allow_aggregate_function_states); + const auto current_ch_type = schema_processor.getClickHouseFieldType(current_field, annotations, context); if (!current_ch_type->equals(*type)) throw Exception( @@ -989,7 +947,21 @@ bool MetadataGenerator::generateModifyColumnMetadata(const String & column_name, type->getName(), current_field->get(Iceberg::f_type).toString()); - if (!needs_reposition) + /// `IDataType::equals` ignores the state version, but all data files of the schema are read with + /// the version of its annotation. + if (getAggregateFunctionStateVersions(current_ch_type) != getAggregateFunctionStateVersions(type)) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Cannot MODIFY COLUMN '{}' from {} to {}: the aggregate function state version differs, " + "so the existing data files would be read with a different state layout", + column_name, + current_ch_type->getName(), + type->getName()); + + /// `IDataType::equals` ignores the custom name of `SimpleAggregateFunction`. + if (!clickHouseTypeAnnotationMatches(metadata_object, current_field, type)) + annotation_changed = true; + else if (!needs_reposition) return false; } else @@ -1018,8 +990,20 @@ bool MetadataGenerator::generateModifyColumnMetadata(const String & column_name, if (target_index == schema_fields->size()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Column {} not found in schema", column_name); + const auto target_field_id = schema_fields->getObject(target_index)->getValue(Iceberg::f_id); + if (!type_changed && !needs_reposition) - return false; + { + if (!annotation_changed) + return false; + /// The schema stays the same, so the annotation is recorded for its id, which a REST catalog keeps as well. + Iceberg::setClickHouseTypeAnnotation( + metadata_object, + target_field_id, + metadata_object->getValue(Iceberg::f_current_schema_id), + getClickHouseTypeAnnotation(type)); + return true; + } const auto next_schema_id = getNextSchemaId(metadata_object); current_schema = Iceberg::deepCopy(current_schema); @@ -1065,9 +1049,9 @@ bool MetadataGenerator::generateModifyColumnMetadata(const String & column_name, current_schema->set(Iceberg::f_fields, new_fields); } - metadata_object->set(Iceberg::f_current_schema_id, next_schema_id); - current_schema->set(Iceberg::f_schema_id, next_schema_id); - metadata_object->getArray(Iceberg::f_schemas)->add(current_schema); + addCurrentSchema(metadata_object, current_schema, next_schema_id); + if (type_changed || annotation_changed) + Iceberg::setClickHouseTypeAnnotation(metadata_object, target_field_id, next_schema_id, getClickHouseTypeAnnotation(type)); return true; } @@ -1098,10 +1082,7 @@ void MetadataGenerator::generateRenameColumnMetadata(const String & column_name, if (!found) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not found column {}", column_name); - const auto next_schema_id = getNextSchemaId(metadata_object); - metadata_object->set(Iceberg::f_current_schema_id, next_schema_id); - current_schema->set(Iceberg::f_schema_id, next_schema_id); - metadata_object->getArray(Iceberg::f_schemas)->add(current_schema); + addCurrentSchema(metadata_object, current_schema, getNextSchemaId(metadata_object)); } } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h index aeec2e00c8f33..022beafd67d9f 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h @@ -75,8 +75,15 @@ class MetadataGenerator /// Returns false when neither the type nor the position changed (true no-op). /// Throws when the requested type differs from the current one but maps to the same Iceberg type. /// `context` supplies the settings used to map the stored Iceberg type back to a ClickHouse - /// type (the timestamptz timezone and whether geo types are allowed). - bool generateModifyColumnMetadata(const String & column_name, DataTypePtr type, ContextPtr context, bool first = false, const String & after_column = {}); + /// type (the timestamptz timezone, whether geo types are allowed and, unless the table sets it + /// in `table_allow_aggregate_function_states`, whether aggregate function states are). + bool generateModifyColumnMetadata( + const String & column_name, + DataTypePtr type, + ContextPtr context, + bool first = false, + const String & after_column = {}, + std::optional table_allow_aggregate_function_states = std::nullopt); void generateRenameColumnMetadata(const String & column_name, const String & new_column_name); /// A commit attempt can land in the catalog even when the client observes a failure diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp index 47ddf975bdc11..4f91065064d83 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp @@ -835,6 +835,9 @@ void mutate( } } + /// Register the metadata.json schemas before the manifest headers carry copies of them without the type annotations. + addIcebergTableSchemasFromMetadata(metadata, *persistent_table_components.schema_processor, context); + /// Validate against the freshly-fetched snapshot. Bound to this exact /// metadata version, so a concurrent writer that commits non-Parquet /// data files between iterations is caught by the next retry. @@ -943,6 +946,9 @@ void alter( auto metadata = deepCopy(getMetadataJSONObject(metadata_path, object_storage, persistent_table_components.metadata_cache, context, log, compression_method, persistent_table_components.table_uuid)); const auto previous_schema_id = metadata->getValue(Iceberg::f_current_schema_id); + Poco::JSON::Object::Ptr previous_properties = metadata->has(Iceberg::f_properties) + ? new Poco::JSON::Object(*metadata->getObject(Iceberg::f_properties)) + : new Poco::JSON::Object; auto metadata_json_generator = MetadataGenerator(metadata); @@ -969,7 +975,13 @@ void alter( break; case AlterCommand::Type::MODIFY_COLUMN: { - if (!metadata_json_generator.generateModifyColumnMetadata(params[0].column_name, params[0].data_type, context, params[0].first, params[0].after_column)) + if (!metadata_json_generator.generateModifyColumnMetadata( + params[0].column_name, + params[0].data_type, + context, + params[0].first, + params[0].after_column, + getTableAllowAggregateFunctionStates(data_lake_settings))) { succeeded = true; } @@ -1034,7 +1046,9 @@ void alter( metadata->getValue(Iceberg::f_last_column_id), getHighestFieldId(new_schema)); commit_attempted = true; - if (!catalog->updateSchema(namespace_name, table_name, catalog_filename, new_schema, previous_schema_id, new_last_column_id, metadata, context->getForwardedAuthToken())) + if (!catalog->updateSchema( + namespace_name, table_name, catalog_filename, new_schema, previous_schema_id, new_last_column_id, metadata, + previous_properties, context->getForwardedAuthToken())) { ++i; continue; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/RemoveOrphanFilesExecute.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/RemoveOrphanFilesExecute.cpp index 715a7e98bcf36..4a9dbf053f29c 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/RemoveOrphanFilesExecute.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/RemoveOrphanFilesExecute.cpp @@ -385,6 +385,9 @@ Pipe executeRemoveOrphanFiles( params.location = parsed.getAs("location"); params.dry_run = parsed.getAs("dry_run") != 0; + /// Register the metadata.json schemas before the manifest headers carry copies of them without the type annotations. + addIcebergTableSchemasFromMetadata(latest_metadata, *persistent_components.schema_processor, context); + auto result = removeOrphanFiles(params, context, object_storage, data_lake_settings, persistent_components, external_storages); return resultToPipe(result); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp index ebe8ef683883b..e01261058d239 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -45,6 +46,7 @@ #include #include +#include namespace DB { @@ -54,6 +56,7 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; extern const int ICEBERG_SPECIFICATION_VIOLATION; +extern const int SUPPORT_IS_DISABLED; } namespace Setting @@ -444,6 +447,23 @@ std::pair parseDecimal(const String & type_name) return {precision, scale}; } +/// The ClickHouse type recorded for an Iceberg field, gated by the table's own setting or, if it has none, the query's. +DataTypePtr resolveFieldTypeAnnotation(Int32 field_id, const String & type_name, std::optional table_allow, const ContextPtr & context) +{ + auto type = resolveClickHouseTypeAnnotation(type_name, allowAggregateFunctionStates(table_allow, context)); + if (!type) + throw Exception( + ErrorCodes::SUPPORT_IS_DISABLED, + "Iceberg field with id {} records ClickHouse type {} in table properties `{}.{}.`, which has aggregate " + "function states: enable setting allow_aggregate_function_states_in_open_formats in the table's SETTINGS or, if the " + "table does not set it, in the query", + field_id, + type_name, + Iceberg::f_clickhouse_type, + field_id); + return type; +} + } namespace Iceberg @@ -455,13 +475,18 @@ void IcebergSchemaProcessor::dropCachedSchema(Int32 schema_id) { iceberg_table_schemas_by_ids.erase(schema_id); clickhouse_table_schemas_by_ids.erase(schema_id); + clickhouse_type_annotations_by_schema_ids.erase(schema_id); std::erase_if(transform_dags_by_ids, [schema_id](const auto & item) { return item.first.first == schema_id || item.first.second == schema_id; }); std::erase_if(clickhouse_types_by_source_ids, [schema_id](const auto & item) { return item.first.first == schema_id; }); std::erase_if(clickhouse_ids_by_source_names, [schema_id](const auto & item) { return item.first.first == schema_id; }); } void IcebergSchemaProcessor::addIcebergTableSchema( - Poco::JSON::Object::Ptr schema_ptr, ContextPtr context_, SchemaSource source, bool tolerate_conflicting_manifest_schemas) + Poco::JSON::Object::Ptr schema_ptr, + ContextPtr context_, + const ClickHouseTypeAnnotations & clickhouse_type_annotations, + SchemaSource source, + bool tolerate_conflicting_manifest_schemas) { Int32 schema_id = schema_ptr->getValue(f_schema_id); @@ -470,6 +495,12 @@ void IcebergSchemaProcessor::addIcebergTableSchema( if (!schema_ptr->isArray(f_fields) || schema_ptr->getArray(f_fields)->size() == 0) return; + auto schema_annotations = getClickHouseTypeAnnotationsOfSchema(schema_ptr, clickhouse_type_annotations); + + /// Checked on every call, including for an already registered schema: unless the table sets it, the setting belongs to the current query. + for (const auto & [field_id, annotation] : schema_annotations) + resolveFieldTypeAnnotation(field_id, annotation.type_name, table_allow_aggregate_function_states, context_); + std::unordered_map type_mapping; if (allow_geo_parser) { @@ -486,7 +517,8 @@ void IcebergSchemaProcessor::addIcebergTableSchema( const bool registered_from_manifest = manifest_sourced_schema_ids.contains(schema_id); if (source == SchemaSource::ManifestFile && tolerate_conflicting_manifest_schemas && !registered_from_manifest) return; - if (source == SchemaSource::ManifestFile || !registered_from_manifest) + if (source == SchemaSource::ManifestFile + || (!registered_from_manifest && clickHouseTypeAnnotationsUnchanged(schema_id, schema_annotations))) registered_schema = it->second; } } @@ -495,7 +527,12 @@ void IcebergSchemaProcessor::addIcebergTableSchema( std::lock_guard lock(mutex); - if (iceberg_table_schemas_by_ids.contains(schema_id)) + /// Table properties changed the ClickHouse types of an already registered schema: it is replaced once the new copy parsed. + const bool replace_registered_schema = source == SchemaSource::Metadata && iceberg_table_schemas_by_ids.contains(schema_id) + && schemasAreIdentical(*iceberg_table_schemas_by_ids.at(schema_id), *schema_ptr, type_mapping) + && !clickHouseTypeAnnotationsUnchanged(schema_id, schema_annotations); + + if (!replace_registered_schema && iceberg_table_schemas_by_ids.contains(schema_id)) { chassert(clickhouse_table_schemas_by_ids.contains(schema_id)); if (schemasAreIdentical(*iceberg_table_schemas_by_ids.at(schema_id), *schema_ptr, type_mapping)) @@ -568,6 +605,15 @@ void IcebergSchemaProcessor::addIcebergTableSchema( } current_schema_id = schema_id; + const auto reset_parse_state = make_scope_guard( + [&]() TSA_NO_THREAD_SAFETY_ANALYSIS + { + /// TSA cannot see the lock held by the caller through this lambda. + current_schema_id = std::nullopt; + parsed_clickhouse_types_by_source_ids.clear(); + parsed_clickhouse_ids_by_source_names.clear(); + }); + auto clickhouse_schema = std::make_shared(); String current_full_name{}; for (size_t i = 0; i != fields->size(); ++i) @@ -576,16 +622,26 @@ void IcebergSchemaProcessor::addIcebergTableSchema( auto name = field->getValue(f_name); bool required = field->getValue(f_required); current_full_name = name; - auto type = getFieldType(field, f_type, context_, required, current_full_name, true); + auto type = getFieldType(field, f_type, context_, schema_annotations, required, current_full_name, true); clickhouse_schema->push_back(NameAndTypePair{name, type}); - clickhouse_types_by_source_ids[{schema_id, field->getValue(f_id)}] = NameAndTypePair{current_full_name, type}; - clickhouse_ids_by_source_names[{schema_id, current_full_name}] = field->getValue(f_id); + parsed_clickhouse_types_by_source_ids[{schema_id, field->getValue(f_id)}] = NameAndTypePair{current_full_name, type}; + parsed_clickhouse_ids_by_source_names[{schema_id, current_full_name}] = field->getValue(f_id); } + + if (replace_registered_schema) + { + dropCachedSchema(schema_id); + manifest_sourced_schema_ids.erase(schema_id); + } + for (auto & [key, value] : parsed_clickhouse_types_by_source_ids) + clickhouse_types_by_source_ids[key] = std::move(value); + for (auto & [key, value] : parsed_clickhouse_ids_by_source_names) + clickhouse_ids_by_source_names[key] = value; clickhouse_table_schemas_by_ids[schema_id] = clickhouse_schema; iceberg_table_schemas_by_ids[schema_id] = schema_ptr; + clickhouse_type_annotations_by_schema_ids[schema_id] = std::move(schema_annotations); if (source == SchemaSource::ManifestFile) manifest_sourced_schema_ids.insert(schema_id); - current_schema_id = std::nullopt; } NameAndTypePair IcebergSchemaProcessor::getFieldCharacteristics(Int32 schema_version, Int32 source_id) const @@ -711,6 +767,7 @@ IcebergSchemaProcessor::getComplexTypeFromObject( const Poco::JSON::Object::Ptr & type, String & current_full_name, ContextPtr context_, + const ClickHouseTypeAnnotations & clickhouse_type_annotations, bool is_subfield_of_root) { /// The schema comes from the table metadata and can be nested arbitrarily deeply. @@ -720,15 +777,15 @@ IcebergSchemaProcessor::getComplexTypeFromObject( if (type_name == f_list) { bool element_required = type->getValue("element-required"); - auto element_type = getFieldType(type, f_element, context_, element_required); + auto element_type = getFieldType(type, f_element, context_, clickhouse_type_annotations, element_required); return std::make_shared(element_type); } if (type_name == f_map) { - auto key_type = getFieldType(type, f_key, context_, true); + auto key_type = getFieldType(type, f_key, context_, clickhouse_type_annotations, true); auto value_required = type->getValue("value-required"); - auto value_type = getFieldType(type, f_value, context_, value_required); + auto value_type = getFieldType(type, f_value, context_, clickhouse_type_annotations, value_required); return std::make_shared(key_type, value_type); } @@ -752,16 +809,16 @@ IcebergSchemaProcessor::getComplexTypeFromObject( (current_full_name += ".").append(element_names.back()); scope_guard guard([&] { current_full_name.resize(current_full_name.size() - element_names.back().size() - 1); }); - element_types.push_back(getFieldType(field, f_type, context_, required, current_full_name, true)); - TSA_SUPPRESS_WARNING_FOR_WRITE(clickhouse_types_by_source_ids) + element_types.push_back(getFieldType(field, f_type, context_, clickhouse_type_annotations, required, current_full_name, true)); + TSA_SUPPRESS_WARNING_FOR_WRITE(parsed_clickhouse_types_by_source_ids) [{schema_id, field->getValue(f_id)}] = NameAndTypePair{current_full_name, element_types.back()}; - TSA_SUPPRESS_WARNING_FOR_WRITE(clickhouse_ids_by_source_names) + TSA_SUPPRESS_WARNING_FOR_WRITE(parsed_clickhouse_ids_by_source_names) [{schema_id, current_full_name}] = field->getValue(f_id); } else { - element_types.push_back(getFieldType(field, f_type, context_, required)); + element_types.push_back(getFieldType(field, f_type, context_, clickhouse_type_annotations, required)); } } @@ -775,27 +832,67 @@ DataTypePtr IcebergSchemaProcessor::getFieldType( const Poco::JSON::Object::Ptr & field, const String & type_key, ContextPtr context_, + const ClickHouseTypeAnnotations & clickhouse_type_annotations, bool required, String & current_full_name, bool is_subfield_of_root) { + DataTypePtr derived_type; if (field->isObject(type_key)) - return getComplexTypeFromObject(field->getObject(type_key), current_full_name, context_, is_subfield_of_root); + derived_type = getComplexTypeFromObject( + field->getObject(type_key), current_full_name, context_, clickhouse_type_annotations, is_subfield_of_root); + else + { + auto type = field->get(type_key); + if (!type.isString()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected 'type' field: {}", type.toString()); - auto type = field->get(type_key); - if (type.isString()) + derived_type = getSimpleType(type.extract(), context_, allow_geo_parser); + if (!required && derived_type->canBeInsideNullable()) + derived_type = makeNullable(derived_type); + } + + if (!field->has(f_id)) + return derived_type; + + const Int32 field_id = field->getValue(f_id); + auto annotation_it = clickhouse_type_annotations.find(field_id); + if (annotation_it == clickhouse_type_annotations.end()) + return derived_type; + + const auto & annotation = annotation_it->second; + const String & annotated_name = annotation.type_name; + auto annotated_type = resolveFieldTypeAnnotation(field_id, annotated_name, table_allow_aggregate_function_states, context_); + + /// The annotation is valid only for the Iceberg type ClickHouse writes for it. The format version affects only + /// whether `timestamp_ns` may be written, so the latest one is used and the field's own type decides. + Int32 unused_field_id = 0; + const auto [annotated_iceberg_type, annotated_required] + = getIcebergType(annotated_type, unused_field_id, /*format_version=*/ 3); + if (annotated_required != required || !icebergTypesEqualIgnoringIds(field->get(type_key), annotated_iceberg_type)) { - const String & type_name = type.extract(); - auto data_type = getSimpleType(type_name, context_, allow_geo_parser); - return required || !data_type->canBeInsideNullable() ? data_type : makeNullable(data_type); + /// The field has evolved since the annotation was recorded for a lower schema id, e.g. another engine + /// promoted `int` to `long` or made the field optional. + if (annotation.inherited) + return derived_type; + + throw Exception( + ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, + "Iceberg field '{}' records ClickHouse type {} in table properties `{}.{}.`, but the field itself reads as {}", + field->has(f_name) ? field->getValue(f_name) : type_key, + annotated_name, + f_clickhouse_type, + field_id, + derived_type->getName()); } - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected 'type' field: {}", type.toString()); + return annotated_type; } -DataTypePtr IcebergSchemaProcessor::getClickHouseFieldType(const Poco::JSON::Object::Ptr & field, ContextPtr context_) +DataTypePtr IcebergSchemaProcessor::getClickHouseFieldType( + const Poco::JSON::Object::Ptr & field, const ClickHouseTypeAnnotations & clickhouse_type_annotations, ContextPtr context_) { - return getFieldType(field, f_type, context_, field->getValue(f_required)); + return getFieldType(field, f_type, context_, clickhouse_type_annotations, field->getValue(f_required)); } /** @@ -828,6 +925,8 @@ bool IcebergSchemaProcessor::allowPrimitiveTypeConversion(const String & old_typ std::shared_ptr IcebergSchemaProcessor::getSchemaTransformationDag( const Poco::JSON::Object::Ptr & old_schema, const Poco::JSON::Object::Ptr & new_schema, + const ClickHouseTypeAnnotations & old_annotations, + const ClickHouseTypeAnnotations & new_annotations, ContextPtr context_, Int32 old_id, Int32 new_id) @@ -842,7 +941,7 @@ std::shared_ptr IcebergSchemaProcessor::getSchemaTransformationDag( size_t id = field->getValue(f_id); auto name = field->getValue(f_name); bool required = field->getValue(f_required); - old_schema_entries[id] = {field, &dag->addInput(name, getFieldType(field, f_type, context_, required))}; + old_schema_entries[id] = {field, &dag->addInput(name, getFieldType(field, f_type, context_, old_annotations, required))}; } auto new_schema_fields = new_schema->get(f_fields).extract(); for (size_t i = 0; i != new_schema_fields->size(); ++i) @@ -851,7 +950,7 @@ std::shared_ptr IcebergSchemaProcessor::getSchemaTransformationDag( size_t id = field->getValue(f_id); auto name = field->getValue(f_name); bool required = field->getValue(f_required); - auto type = getFieldType(field, f_type, context_, required); + auto type = getFieldType(field, f_type, context_, new_annotations, required); auto old_node_it = old_schema_entries.find(id); if (old_node_it != old_schema_entries.end()) { @@ -870,7 +969,7 @@ std::shared_ptr IcebergSchemaProcessor::getSchemaTransformationDag( old_id, new_id); } - auto old_type = getFieldType(old_json, "type", context_, required); + auto old_type = getFieldType(old_json, "type", context_, old_annotations, required); auto transform = std::make_shared(DataTypes{type}, DataTypes{old_type}, old_json, field); old_node = &dag->addFunction(transform, std::vector{old_node}, name); @@ -911,7 +1010,7 @@ std::shared_ptr IcebergSchemaProcessor::getSchemaTransformationDag( } else if (allowPrimitiveTypeConversion(old_type, new_type)) { - node = &dag->addCast(*old_node, getFieldType(field, f_type, context_, required), name, nullptr); + node = &dag->addCast(*old_node, getFieldType(field, f_type, context_, new_annotations, required), name, nullptr); } outputs.push_back(node); } @@ -960,8 +1059,14 @@ std::shared_ptr IcebergSchemaProcessor::getSchemaTransformatio if (new_schema_it == iceberg_table_schemas_by_ids.end()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Schema with schema-id {} is unknown", new_id); - return transform_dags_by_ids[{old_id, new_id}] - = getSchemaTransformationDag(old_schema_it->second, new_schema_it->second, context_, old_id, new_id); + return transform_dags_by_ids[{old_id, new_id}] = getSchemaTransformationDag( + old_schema_it->second, + new_schema_it->second, + clickhouse_type_annotations_by_schema_ids.at(old_id), + clickhouse_type_annotations_by_schema_ids.at(new_id), + context_, + old_id, + new_id); } Poco::JSON::Object::Ptr IcebergSchemaProcessor::getIcebergTableSchemaById(Int32 id) const @@ -1038,6 +1143,14 @@ bool IcebergSchemaProcessor::isSchemaRegisteredFromMetadata(Int32 id) const return iceberg_table_schemas_by_ids.contains(id) && !manifest_sourced_schema_ids.contains(id); } +bool IcebergSchemaProcessor::hasClickHouseTypeAnnotation(Int32 schema_id, Int32 field_id) const +{ + SharedLockGuard lock(mutex); + + auto it = clickhouse_type_annotations_by_schema_ids.find(schema_id); + return it != clickhouse_type_annotations_by_schema_ids.end() && it->second.contains(field_id); +} + std::unordered_map IcebergSchemaProcessor::traverseSchema(Poco::JSON::Array::Ptr schema) { std::unordered_map result; @@ -1099,6 +1212,26 @@ void IcebergSchemaProcessor::updateLastColumnId(Int32 last_column_id_) ; } +ClickHouseTypeAnnotations IcebergSchemaProcessor::getClickHouseTypeAnnotationsOfSchema( + const Poco::JSON::Object::Ptr & schema, const ClickHouseTypeAnnotations & clickhouse_type_annotations) +{ + ClickHouseTypeAnnotations result; + if (clickhouse_type_annotations.empty()) + return result; + for (const auto & name_and_id : traverseSchema(schema->getArray(f_fields))) + { + if (auto it = clickhouse_type_annotations.find(static_cast(name_and_id.second)); it != clickhouse_type_annotations.end()) + result.emplace(it->first, it->second); + } + return result; +} + +bool IcebergSchemaProcessor::clickHouseTypeAnnotationsUnchanged(Int32 schema_id, const ClickHouseTypeAnnotations & schema_annotations) const +{ + auto it = clickhouse_type_annotations_by_schema_ids.find(schema_id); + return it != clickhouse_type_annotations_by_schema_ids.end() && it->second == schema_annotations; +} + ColumnMapperPtr IcebergSchemaProcessor::getColumnMapperById(Int32 id) const { auto schema = getIcebergTableSchemaById(id); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.h index 541e4ec46a32e..dcb5853f76808 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.h @@ -1,6 +1,7 @@ #pragma once +#include #include #include @@ -28,6 +29,20 @@ ColumnMapperPtr createColumnMapperFromFields(Poco::JSON::Array::Ptr fields); ColumnMapperPtr createColumnMapper(Poco::JSON::Object::Ptr schema_object); +/// A ClickHouse type name recorded in a `clickhouse.type..` table property. +struct ClickHouseTypeAnnotation +{ + String type_name; + /// Recorded for a lower schema id. Another engine may have evolved the field since then, + /// so it applies only while the field keeps the Iceberg type `type_name` is stored as. + bool inherited = false; + + bool operator==(const ClickHouseTypeAnnotation &) const = default; +}; + +/// ClickHouse type annotations in effect for the fields of a schema, by field id. +using ClickHouseTypeAnnotations = std::map; + /** * Iceberg supports the following data types (see https://iceberg.apache.org/spec/#schemas-and-data-types): * - Primitive types: @@ -99,12 +114,19 @@ class IcebergSchemaProcessor : private WithContext ManifestFile, }; - explicit IcebergSchemaProcessor(ContextPtr context_, bool allow_geo_parser_ = false) - : WithContext(context_), allow_geo_parser(allow_geo_parser_) {} + explicit IcebergSchemaProcessor( + ContextPtr context_, bool allow_geo_parser_ = false, std::optional table_allow_aggregate_function_states_ = std::nullopt) + : WithContext(context_) + , allow_geo_parser(allow_geo_parser_) + , table_allow_aggregate_function_states(table_allow_aggregate_function_states_) + { + } + /// `clickhouse_type_annotations` are the ones in effect for the schema in the table metadata it belongs to. void addIcebergTableSchema( Poco::JSON::Object::Ptr schema_ptr, ContextPtr context_, + const ClickHouseTypeAnnotations & clickhouse_type_annotations, SchemaSource source = SchemaSource::Metadata, bool tolerate_conflicting_manifest_schemas = false); std::shared_ptr getClickHouseTableSchemaById(Int32 id); @@ -116,11 +138,14 @@ class IcebergSchemaProcessor : private WithContext Poco::JSON::Object::Ptr getIcebergTableSchemaById(Int32 id) const; bool hasClickHouseTableSchemaById(Int32 id) const; bool isSchemaRegisteredFromMetadata(Int32 id) const; + /// Whether the type of `field_id` in schema `schema_id` comes from a `clickhouse.type` table property. + bool hasClickHouseTypeAnnotation(Int32 schema_id, Int32 field_id) const; static DataTypePtr getSimpleType(const String & type_name, ContextPtr context_, bool allow_geo_parser = true); /// The ClickHouse type the reader derives for a top-level schema field. - DataTypePtr getClickHouseFieldType(const Poco::JSON::Object::Ptr & field, ContextPtr context_); + DataTypePtr getClickHouseFieldType( + const Poco::JSON::Object::Ptr & field, const ClickHouseTypeAnnotations & clickhouse_type_annotations, ContextPtr context_); static std::unordered_map traverseSchema(Poco::JSON::Array::Ptr schema); @@ -151,28 +176,41 @@ class IcebergSchemaProcessor : private WithContext mutable std::map, NameAndTypePair> clickhouse_types_by_source_ids TSA_GUARDED_BY(mutex); mutable std::map, Int32> clickhouse_ids_by_source_names TSA_GUARDED_BY(mutex); std::optional current_schema_id TSA_GUARDED_BY(mutex) = 0; + /// Per-field lookups of the schema `addIcebergTableSchema` is parsing, installed only once the whole schema parsed. + std::map, NameAndTypePair> parsed_clickhouse_types_by_source_ids TSA_GUARDED_BY(mutex); + std::map, Int32> parsed_clickhouse_ids_by_source_names TSA_GUARDED_BY(mutex); std::unordered_map schema_id_by_snapshot TSA_GUARDED_BY(mutex); /// Schema-ids whose registered copy came from a manifest file header and has not been confirmed /// by an identical metadata.json copy yet. Such a copy is replaced when metadata.json binds the /// schema-id to a different schema, and two manifest headers disagreeing on such a schema-id is /// an error, because no authoritative copy is left to decide between them. std::unordered_set manifest_sourced_schema_ids TSA_GUARDED_BY(mutex); + /// The annotations each registered schema was parsed with. + std::unordered_map clickhouse_type_annotations_by_schema_ids TSA_GUARDED_BY(mutex); /// Forget the schema registered for `schema_id` together with everything derived from it: the /// per-field lookups and the cached schema transformation DAGs in either direction. They are /// keyed by schema-id and never rebuilt once populated, so a stale entry would keep answering. void dropCachedSchema(Int32 schema_id) TSA_REQUIRES(mutex); + /// The subset of `clickhouse_type_annotations` that refers to the fields of `schema`. + static ClickHouseTypeAnnotations getClickHouseTypeAnnotationsOfSchema( + const Poco::JSON::Object::Ptr & schema, const ClickHouseTypeAnnotations & clickhouse_type_annotations); + bool clickHouseTypeAnnotationsUnchanged(Int32 schema_id, const ClickHouseTypeAnnotations & schema_annotations) const + TSA_REQUIRES_SHARED(mutex); + NamesAndTypesList getSchemaType(const Poco::JSON::Object::Ptr & schema); DataTypePtr getComplexTypeFromObject( const Poco::JSON::Object::Ptr & type, String & current_full_name, ContextPtr context_, + const ClickHouseTypeAnnotations & clickhouse_type_annotations, bool is_subfield_of_root); DataTypePtr getFieldType( const Poco::JSON::Object::Ptr & field, const String & type_key, ContextPtr context_, + const ClickHouseTypeAnnotations & clickhouse_type_annotations, bool required, String & current_full_name = default_link, bool is_subfield_of_root = false); @@ -183,12 +221,16 @@ class IcebergSchemaProcessor : private WithContext std::shared_ptr getSchemaTransformationDag( const Poco::JSON::Object::Ptr & old_schema, const Poco::JSON::Object::Ptr & new_schema, + const ClickHouseTypeAnnotations & old_annotations, + const ClickHouseTypeAnnotations & new_annotations, ContextPtr context_, Int32 old_id, Int32 new_id); mutable SharedMutex mutex; bool allow_geo_parser = true; + /// The table's own `allow_aggregate_function_states_in_open_formats`; when not set, the query's value decides. + std::optional table_allow_aggregate_function_states; }; using IcebergSchemaProcessorPtr = std::shared_ptr; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp index 4fef118fbe08e..f14ea6109e320 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -54,10 +56,263 @@ #include #include +#include + +namespace DB::ErrorCodes +{ +extern const int BAD_ARGUMENTS; +} + +namespace DB::Iceberg +{ + +/// Returns type and required +std::pair getIcebergType(DataTypePtr type, Int32 & iter, UInt64 format_version) +{ + switch (type->getTypeId()) + { + case TypeIndex::UInt8: + { + if (isBool(type)) + return {"boolean", true}; + return {"int", true}; + } + case TypeIndex::Int8: + case TypeIndex::UInt16: + case TypeIndex::Int16: + case TypeIndex::UInt32: + case TypeIndex::Int32: + return {"int", true}; + case TypeIndex::UInt64: + case TypeIndex::Int64: + return {"long", true}; + case TypeIndex::Float32: + return {"float", true}; + case TypeIndex::Float64: + return {"double", true}; + case TypeIndex::Date: + case TypeIndex::Date32: + return {"date", true}; + case TypeIndex::DateTime: + return {"timestamp", true}; + case TypeIndex::DateTime64: + { + /// Iceberg `timestamp` is microseconds; `timestamp_ns` is nanoseconds and is + /// allowed only in format version 3. Writing it into v1/v2 metadata is invalid. + const auto scale = getDecimalScale(*type); + if (scale == 9) + { + if (format_version < 3) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Iceberg type {} requires format version 3 or higher, got version {}", + type->getName(), + format_version); + + auto date_time64 = std::static_pointer_cast(type); + if (date_time64->hasExplicitTimeZone()) + return {Iceberg::f_timestamptz_ns, true}; + return {Iceberg::f_timestamp_ns, true}; + } + if (scale <= 6) + return {Iceberg::f_timestamp, true}; + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); + } + case TypeIndex::Time: + return {"time", true}; + case TypeIndex::Time64: + if (getDecimalScale(*type) <= 6) + return {"time", true}; + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); + case TypeIndex::String: + return {"string", true}; + case TypeIndex::AggregateFunction: + return {Iceberg::f_binary, true}; + case TypeIndex::UUID: + return {"uuid", true}; + case TypeIndex::Nothing: + return {"unknown", false}; + case TypeIndex::Decimal32: + case TypeIndex::Decimal64: + case TypeIndex::Decimal128: + case TypeIndex::Decimal256: + { + auto precision = getDecimalPrecision(*type); + if (precision > 38) + throw Exception(ErrorCodes::BAD_ARGUMENTS, + "Iceberg decimal type supports precision up to 38, got {}", precision); + return {"decimal(" + std::to_string(precision) + ", " + std::to_string(getDecimalScale(*type)) + ")", true}; + } + case TypeIndex::Tuple: + { + auto type_tuple = std::static_pointer_cast(type); + Poco::JSON::Object::Ptr result = new Poco::JSON::Object; + result->set(Iceberg::f_type, "struct"); + Poco::JSON::Array::Ptr fields = new Poco::JSON::Array; + size_t iter_names = 1; + size_t iter_fields = iter; + iter += type_tuple->getElements().size(); + for (const auto & element : type_tuple->getElements()) + { + Poco::JSON::Object::Ptr field = new Poco::JSON::Object; + field->set(Iceberg::f_id, ++iter_fields); + field->set(Iceberg::f_name, type_tuple->getNameByPosition(iter_names)); + /// Recurse on the element itself: `getNormalizedType` would rename a nested + /// tuple's elements to "1", "2", ... (`DataTypeTuple::getNormalizedType`). + auto child_type = getIcebergType(element, iter, format_version); + field->set(Iceberg::f_required, child_type.second); + field->set(Iceberg::f_type, child_type.first); + fields->add(field); + ++iter_names; + } + result->set(Iceberg::f_fields, fields); + return {result, true}; + } + case TypeIndex::Array: + { + auto type_array = std::static_pointer_cast(type); + Poco::JSON::Object::Ptr field = new Poco::JSON::Object; + + field->set(Iceberg::f_type, "list"); + field->set(Iceberg::f_element_id, ++iter); + auto child_type = getIcebergType(type_array->getNestedType(), iter, format_version); + field->set(Iceberg::f_required, false); + field->set(Iceberg::f_element, child_type.first); + field->set(Iceberg::f_element_required, child_type.second); + return {field, true}; + } + case TypeIndex::Map: + { + auto type_map = std::static_pointer_cast(type); + Poco::JSON::Object::Ptr field = new Poco::JSON::Object; + + field->set(Iceberg::f_type, "map"); + field->set(Iceberg::f_key_id, ++iter); + field->set(Iceberg::f_value_id, ++iter); + + field->set(Iceberg::f_key, getIcebergType(type_map->getKeyType(), iter, format_version).first); + auto value_type = getIcebergType(type_map->getValueType(), iter, format_version); + field->set(Iceberg::f_value, value_type.first); + field->set(Iceberg::f_value_required, value_type.second); + return {field, true}; + } + case TypeIndex::Nullable: + { + auto type_nullable = std::static_pointer_cast(type); + return {getIcebergType(type_nullable->getNestedType(), iter, format_version).first, false}; + } + case TypeIndex::Variant: + { + if (type->getCustomName() && type->getCustomName()->getName() == "Geometry") + return {Iceberg::f_geometry, false}; + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); + } + default: + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); + } +} + +namespace +{ + +String removeASCIIWhitespace(const String & s) +{ + String result; + result.reserve(s.size()); + for (char c : s) + { + if (!isWhitespaceASCII(c)) + result.push_back(c); + } + return result; +} + +/// A missing key matches only a missing key. +bool optionalBoolsEqual(const Poco::JSON::Object::Ptr & first, const Poco::JSON::Object::Ptr & second, const char * key) +{ + const bool first_has = first->has(key); + if (first_has != second->has(key)) + return false; + return !first_has || first->getValue(key) == second->getValue(key); +} + +} + +/// Only the properties that define the type are compared. Field ids are ignored because +/// `getIcebergType` allocates them from a running counter, so a previous attempt may have written +/// the very same type with lower ids. Other keys (`doc`, defaults, the `required` that +/// `getIcebergType` puts on a list) are ignored because other writers emit or omit them freely. +bool icebergTypesEqualIgnoringIds(Poco::Dynamic::Var old_type, Poco::Dynamic::Var new_type) +{ + if (old_type.isString() || new_type.isString()) + { + if (!old_type.isString() || !new_type.isString()) + return false; + /// Writers differ in spacing, e.g. `decimal(10,2)` and `decimal(10, 2)`. + return removeASCIIWhitespace(old_type.extract()) == removeASCIIWhitespace(new_type.extract()); + } + + if (old_type.type() != typeid(Poco::JSON::Object::Ptr) || new_type.type() != typeid(Poco::JSON::Object::Ptr)) + return false; + + auto old_object = old_type.extract(); + auto new_object = new_type.extract(); + if (!old_object || !new_object) + return false; + + if (old_object->has("precision") || new_object->has("precision")) + { + return old_object->has("precision") && new_object->has("precision") + && old_object->getValue("precision") == new_object->getValue("precision") + && old_object->getValue("scale") == new_object->getValue("scale"); + } + + if (!old_object->has(Iceberg::f_type) || !new_object->has(Iceberg::f_type)) + return false; + const auto kind = old_object->getValue(Iceberg::f_type); + if (kind != new_object->getValue(Iceberg::f_type)) + return false; + + if (kind == Iceberg::f_list) + { + return optionalBoolsEqual(old_object, new_object, Iceberg::f_element_required) + && icebergTypesEqualIgnoringIds(old_object->get(Iceberg::f_element), new_object->get(Iceberg::f_element)); + } + + if (kind == Iceberg::f_map) + { + return optionalBoolsEqual(old_object, new_object, Iceberg::f_value_required) + && icebergTypesEqualIgnoringIds(old_object->get(Iceberg::f_key), new_object->get(Iceberg::f_key)) + && icebergTypesEqualIgnoringIds(old_object->get(Iceberg::f_value), new_object->get(Iceberg::f_value)); + } + + if (kind == Iceberg::f_struct) + { + auto old_fields = old_object->getArray(Iceberg::f_fields); + auto new_fields = new_object->getArray(Iceberg::f_fields); + if (!old_fields || !new_fields || old_fields->size() != new_fields->size()) + return false; + for (UInt32 i = 0; i < old_fields->size(); ++i) + { + auto old_field = old_fields->getObject(i); + auto new_field = new_fields->getObject(i); + if (!old_field || !new_field + || old_field->getValue(Iceberg::f_name) != new_field->getValue(Iceberg::f_name) + || !optionalBoolsEqual(old_field, new_field, Iceberg::f_required) + || !icebergTypesEqualIgnoringIds(old_field->get(Iceberg::f_type), new_field->get(Iceberg::f_type))) + return false; + } + return true; + } + + return false; +} + +} + #if USE_AVRO #include -#include #include #include #include @@ -84,7 +339,6 @@ using namespace DB; namespace DB::ErrorCodes { extern const int FILE_DOESNT_EXIST; -extern const int BAD_ARGUMENTS; extern const int ICEBERG_SPECIFICATION_VIOLATION; extern const int LOGICAL_ERROR; extern const int UNSUPPORTED_METHOD; @@ -97,6 +351,7 @@ namespace DB::DataLakeStorageSetting extern const DataLakeStorageSettingsBool iceberg_recent_metadata_file_by_last_updated_ms_field; extern const DataLakeStorageSettingsBool iceberg_use_version_hint; extern const DataLakeStorageSettingsNonZeroUInt64 iceberg_format_version; + extern const DataLakeStorageSettingsBool allow_aggregate_function_states_in_open_formats; } namespace DB::Setting @@ -721,148 +976,80 @@ void checkUnknownTypeAllowed(const String & column_name, const DataTypePtr & typ column_name, type->getName(), format_version); } -/// Returns type and required -std::pair getIcebergType(DataTypePtr type, Int32 & iter, UInt64 format_version) +String getClickHouseTypePropertyKey(Int32 field_id, Int32 schema_id) { - switch (type->getTypeId()) - { - case TypeIndex::UInt8: - { - if (isBool(type)) - return {"boolean", true}; - return {"int", true}; - } - case TypeIndex::Int8: - case TypeIndex::UInt16: - case TypeIndex::Int16: - case TypeIndex::UInt32: - case TypeIndex::Int32: - return {"int", true}; - case TypeIndex::UInt64: - case TypeIndex::Int64: - return {"long", true}; - case TypeIndex::Float32: - return {"float", true}; - case TypeIndex::Float64: - return {"double", true}; - case TypeIndex::Date: - case TypeIndex::Date32: - return {"date", true}; - case TypeIndex::DateTime: - return {"timestamp", true}; - case TypeIndex::DateTime64: - { - /// Iceberg `timestamp` is microseconds; `timestamp_ns` is nanoseconds and is - /// allowed only in format version 3. Writing it into v1/v2 metadata is invalid. - const auto scale = getDecimalScale(*type); - if (scale == 9) - { - if (format_version < 3) - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Iceberg type {} requires format version 3 or higher, got version {}", - type->getName(), - format_version); + return fmt::format("{}.{}.{}", Iceberg::f_clickhouse_type, field_id, schema_id); +} - auto date_time64 = std::static_pointer_cast(type); - if (date_time64->hasExplicitTimeZone()) - return {Iceberg::f_timestamptz_ns, true}; - return {Iceberg::f_timestamp_ns, true}; - } - if (scale <= 6) - return {Iceberg::f_timestamp, true}; - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); - } - case TypeIndex::Time: - return {"time", true}; - case TypeIndex::Time64: - if (getDecimalScale(*type) <= 6) - return {"time", true}; - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); - case TypeIndex::String: - return {"string", true}; - case TypeIndex::UUID: - return {"uuid", true}; - case TypeIndex::Nothing: - return {"unknown", false}; - case TypeIndex::Decimal32: - case TypeIndex::Decimal64: - case TypeIndex::Decimal128: - case TypeIndex::Decimal256: - { - auto precision = getDecimalPrecision(*type); - if (precision > 38) - throw Exception(ErrorCodes::BAD_ARGUMENTS, - "Iceberg decimal type supports precision up to 38, got {}", precision); - return {"decimal(" + std::to_string(precision) + ", " + std::to_string(getDecimalScale(*type)) + ")", true}; - } - case TypeIndex::Tuple: - { - auto type_tuple = std::static_pointer_cast(type); - Poco::JSON::Object::Ptr result = new Poco::JSON::Object; - result->set(Iceberg::f_type, "struct"); - Poco::JSON::Array::Ptr fields = new Poco::JSON::Array; - size_t iter_names = 1; - size_t iter_fields = iter; - iter += type_tuple->getElements().size(); - for (const auto & element : type_tuple->getElements()) - { - Poco::JSON::Object::Ptr field = new Poco::JSON::Object; - field->set(Iceberg::f_id, ++iter_fields); - field->set(Iceberg::f_name, type_tuple->getNameByPosition(iter_names)); - /// Recurse on the element itself: `getNormalizedType` would rename a nested - /// tuple's elements to "1", "2", ... (`DataTypeTuple::getNormalizedType`). - auto child_type = getIcebergType(element, iter, format_version); - field->set(Iceberg::f_required, child_type.second); - field->set(Iceberg::f_type, child_type.first); - fields->add(field); - ++iter_names; - } - result->set(Iceberg::f_fields, fields); - return {result, true}; - } - case TypeIndex::Array: - { - auto type_array = std::static_pointer_cast(type); - Poco::JSON::Object::Ptr field = new Poco::JSON::Object; +ClickHouseTypeAnnotations getClickHouseTypeAnnotations(const Poco::JSON::Object::Ptr & metadata_object, Int32 schema_id) +{ + ClickHouseTypeAnnotations annotations; + if (!metadata_object->has(Iceberg::f_properties)) + return annotations; + const auto properties = metadata_object->getObject(Iceberg::f_properties); + const String prefix = String(Iceberg::f_clickhouse_type) + "."; + /// For each field, the schema id of the entry in effect and its value. + std::map> entries; + for (const auto & [key, value] : *properties) + { + if (!key.starts_with(prefix)) + continue; + /// Only keys whose suffix is `.` are annotations + const std::string_view suffix = std::string_view(key).substr(prefix.size()); + const size_t dot = suffix.find('.'); + Int32 field_id; + Int32 entry_schema_id; + if (dot == std::string_view::npos || !tryParse(field_id, suffix.substr(0, dot)) + || !tryParse(entry_schema_id, suffix.substr(dot + 1)) || entry_schema_id > schema_id) + continue; + auto [it, inserted] = entries.try_emplace(field_id, entry_schema_id, value.toString()); + if (!inserted && it->second.first < entry_schema_id) + it->second = {entry_schema_id, value.toString()}; + } + for (auto & [field_id, entry] : entries) + { + if (!entry.second.empty()) + annotations.emplace( + field_id, ClickHouseTypeAnnotation{.type_name = std::move(entry.second), .inherited = entry.first < schema_id}); + } + return annotations; +} - field->set(Iceberg::f_type, "list"); - field->set(Iceberg::f_element_id, ++iter); - auto child_type = getIcebergType(type_array->getNestedType(), iter, format_version); - field->set(Iceberg::f_required, false); - field->set(Iceberg::f_element, child_type.first); - field->set(Iceberg::f_element_required, child_type.second); - return {field, true}; - } - case TypeIndex::Map: - { - auto type_map = std::static_pointer_cast(type); - Poco::JSON::Object::Ptr field = new Poco::JSON::Object; +void setClickHouseTypeAnnotation(Poco::JSON::Object::Ptr metadata_object, Int32 field_id, Int32 schema_id, const String & annotation) +{ + const auto key = getClickHouseTypePropertyKey(field_id, schema_id); + const auto inherited_annotations = getClickHouseTypeAnnotations(metadata_object, schema_id - 1); + const auto inherited = inherited_annotations.find(field_id); + const String & inherited_annotation = inherited == inherited_annotations.end() ? String{} : inherited->second.type_name; + if (annotation == inherited_annotation) + { + if (metadata_object->has(Iceberg::f_properties)) + metadata_object->getObject(Iceberg::f_properties)->remove(key); + return; + } - field->set(Iceberg::f_type, "map"); - field->set(Iceberg::f_key_id, ++iter); - field->set(Iceberg::f_value_id, ++iter); + if (!metadata_object->has(Iceberg::f_properties)) + metadata_object->set(Iceberg::f_properties, Poco::JSON::Object::Ptr(new Poco::JSON::Object)); + metadata_object->getObject(Iceberg::f_properties)->set(key, annotation); +} - field->set(Iceberg::f_key, getIcebergType(type_map->getKeyType(), iter, format_version).first); - auto value_type = getIcebergType(type_map->getValueType(), iter, format_version); - field->set(Iceberg::f_value, value_type.first); - field->set(Iceberg::f_value_required, value_type.second); - return {field, true}; - } - case TypeIndex::Nullable: - { - auto type_nullable = std::static_pointer_cast(type); - return {getIcebergType(type_nullable->getNestedType(), iter, format_version).first, false}; - } - case TypeIndex::Variant: - { - if (type->getCustomName() && type->getCustomName()->getName() == "Geometry") - return {Iceberg::f_geometry, false}; - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); - } - default: - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unsupported type for iceberg {}", type->getName()); +void addIcebergTableSchemasFromMetadata( + const Poco::JSON::Object::Ptr & metadata_object, IcebergSchemaProcessor & schema_processor, ContextPtr context) +{ + auto add_schema = [&](const Poco::JSON::Object::Ptr & schema) + { + schema_processor.addIcebergTableSchema( + schema, context, getClickHouseTypeAnnotations(metadata_object, schema->getValue(f_schema_id))); + }; + /// `schemas` is optional in format version 1, which keeps its only schema in the top-level `schema`. + if (!metadata_object->has(f_schemas)) + { + add_schema(parseTableSchemaV1Method(metadata_object).first); + return; } + auto schemas = metadata_object->getArray(f_schemas); + for (UInt32 i = 0; i < schemas->size(); ++i) + add_schema(schemas->getObject(i)); } Poco::Dynamic::Var getAvroType(DataTypePtr type, Int32 field_id) @@ -1353,6 +1540,8 @@ std::pair createEmptyMetadataFile( auto type = getIcebergType(column.type, iter, format_version); field->set(Iceberg::f_required, type.second); field->set(Iceberg::f_type, type.first); + if (auto annotation = getClickHouseTypeAnnotation(column.type); !annotation.empty()) + setClickHouseTypeAnnotation(new_metadata_file_content, iter_for_initial_columns, /*schema_id=*/ 0, annotation); column_name_to_source_id[column.name] = iter_for_initial_columns; schema_fields->add(field); } @@ -1615,6 +1804,14 @@ std::optional getMaxMetadataFileVersionInDirectory(const ObjectStoragePtr return max_version; } +std::optional getTableAllowAggregateFunctionStates(const DataLakeStorageSettings & data_lake_settings) +{ + const auto & setting = data_lake_settings[DataLakeStorageSetting::allow_aggregate_function_states_in_open_formats]; + if (!setting.changed) + return std::nullopt; + return setting.value; +} + MetadataFileWithInfo getLatestOrExplicitMetadataFileAndVersion( const ObjectStoragePtr & object_storage, const String & table_path, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.h index 397c47bb1b59c..2c5c1a70c36f7 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.h @@ -16,6 +16,20 @@ #include #include +#include + +namespace DB::Iceberg +{ + +/// Maps a ClickHouse type to an Iceberg JSON type. `timestamp_ns` / `timestamptz_ns` +/// require `format_version` >= 3; lower versions throw instead of writing v3 types +/// into v1/v2 metadata. +std::pair getIcebergType(DataTypePtr type, Int32 & iter, UInt64 format_version); + +/// Whether two Iceberg type descriptors denote the same type, ignoring the ids of nested fields. +bool icebergTypesEqualIgnoringIds(Poco::Dynamic::Var old_type, Poco::Dynamic::Var new_type); + +} #if USE_AVRO @@ -126,15 +140,25 @@ Poco::JSON::Object::Ptr parseMetadataJSONString(const String & metadata_json_str Poco::JSON::Object::Ptr deepCopy(const Poco::JSON::Object::Ptr & object); -/// Maps a ClickHouse type to an Iceberg JSON type. `timestamp_ns` / `timestamptz_ns` -/// require `format_version` >= 3; lower versions throw instead of writing v3 types -/// into v1/v2 metadata. -std::pair getIcebergType(DataTypePtr type, Int32 & iter, UInt64 format_version); - /// Throws if `type` contains `Nothing` at any depth (the Iceberg `unknown` type) and /// `format_version` is below 3, the first format version that defines `unknown`. void checkUnknownTypeAllowed(const String & column_name, const DataTypePtr & type, Int64 format_version); +/// Table property `clickhouse.type..` records a type Iceberg cannot express for the field, +/// effective from that schema id until the next property of the field. An empty value records no type. +String getClickHouseTypePropertyKey(Int32 field_id, Int32 schema_id); + +/// The annotations in effect for schema `schema_id`: per field, the property with the greatest schema id not above it. +ClickHouseTypeAnnotations getClickHouseTypeAnnotations(const Poco::JSON::Object::Ptr & metadata_object, Int32 schema_id); + +/// Records `annotation` (empty for none) for `field_id` from schema `schema_id` on. The property is removed +/// when the field inherits the same annotation from a lower schema id. +void setClickHouseTypeAnnotation(Poco::JSON::Object::Ptr metadata_object, Int32 field_id, Int32 schema_id, const String & annotation); + +/// Registers every schema of the table metadata with the ClickHouse type annotations in effect for it. +void addIcebergTableSchemasFromMetadata( + const Poco::JSON::Object::Ptr & metadata_object, IcebergSchemaProcessor & schema_processor, ContextPtr context); + Poco::Dynamic::Var getAvroType(DataTypePtr type, Int32 field_id); Poco::Dynamic::Var getAvroLogicalType(DataTypePtr type); @@ -156,6 +180,9 @@ std::pair createEmptyMetadataFile( UInt64 format_version = 2, bool is_catalog_table = false); +/// The table's own `allow_aggregate_function_states_in_open_formats`, when its `SETTINGS` give one. +std::optional getTableAllowAggregateFunctionStates(const DataLakeStorageSettings & data_lake_settings); + MetadataFileWithInfo getLatestOrExplicitMetadataFileAndVersion( const ObjectStoragePtr & object_storage, const String & table_path, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_metadata_generator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_metadata_generator.cpp index e262df663178b..830d715069bcd 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_metadata_generator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_metadata_generator.cpp @@ -6,7 +6,9 @@ #include #include +#include #include +#include #include #include #include @@ -557,8 +559,7 @@ std::vector getCurrentFieldNames(const Poco::JSON::Object::Ptr & metadat return {}; } -/// The Iceberg type recorded for `name` in the schema `current-schema-id` points at. -Poco::Dynamic::Var findCurrentFieldType(const Poco::JSON::Object::Ptr & metadata, const String & name) +Poco::Dynamic::Var findCurrentFieldValue(const Poco::JSON::Object::Ptr & metadata, const String & name, const String & key) { auto current_schema_id = metadata->getValue(f_current_schema_id); auto schemas = metadata->getArray(f_schemas); @@ -572,24 +573,52 @@ Poco::Dynamic::Var findCurrentFieldType(const Poco::JSON::Object::Ptr & metadata { auto field = fields->getObject(j); if (field->getValue(f_name) == name) - return field->get(f_type); + return field->get(key); } } return {}; } +/// The Iceberg type recorded for `name` in the schema `current-schema-id` points at. +Poco::Dynamic::Var findCurrentFieldType(const Poco::JSON::Object::Ptr & metadata, const String & name) +{ + return findCurrentFieldValue(metadata, name, f_type); +} + +Poco::JSON::Object::Ptr makeMetadataWithAnnotatedField( + const String & name, const Poco::Dynamic::Var & iceberg_type, bool required, const String & annotation) +{ + auto metadata = makeMetadataWithField(name, iceberg_type, required); + auto field_id = metadata->getArray(f_schemas)->getObject(0)->getArray(f_fields)->getObject(0)->getValue(f_id); + Poco::JSON::Object::Ptr properties = new Poco::JSON::Object; + properties->set(Iceberg::getClickHouseTypePropertyKey(field_id, /*schema_id=*/ 0), annotation); + metadata->set(f_properties, properties); + return metadata; +} + +std::optional findCurrentFieldAnnotation(const Poco::JSON::Object::Ptr & metadata, const String & name) +{ + const auto annotations = Iceberg::getClickHouseTypeAnnotations(metadata, metadata->getValue(f_current_schema_id)); + const auto it = annotations.find(findCurrentFieldValue(metadata, name, f_id).convert()); + if (it == annotations.end()) + return std::nullopt; + return it->second.type_name; +} + void expectModifyRejected( const Poco::JSON::Object::Ptr & metadata, const String & column, const DataTypePtr & requested_type, bool first = false, - const String & after_column = {}) + const String & after_column = {}, + std::optional table_allow_aggregate_function_states = std::nullopt) { const auto before = readSchemaState(metadata); MetadataGenerator gen(metadata); try { - gen.generateModifyColumnMetadata(column, requested_type, getContext().context, first, after_column); + gen.generateModifyColumnMetadata( + column, requested_type, getContext().context, first, after_column, table_allow_aggregate_function_states); FAIL() << "MODIFY COLUMN " << column << " " << requested_type->getName() << " cannot be recorded in Iceberg and must be rejected"; } @@ -1233,4 +1262,58 @@ TEST(IcebergMetadataGenerator, ModifyColumnSameComplexTypeWithDocOnlyRepositions EXPECT_EQ(stored_fields->getObject(0)->getValue(f_type), "int"); } +/// The Iceberg type stays, so only the ClickHouse type annotation changes and the schema is kept. +TEST(IcebergMetadataGenerator, ModifyColumnChangingOnlyTheSimpleAggregateFunctionKeepsTheSchema) +{ + tryRegisterAggregateFunctions(); + auto metadata = makeMetadataWithField("s", "long", /* required */ true); + const auto before = readSchemaState(metadata); + auto modify = [&](const String & type) + { + return MetadataGenerator(metadata).generateModifyColumnMetadata( + "s", DataTypeFactory::instance().get(type), getContext().context); + }; + + EXPECT_TRUE(modify("SimpleAggregateFunction(sum, Int64)")); + EXPECT_EQ(findCurrentFieldAnnotation(metadata, "s"), "SimpleAggregateFunction(sum, Int64)"); + EXPECT_FALSE(modify("SimpleAggregateFunction(sum, Int64)")); + EXPECT_TRUE(modify("SimpleAggregateFunction(max, Int64)")); + EXPECT_EQ(findCurrentFieldAnnotation(metadata, "s"), "SimpleAggregateFunction(max, Int64)"); + EXPECT_TRUE(modify("Int64")); + EXPECT_EQ(findCurrentFieldAnnotation(metadata, "s"), std::nullopt); + expectSchemaUnchanged(metadata, before); +} + +/// The current type of a state is its annotation, not the `String` its `binary` Iceberg type reads as. +TEST(IcebergMetadataGenerator, ModifyColumnComparesWithTheAnnotatedTypeOfAState) +{ + tryRegisterAggregateFunctions(); + auto metadata + = makeMetadataWithAnnotatedField("u", f_binary, /* required */ true, "AggregateFunction(uniq, UInt64)"); + EXPECT_FALSE(MetadataGenerator(metadata).generateModifyColumnMetadata( + "u", DataTypeFactory::instance().get("AggregateFunction(uniq, UInt64)"), getContext().context, + /* first */ false, /* after_column */ {}, /* table_allow_aggregate_function_states */ true)); + expectModifyRejected( + metadata, "u", DataTypeFactory::instance().get("AggregateFunction(sum, UInt64)"), + /* first */ false, /* after_column */ {}, /* table_allow_aggregate_function_states */ true); + EXPECT_EQ(findCurrentFieldAnnotation(metadata, "u"), "AggregateFunction(uniq, UInt64)"); +} + +TEST(IcebergMetadataGenerator, AddColumnRecordsAndDetectsTheClickHouseTypeAnnotation) +{ + tryRegisterAggregateFunctions(); + auto metadata = makeMetadataWithGap(); + MetadataGenerator gen(metadata); + + auto type = DataTypeFactory::instance().get("SimpleAggregateFunction(anyLast, Nullable(String))"); + EXPECT_FALSE(gen.isAddColumnApplied("extra", type)); + + gen.generateAddColumnMetadata("extra", type); + EXPECT_EQ(findCurrentFieldAnnotation(metadata, "extra"), "SimpleAggregateFunction(anyLast, Nullable(String))"); + EXPECT_TRUE(gen.isAddColumnApplied("extra", type)); + EXPECT_FALSE(gen.isAddColumnApplied( + "extra", DataTypeFactory::instance().get("SimpleAggregateFunction(any, Nullable(String))"))); + EXPECT_FALSE(gen.isAddColumnApplied("extra", makeNullable(std::make_shared()))); +} + #endif diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_schema_processor.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_schema_processor.cpp index 77908fb3e0c08..238ba8d58877e 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_schema_processor.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_schema_processor.cpp @@ -1,9 +1,17 @@ #include #include +#include #include #include #include +#include + +#include "config.h" +#if USE_AVRO +#include +#include +#endif #include #include @@ -11,6 +19,7 @@ namespace DB::ErrorCodes { extern const int ICEBERG_SPECIFICATION_VIOLATION; + extern const int SUPPORT_IS_DISABLED; } using namespace DB::Iceberg; @@ -22,6 +31,28 @@ Poco::JSON::Object::Ptr parseSchema(const std::string & json) Poco::JSON::Parser parser; return parser.parse(json).extract(); } + +DB::ContextMutablePtr contextWithAggregateFunctionStates(bool allow) +{ + auto context = DB::Context::createCopy(getContext().context); + context->setSetting("allow_aggregate_function_states_in_open_formats", DB::Field(allow)); + return context; +} + +void expectAnnotatedSchemaRejected(const Poco::JSON::Object::Ptr & schema, const ClickHouseTypeAnnotations & annotations) +{ + auto context = contextWithAggregateFunctionStates(true); + IcebergSchemaProcessor processor(context); + try + { + processor.addIcebergTableSchema(schema, context, annotations); + FAIL() << "The annotation does not describe the field type and must be rejected"; + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION) << e.message(); + } +} } TEST(IcebergSchemaProcessor, GetSimpleTypeBoolean) @@ -141,7 +172,7 @@ TEST(IcebergSchemaProcessor, UnknownFieldInSchemaProducesNullableNothing) { auto schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"placeholder","required":false,"type":"unknown"}]})json"); IcebergSchemaProcessor processor(getContext().context); - EXPECT_NO_THROW(processor.addIcebergTableSchema(schema, getContext().context)); + EXPECT_NO_THROW(processor.addIcebergTableSchema(schema, getContext().context, {})); } TEST(IcebergSchemaProcessor, GetSimpleTypeUnknownThrows) @@ -165,7 +196,7 @@ TEST(IcebergSchemaProcessor, InitialSchemaTypeWithStringLiteralArgumentThrows) { auto schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"MyType('Hello ( world )')"}]})json"); IcebergSchemaProcessor processor(getContext().context); - EXPECT_THROW(processor.addIcebergTableSchema(schema, getContext().context), DB::Exception); + EXPECT_THROW(processor.addIcebergTableSchema(schema, getContext().context, {}), DB::Exception); } /// The primitive parser must accept the same inner-whitespace spellings that the @@ -195,8 +226,8 @@ TEST(IcebergSchemaProcessor, DecimalTypeWhitespaceIsInsensitive) auto first = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(20,0)"}]})json"); auto second = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(20, 0)"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context)); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context, {})); } /// A genuinely different type bound to the same schema-id must still be rejected. @@ -205,8 +236,8 @@ TEST(IcebergSchemaProcessor, RebindingSchemaIdToDifferentTypeStillRejected) auto first = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(20,0)"}]})json"); auto second = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(20,2)"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_THROW(processor.addIcebergTableSchema(second, getContext().context), DB::Exception); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_THROW(processor.addIcebergTableSchema(second, getContext().context, {}), DB::Exception); } /// The manifest header 'schema' key is only a copy of the table schema at write time; metadata.json @@ -219,9 +250,9 @@ TEST(IcebergSchemaProcessor, ConflictingManifestSchemaToleratedWhenEnabled) auto from_metadata = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"}]})json"); auto from_manifest = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamp"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(from_metadata, getContext().context); + processor.addIcebergTableSchema(from_metadata, getContext().context, {}); EXPECT_NO_THROW(processor.addIcebergTableSchema( - from_manifest, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); + from_manifest, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); /// The metadata.json copy must win: the field keeps the timestamptz type. auto schema = processor.getClickHouseTableSchemaById(0); @@ -235,10 +266,10 @@ TEST(IcebergSchemaProcessor, ConflictingManifestSchemaRejectedWhenDisabled) auto from_metadata = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"}]})json"); auto from_manifest = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamp"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(from_metadata, getContext().context); + processor.addIcebergTableSchema(from_metadata, getContext().context, {}); EXPECT_THROW( processor.addIcebergTableSchema( - from_manifest, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/false), + from_manifest, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/false), DB::Exception); } @@ -249,10 +280,10 @@ TEST(IcebergSchemaProcessor, ConflictingMetadataSchemaAlwaysRejected) auto first = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"}]})json"); auto second = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamp"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(first, getContext().context); + processor.addIcebergTableSchema(first, getContext().context, {}); EXPECT_THROW( processor.addIcebergTableSchema( - second, getContext().context, IcebergSchemaProcessor::SchemaSource::Metadata, /*tolerate_conflicting_manifest_schemas=*/true), + second, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::Metadata, /*tolerate_conflicting_manifest_schemas=*/true), DB::Exception); } @@ -263,7 +294,7 @@ TEST(IcebergSchemaProcessor, ManifestSchemaWithNewIdRegistersNormally) auto from_manifest = parseSchema(R"json({"schema-id":5,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamp"}]})json"); IcebergSchemaProcessor processor(getContext().context); EXPECT_NO_THROW(processor.addIcebergTableSchema( - from_manifest, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); + from_manifest, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); EXPECT_TRUE(processor.hasClickHouseTableSchemaById(5)); } @@ -277,15 +308,15 @@ TEST(IcebergSchemaProcessor, ManifestHeaderRegisteredFirstIsReplacedByMetadata) auto other = parseSchema(R"json({"schema-id":1,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"},{"id":2,"name":"v","required":false,"type":"int"}]})json"); auto from_metadata = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(from_manifest, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); - processor.addIcebergTableSchema(other, getContext().context); + processor.addIcebergTableSchema(from_manifest, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); + processor.addIcebergTableSchema(other, getContext().context, {}); /// Populate everything derived from the schema that came from the manifest. EXPECT_EQ(processor.getFieldCharacteristics(0, 1).type->getName(), "Nullable(DateTime64(6))"); auto stale_dag = processor.getSchemaTransformationDagByIds(getContext().context, 0, 1); ASSERT_NE(stale_dag, nullptr); - EXPECT_NO_THROW(processor.addIcebergTableSchema(from_metadata, getContext().context)); + EXPECT_NO_THROW(processor.addIcebergTableSchema(from_metadata, getContext().context, {})); auto schema = processor.getClickHouseTableSchemaById(0); ASSERT_EQ(schema->size(), 1u); @@ -296,10 +327,10 @@ TEST(IcebergSchemaProcessor, ManifestHeaderRegisteredFirstIsReplacedByMetadata) /// Once metadata.json has settled the schema-id, a later divergent schema from a manifest is handled like /// any header conflicting with a known metadata.json copy: ignored when tolerated, rejected otherwise. EXPECT_NO_THROW(processor.addIcebergTableSchema( - from_manifest, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); + from_manifest, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); EXPECT_THROW( processor.addIcebergTableSchema( - from_manifest, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/false), + from_manifest, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/false), DB::Exception); EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "Nullable(DateTime64(6, 'UTC'))"); } @@ -312,14 +343,14 @@ TEST(IcebergSchemaProcessor, ManifestHeaderRegisteredFirstIsConfirmedByIdentical auto from_metadata = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"}]})json"); auto degraded = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamp"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(from_manifest, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); - EXPECT_NO_THROW(processor.addIcebergTableSchema(from_metadata, getContext().context)); + processor.addIcebergTableSchema(from_manifest, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); + EXPECT_NO_THROW(processor.addIcebergTableSchema(from_metadata, getContext().context, {})); EXPECT_NO_THROW(processor.addIcebergTableSchema( - degraded, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); + degraded, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true)); EXPECT_THROW( processor.addIcebergTableSchema( - degraded, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/false), + degraded, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/false), DB::Exception); EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "Nullable(DateTime64(6, 'UTC'))"); } @@ -333,11 +364,11 @@ TEST(IcebergSchemaProcessor, ConflictingManifestHeadersWithoutMetadataSchemaReje auto second = parseSchema(R"json({"schema-id":5,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"}]})json"); auto other = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"ts","required":false,"type":"timestamptz"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(other, getContext().context); - processor.addIcebergTableSchema(first, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); + processor.addIcebergTableSchema(other, getContext().context, {}); + processor.addIcebergTableSchema(first, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); try { - processor.addIcebergTableSchema(second, getContext().context, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); + processor.addIcebergTableSchema(second, getContext().context, {}, IcebergSchemaProcessor::SchemaSource::ManifestFile, /*tolerate_conflicting_manifest_schemas=*/true); FAIL() << "expected ICEBERG_SPECIFICATION_VIOLATION"; } catch (const DB::Exception & e) @@ -354,8 +385,8 @@ TEST(IcebergSchemaProcessor, RebindingSchemaIdToRenamedFieldStillRejected) auto first = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"long"}]})json"); auto second = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c9","required":false,"type":"long"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_THROW(processor.addIcebergTableSchema(second, getContext().context), DB::Exception); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_THROW(processor.addIcebergTableSchema(second, getContext().context, {}), DB::Exception); } /// The whitespace-insensitive comparison must reach into list/map wrappers: the nested @@ -368,8 +399,8 @@ TEST(IcebergSchemaProcessor, ListElementDecimalWhitespaceIsInsensitive) auto second = parseSchema( R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":{"type":"list","element-id":2,"element-required":false,"element":"decimal(20, 0)"}}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context)); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context, {})); } /// Same for map key/value primitive types (here map). @@ -380,8 +411,8 @@ TEST(IcebergSchemaProcessor, MapKeyValueDecimalWhitespaceIsInsensitive) auto second = parseSchema( R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":{"type":"map","key-id":2,"key":"decimal(20, 0)","value-id":3,"value-required":false,"value":"decimal(10, 2)"}}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context)); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context, {})); } /// The Iceberg geography/geometry primitives carry parameters too, e.g. @@ -393,8 +424,8 @@ TEST(IcebergSchemaProcessor, GeographyTypeWhitespaceIsInsensitive) auto first = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"geography(C,A)"}]})json"); auto second = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"geography(C, A)"}]})json"); IcebergSchemaProcessor processor(getContext().context, /*allow_geo_parser_=*/true); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context)); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context, {})); } /// A geo type string carrying leading/trailing whitespace must map to its alias just like the @@ -406,8 +437,8 @@ TEST(IcebergSchemaProcessor, GeographyTypeEdgeWhitespaceIsInsensitive) auto first = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":" geography(C,A) "}]})json"); auto second = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"geography(C, A)"}]})json"); IcebergSchemaProcessor processor(getContext().context, /*allow_geo_parser_=*/true); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context)); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_NO_THROW(processor.addIcebergTableSchema(second, getContext().context, {})); } /// Schema-evolution path: renaming a geo field across two schema-ids while only changing the @@ -419,8 +450,8 @@ TEST(IcebergSchemaProcessor, RenameGeoFieldAcrossSchemaIdsWithWhitespaceIsRename auto old_schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"a","required":false,"type":"geography(C,A)"}]})json"); auto new_schema = parseSchema(R"json({"schema-id":1,"fields":[{"id":1,"name":"b","required":false,"type":"geography(C, A)"}]})json"); IcebergSchemaProcessor processor(getContext().context, /*allow_geo_parser_=*/true); - processor.addIcebergTableSchema(old_schema, getContext().context); - processor.addIcebergTableSchema(new_schema, getContext().context); + processor.addIcebergTableSchema(old_schema, getContext().context, {}); + processor.addIcebergTableSchema(new_schema, getContext().context, {}); auto dag = processor.getSchemaTransformationDagByIds(getContext().context, 0, 1); ASSERT_TRUE(dag); @@ -436,7 +467,7 @@ TEST(IcebergSchemaProcessor, InitialSchemaDecimalInnerWhitespaceAccepted) { auto schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal( 20, 0 )"}]})json"); IcebergSchemaProcessor processor(getContext().context); - EXPECT_NO_THROW(processor.addIcebergTableSchema(schema, getContext().context)); + EXPECT_NO_THROW(processor.addIcebergTableSchema(schema, getContext().context, {})); } /// Schema-evolution across two schema-ids where a decimal widens (allowed conversion) while its @@ -447,8 +478,8 @@ TEST(IcebergSchemaProcessor, WidenDecimalAcrossSchemaIdsWithInnerWhitespace) auto old_schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(10,2)"}]})json"); auto new_schema = parseSchema(R"json({"schema-id":1,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal( 20, 2 )"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(old_schema, getContext().context); - processor.addIcebergTableSchema(new_schema, getContext().context); + processor.addIcebergTableSchema(old_schema, getContext().context, {}); + processor.addIcebergTableSchema(new_schema, getContext().context, {}); auto dag = processor.getSchemaTransformationDagByIds(getContext().context, 0, 1); ASSERT_TRUE(dag); @@ -465,8 +496,8 @@ TEST(IcebergSchemaProcessor, RebindingListElementToDifferentTypeStillRejected) auto second = parseSchema( R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":{"type":"list","element-id":2,"element-required":false,"element":"decimal(20,2)"}}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(first, getContext().context); - EXPECT_THROW(processor.addIcebergTableSchema(second, getContext().context), DB::Exception); + processor.addIcebergTableSchema(first, getContext().context, {}); + EXPECT_THROW(processor.addIcebergTableSchema(second, getContext().context, {}), DB::Exception); } /// Spacing normalization only removes whitespace adjacent to the delimiters '(', ')', '[', ']', ','. @@ -488,7 +519,7 @@ TEST(IcebergSchemaProcessor, InitialSchemaDecimalMalformedInnerTokenWhitespaceTh { auto schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(2 0,0)"}]})json"); IcebergSchemaProcessor processor(getContext().context); - EXPECT_THROW(processor.addIcebergTableSchema(schema, getContext().context), DB::Exception); + EXPECT_THROW(processor.addIcebergTableSchema(schema, getContext().context, {}), DB::Exception); } /// Trailing garbage after the scale token must be rejected. Canonicalizing spacing does not remove @@ -504,7 +535,7 @@ TEST(IcebergSchemaProcessor, InitialSchemaDecimalTrailingGarbageInScaleThrows) { auto schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(20,0 0)"}]})json"); IcebergSchemaProcessor processor(getContext().context); - EXPECT_THROW(processor.addIcebergTableSchema(schema, getContext().context), DB::Exception); + EXPECT_THROW(processor.addIcebergTableSchema(schema, getContext().context, {}), DB::Exception); } /// A new schema-id introduced during evolution is parsed at add time (getSimpleType runs on every @@ -515,8 +546,8 @@ TEST(IcebergSchemaProcessor, SchemaEvolutionDecimalTrailingGarbageInScaleThrows) auto old_schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(10,2)"}]})json"); auto new_schema = parseSchema(R"json({"schema-id":1,"fields":[{"id":1,"name":"c0","required":false,"type":"decimal(20,2 2)"}]})json"); IcebergSchemaProcessor processor(getContext().context); - processor.addIcebergTableSchema(old_schema, getContext().context); - EXPECT_THROW(processor.addIcebergTableSchema(new_schema, getContext().context), DB::Exception); + processor.addIcebergTableSchema(old_schema, getContext().context, {}); + EXPECT_THROW(processor.addIcebergTableSchema(new_schema, getContext().context, {}), DB::Exception); } /// A missing scale ("decimal(20,)") or a sign-only scale ("decimal(20,+)") is malformed metadata and @@ -531,3 +562,171 @@ TEST(IcebergSchemaProcessor, GetSimpleTypeDecimalSignOnlyScaleThrows) { EXPECT_THROW(IcebergSchemaProcessor::getSimpleType("decimal(20,+)", getContext().context), DB::Exception); } + +TEST(IcebergSchemaProcessor, ChangedAnnotationReparsesIdenticalSchema) +{ + tryRegisterAggregateFunctions(); + const std::string schema_json = R"json({"schema-id":0,"fields":[{"id":1,"name":"s","required":true,"type":"long"}]})json"; + auto context = contextWithAggregateFunctionStates(false); + IcebergSchemaProcessor processor(context); + + processor.addIcebergTableSchema(parseSchema(schema_json), context, {{1, {"SimpleAggregateFunction(sum, Int64)"}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "SimpleAggregateFunction(sum, Int64)"); + + processor.addIcebergTableSchema(parseSchema(schema_json), context, {}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "Int64"); + EXPECT_EQ(processor.getFieldCharacteristics(0, 1).type->getName(), "Int64"); +} + +TEST(IcebergSchemaProcessor, SchemasKeepTheAnnotationsTheyWereRegisteredWith) +{ + tryRegisterAggregateFunctions(); + auto context = contextWithAggregateFunctionStates(false); + IcebergSchemaProcessor processor(context); + + processor.addIcebergTableSchema( + parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"s","required":true,"type":"long"}]})json"), + context, + {{1, {"SimpleAggregateFunction(sum, Int64)"}}}); + processor.addIcebergTableSchema( + parseSchema( + R"json({"schema-id":1,"fields":[{"id":1,"name":"s","required":true,"type":"long"},{"id":2,"name":"t","required":false,"type":"long"}]})json"), + context, + {}); + + EXPECT_EQ(processor.getFieldCharacteristics(0, 1).type->getName(), "SimpleAggregateFunction(sum, Int64)"); + EXPECT_EQ(processor.getFieldCharacteristics(1, 1).type->getName(), "Int64"); + + auto dag = processor.getSchemaTransformationDagByIds(context, 0, 1); + ASSERT_EQ(dag->getInputs().size(), 1u); + EXPECT_EQ(dag->getInputs().front()->result_type->getName(), "SimpleAggregateFunction(sum, Int64)"); +} + +TEST(IcebergSchemaProcessor, AnnotationMustDescribeTheFieldType) +{ + tryRegisterAggregateFunctions(); + auto schema = parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"s","required":true,"type":"long"}]})json"); + + /// ClickHouse writes both `Int64` and `UInt64` as `long`. + auto context = contextWithAggregateFunctionStates(false); + IcebergSchemaProcessor processor(context); + processor.addIcebergTableSchema(schema, context, {{1, {"SimpleAggregateFunction(sum, UInt64)"}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "SimpleAggregateFunction(sum, UInt64)"); + + /// An annotation recorded for the schema itself must describe its field. + expectAnnotatedSchemaRejected(schema, {{1, {"AggregateFunction(uniq, UInt64)"}}}); + expectAnnotatedSchemaRejected(schema, {{1, {"SimpleAggregateFunction(max, Int32)"}}}); + expectAnnotatedSchemaRejected( + parseSchema(R"json({"schema-id":0,"fields":[{"id":1,"name":"u","required":false,"type":"binary"}]})json"), + {{1, {"AggregateFunction(uniq, UInt64)"}}}); +} + +/// Another engine evolved the field after the annotation was recorded for a lower schema id: the annotation no longer +/// applies, and the field reads as its Iceberg type. +TEST(IcebergSchemaProcessor, InheritedAnnotationDoesNotApplyToAnEvolvedField) +{ + tryRegisterAggregateFunctions(); + auto context = contextWithAggregateFunctionStates(true); + IcebergSchemaProcessor processor(context); + + /// `int` promoted to `long`. + processor.addIcebergTableSchema( + parseSchema(R"json({"schema-id":1,"fields":[{"id":1,"name":"s","required":true,"type":"long"}]})json"), + context, + {{1, {"SimpleAggregateFunction(max, Int32)", true}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(1)->front().type->getName(), "Int64"); + + /// A required state field made optional. + processor.addIcebergTableSchema( + parseSchema(R"json({"schema-id":2,"fields":[{"id":2,"name":"u","required":false,"type":"binary"}]})json"), + context, + {{2, {"AggregateFunction(uniq, UInt64)", true}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(2)->front().type->getName(), "Nullable(String)"); + + /// An inherited annotation that still describes the field applies. + processor.addIcebergTableSchema( + parseSchema(R"json({"schema-id":3,"fields":[{"id":3,"name":"u","required":true,"type":"binary"}]})json"), + context, + {{3, {"AggregateFunction(uniq, UInt64)", true}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(3)->front().type->getName(), "AggregateFunction(uniq, UInt64)"); +} + +TEST(IcebergSchemaProcessor, AggregateFunctionStateSchemaRegisteredByAllowedQueryIsRefusedWithoutSetting) +{ + tryRegisterAggregateFunctions(); + const std::string schema_json = R"json({"schema-id":0,"fields":[{"id":1,"name":"u","required":true,"type":"binary"}]})json"; + const ClickHouseTypeAnnotations annotations{{1, {"AggregateFunction(uniq, UInt64)"}}}; + IcebergSchemaProcessor processor(getContext().context); + + processor.addIcebergTableSchema(parseSchema(schema_json), contextWithAggregateFunctionStates(true), annotations); + ASSERT_TRUE(processor.hasClickHouseTableSchemaById(0)); + + try + { + processor.addIcebergTableSchema(parseSchema(schema_json), contextWithAggregateFunctionStates(false), annotations); + FAIL() << "A query without the setting must be refused even when the schema is already registered"; + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::SUPPORT_IS_DISABLED) << e.message(); + } +} + +#if USE_AVRO +TEST(IcebergSchemaProcessor, SkippingTheSchemaNeitherAppliesTheGateNorPublishesTheSchema) +{ + tryRegisterAggregateFunctions(); + Poco::JSON::Parser parser; + auto metadata = parser + .parse( + R"json({"format-version":2,"current-schema-id":0,"schemas":[{"schema-id":0,)json" + R"json("fields":[{"id":1,"name":"u","required":true,"type":"binary"}]}],)json" + R"json("properties":{"clickhouse.type.1.0":"AggregateFunction(uniq, UInt64)"}})json") + .extract(); + + auto log = getLogger("IcebergSchemaProcessorTest"); + auto context = contextWithAggregateFunctionStates(false); + DB::Iceberg::IcebergSchemaProcessor processor(context); + + Int32 schema_id = -1; + ASSERT_NO_THROW( + schema_id = DB::IcebergMetadata::parseTableSchema( + metadata, processor, context, log, DB::IcebergMetadata::SchemaParsing::Skip)); + EXPECT_EQ(schema_id, 0); + + EXPECT_FALSE(processor.hasClickHouseTableSchemaById(0)); + EXPECT_FALSE(processor.tryGetFieldCharacteristics(0, 1).has_value()); + EXPECT_FALSE(processor.tryGetColumnIDByName(0, "u").has_value()); + + auto allowed_context = contextWithAggregateFunctionStates(true); + ASSERT_NO_THROW(DB::IcebergMetadata::parseTableSchema( + metadata, processor, allowed_context, log, DB::IcebergMetadata::SchemaParsing::Parse)); + auto columns = processor.getClickHouseTableSchemaById(0); + ASSERT_EQ(columns->size(), 1u); + EXPECT_EQ(columns->front().name, "u"); + EXPECT_EQ(columns->front().type->getName(), "AggregateFunction(uniq, UInt64)"); +} + +/// Per field, the property with the greatest schema id not above the requested one is in effect. +TEST(IcebergSchemaProcessor, ClickHouseTypeAnnotationsInEffectForSchema) +{ + Poco::JSON::Parser parser; + auto metadata = parser + .parse( + R"json({"properties":{"clickhouse.type.comment":"x","clickhouse.type.1":"x",)json" + R"json("clickhouse.type.1.x":"x","clickhouse.type.1.0.1":"x",)json" + R"json("clickhouse.type.1.0":"SimpleAggregateFunction(max, Int32)",)json" + R"json("clickhouse.type.1.2":"SimpleAggregateFunction(max, Int64)","clickhouse.type.1.4":"",)json" + R"json("clickhouse.type.2.3":"SimpleAggregateFunction(sum, Int64)"}})json") + .extract(); + + EXPECT_EQ(getClickHouseTypeAnnotations(metadata, 0), (ClickHouseTypeAnnotations{{1, {"SimpleAggregateFunction(max, Int32)", false}}})); + EXPECT_EQ(getClickHouseTypeAnnotations(metadata, 1), (ClickHouseTypeAnnotations{{1, {"SimpleAggregateFunction(max, Int32)", true}}})); + EXPECT_EQ(getClickHouseTypeAnnotations(metadata, 2), (ClickHouseTypeAnnotations{{1, {"SimpleAggregateFunction(max, Int64)", false}}})); + EXPECT_EQ( + getClickHouseTypeAnnotations(metadata, 3), + (ClickHouseTypeAnnotations{ + {1, {"SimpleAggregateFunction(max, Int64)", true}}, {2, {"SimpleAggregateFunction(sum, Int64)", false}}})); + EXPECT_EQ(getClickHouseTypeAnnotations(metadata, 4), (ClickHouseTypeAnnotations{{2, {"SimpleAggregateFunction(sum, Int64)", true}}})); +} +#endif diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_type_mapping.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_type_mapping.cpp index 3168cdbf90922..1bb26c7056f3c 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_type_mapping.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/tests/gtest_iceberg_type_mapping.cpp @@ -5,6 +5,10 @@ #include #include +#include +#include +#include +#include #include #include #include @@ -176,4 +180,27 @@ TEST(IcebergTypeMapping, NullableDecimalPrecisionAboveSpecLimitIsRejected) expectIcebergTypeRejected(makeNullable(createDecimal(76, 1))); } +TEST(IcebergTypeMapping, AnnotationKeepsAggregateStateVersion) +{ + tryRegisterAggregateFunctions(); + + auto version_of = [](const DataTypePtr & type) + { + return assert_cast(*type).getVersion(); + }; + + /// The name of a version 0 state has no version, which reads back as version 0, not as the default version. + auto v0 = DataTypeFactory::instance().get("AggregateFunction(0, sumMap, Array(UInt8), Array(UInt8))"); + EXPECT_EQ(v0->getName(), "AggregateFunction(sumMap, Array(UInt8), Array(UInt8))"); + EXPECT_EQ(version_of(resolveClickHouseTypeAnnotation(v0->getName(), true)), 0u); + + auto array_v0 = DataTypeFactory::instance().get("Array(AggregateFunction(0, sumMap, Array(UInt8), Array(UInt8)))"); + EXPECT_EQ( + version_of(assert_cast(*resolveClickHouseTypeAnnotation(array_v0->getName(), true)).getNestedType()), + 0u); + + auto latest = DataTypeFactory::instance().get("AggregateFunction(sumMap, Array(UInt8), Array(UInt8))"); + EXPECT_EQ(version_of(resolveClickHouseTypeAnnotation(latest->getName(), true)), version_of(latest)); +} + #endif diff --git a/src/Storages/ObjectStorage/StorageObjectStorage.cpp b/src/Storages/ObjectStorage/StorageObjectStorage.cpp index b9e9d1e3ed8bf..56647d6fef7df 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorage.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorage.cpp @@ -157,11 +157,13 @@ StorageObjectStorage::StorageObjectStorage( bool is_table_function_, bool lazy_init, bool updated_configuration, - std::optional sample_path_) + std::optional sample_path_, + std::optional table_allow_aggregate_function_states_) : IStorage(table_id_) , configuration(configuration_) , object_storage(object_storage_) , format_settings(format_settings_) + , table_allow_aggregate_function_states(table_allow_aggregate_function_states_) , distributed_processing(distributed_processing_) , is_table_function(is_table_function_) , log(getLogger(fmt::format("Storage{}({})", configuration->getEngineName(), table_id_.getFullTableName()))) @@ -242,7 +244,13 @@ StorageObjectStorage::StorageObjectStorage( } if (need_resolve_columns_or_format) - resolveSchemaAndFormat(columns, object_storage, configuration, format_settings, sample_path, context); + resolveSchemaAndFormat( + columns, + object_storage, + configuration, + withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, context), + sample_path, + context); else validateSupportedColumns(columns, *configuration); @@ -740,7 +748,8 @@ void StorageObjectStorage::read( && settings[Setting::optimize_count_from_files] && !VirtualColumnUtils::hasRowDependentVirtualColumns(read_from_format_info.requested_virtual_columns); - auto modified_format_settings{format_settings}; + auto modified_format_settings + = withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, local_context); if (!modified_format_settings.has_value()) modified_format_settings.emplace(getFormatSettings(local_context)); @@ -777,7 +786,14 @@ SinkToStoragePtr StorageObjectStorage::write( configuration->update(object_storage, local_context); } - return createSink(configuration, object_storage, storage_id, format_settings, catalog, metadata_snapshot, local_context); + return createSink( + configuration, + object_storage, + storage_id, + withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, local_context), + catalog, + metadata_snapshot, + local_context); } SinkToStoragePtr StorageObjectStorage::createSink( @@ -849,7 +865,13 @@ bool StorageObjectStorage::optimize( bool /*cleanup*/, [[maybe_unused]] ContextPtr context) { - return configuration->optimize(object_storage, metadata_snapshot, context, format_settings, catalog, getStorageID()); + return configuration->optimize( + object_storage, + metadata_snapshot, + context, + withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, context), + catalog, + getStorageID()); } bool StorageObjectStorage::supportsImport(ContextPtr local_context) const @@ -880,6 +902,13 @@ IStorage::ImportResult StorageObjectStorage::import( const std::optional & format_settings_, ContextPtr local_context) { + /// The export brings its own format settings, but the table's own `allow_aggregate_function_states_in_open_formats` decides over them. + auto import_format_settings = format_settings_ + ? format_settings_ + : withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, local_context); + if (format_settings_ && table_allow_aggregate_function_states) + import_format_settings->parquet.allow_aggregate_function_states = *table_allow_aggregate_function_states; + if (isDataLake()) { configuration->lazyInitializeIfNeeded(object_storage, local_context); @@ -889,7 +918,7 @@ IStorage::ImportResult StorageObjectStorage::import( new_file_path_callback, std::make_shared(metadata_snapshot->getSampleBlock()), *iceberg_metadata_json_string, - format_settings_ ? format_settings_ : format_settings, + import_format_settings, local_context)); } @@ -952,7 +981,7 @@ IStorage::ImportResult StorageObjectStorage::import( max_rows_per_file, /* overwrite_existing_data_files= */ file_already_exists_policy != MergeTreePartExportFileAlreadyExistsPolicy::error, new_file_path_callback, - format_settings_ ? format_settings_ : format_settings, + import_format_settings, std::make_shared(metadata_snapshot->getSampleBlock()), local_context)); } @@ -1273,7 +1302,14 @@ void StorageObjectStorage::mutate([[maybe_unused]] const MutationCommands & comm updateExternalDynamicMetadataIfExists(context_); auto metadata_snapshot = getInMemoryMetadataPtr(context_, false); auto storage = getStorageID(); - configuration->mutate(commands, context_, shared_from_this(), storage, metadata_snapshot, catalog, format_settings); + configuration->mutate( + commands, + context_, + shared_from_this(), + storage, + metadata_snapshot, + catalog, + withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, context_)); } void StorageObjectStorage::checkMutationIsPossible(const MutationCommands & commands, const Settings & /* settings */) const diff --git a/src/Storages/ObjectStorage/StorageObjectStorage.h b/src/Storages/ObjectStorage/StorageObjectStorage.h index 1f31e30e01a28..c0ef45cdc9d9e 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorage.h +++ b/src/Storages/ObjectStorage/StorageObjectStorage.h @@ -65,7 +65,8 @@ class StorageObjectStorage : public IStorage, public IBackgroundOperation bool is_table_function_ = false, bool lazy_init = false, bool updated_configuration = false, // avoid double update configuration from cluster and local versions - std::optional sample_path_ = std::nullopt); + std::optional sample_path_ = std::nullopt, + std::optional table_allow_aggregate_function_states_ = std::nullopt); String getName() const override; @@ -294,6 +295,8 @@ class StorageObjectStorage : public IStorage, public IBackgroundOperation /// `object_storage` to allow direct access to data storage. const ObjectStoragePtr object_storage; const std::optional format_settings; + /// The table's own `allow_aggregate_function_states_in_open_formats`, when its `SETTINGS` give one. + const std::optional table_allow_aggregate_function_states; /// Whether this engine is a part of according Cluster engine implementation. /// (One of the reading replicas, not the initiator). const bool distributed_processing; diff --git a/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp b/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp index 401326c070cda..753aee987f52c 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp @@ -121,7 +121,8 @@ StorageObjectStorageCluster::StorageObjectStorageCluster( bool if_not_exists, bool is_datalake_query, bool is_table_function, - bool lazy_init) + bool lazy_init, + std::optional table_allow_aggregate_function_states_) : IStorageCluster( cluster_name_, table_id_, getLogger(fmt::format("{}({})", configuration_->getEngineName(), table_id_.table_name))) , configuration{configuration_} @@ -192,7 +193,13 @@ StorageObjectStorageCluster::StorageObjectStorageCluster( std::string sample_path; if (need_resolve_columns_or_format) - resolveSchemaAndFormat(columns, object_storage, configuration, {}, sample_path, context_); + resolveSchemaAndFormat( + columns, + object_storage, + configuration, + withAllowAggregateFunctionStatesForQuery(format_settings_, table_allow_aggregate_function_states_, context_), + sample_path, + context_); else validateSupportedColumns(columns, *configuration); @@ -294,7 +301,8 @@ StorageObjectStorageCluster::StorageObjectStorageCluster( /* is_table_function */is_table_function, /* lazy_init */lazy_init, updated_configuration, - sample_path); + sample_path, + table_allow_aggregate_function_states_); /// Virtual columns are a part of StorageInMemoryMetadata, so they are propagated together with it. pure_storage->setInMemoryMetadata(metadata); diff --git a/src/Storages/ObjectStorage/StorageObjectStorageCluster.h b/src/Storages/ObjectStorage/StorageObjectStorageCluster.h index 631d7efd06513..71f26500ebbf9 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageCluster.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageCluster.h @@ -27,7 +27,8 @@ class StorageObjectStorageCluster : public IStorageCluster bool if_not_exists, bool is_datalake_query, bool is_table_function_ = false, - bool lazy_init = false); + bool lazy_init = false, + std::optional table_allow_aggregate_function_states_ = std::nullopt); std::string getName() const override; diff --git a/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp b/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp index 84026dba4ac37..bcff56ddfa7c5 100644 --- a/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp +++ b/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp @@ -80,6 +80,9 @@ createStorageObjectStorage(const StorageFactory::Arguments & args, StorageObject format_settings = getFormatSettings(context); } + const auto table_allow_aggregate_function_states = extractTableAllowAggregateFunctionStates( + *format_settings, args.storage_def->settings ? &args.storage_def->settings->changes : nullptr); + ASTPtr partition_by; if (args.storage_def->partition_by) partition_by = args.storage_def->partition_by->clone(); @@ -134,7 +137,8 @@ createStorageObjectStorage(const StorageFactory::Arguments & args, StorageObject args.query.if_not_exists, /* is_datalake_query */ false, /* is_table_function */ false, - /* lazy_init */ false); + /* lazy_init */ false, + table_allow_aggregate_function_states); } #endif @@ -1257,6 +1261,55 @@ Writes use the inverse mapping: `DateTime64(9)` is stored as `timestamp_ns`, and | `map` | `Map` | | `struct` | `Tuple` | +### Aggregate function states {#aggregate-function-states} + +Iceberg has no aggregate-state type. ClickHouse stores these types as plain Iceberg values and records the +ClickHouse type in the table property `clickhouse.type..`: + +| ClickHouse type | Iceberg type | Stored as | +|---|---|---| +| `AggregateFunction(f, T...)` | `binary` | The serialized state, the bytes the `-State` combinator produces | +| `SimpleAggregateFunction(f, T)` | the type `T` maps to | A plain value of type `T` | + +A property applies from schema `` until the next property of the same field; an empty value means no type. +If another engine later changes the field's type, for example promotes `int` to `long` or makes the field optional, +the type no longer applies to the new schemas, and the field reads as its Iceberg type. Other query engines ignore +these properties. + +```sql +CREATE TABLE agg (k UInt32, u AggregateFunction(uniq, UInt64), s SimpleAggregateFunction(sum, UInt64)) +ENGINE = IcebergLocal('/path/to/table/') +PARTITION BY k +SETTINGS allow_aggregate_function_states_in_open_formats = 1; + +SELECT k, uniqMerge(u), sum(s) FROM agg GROUP BY k; +``` + +States are controlled by +[`allow_aggregate_function_states_in_open_formats`](/reference/settings/formats/other#allow_aggregate_function_states_in_open_formats), +disabled by default. The table metadata chooses the deserializer for the stored bytes, so enable the setting only for +tables from trusted sources. When it is disabled, creating an `AggregateFunction` column and any query on a table +that has one (`SELECT`, `INSERT`, `ALTER TABLE ... UPDATE`, `OPTIMIZE TABLE`, ...) throw `SUPPORT_IS_DISABLED`. +`SimpleAggregateFunction` is not affected: its type is always recorded and restored on read, so the column reads as +`SimpleAggregateFunction(f, T)`, not `T`. Fields without a `clickhouse.type` property read as their Iceberg type. + +If the table sets the setting in its `SETTINGS` clause, that value is stored with the table and applies to every +query on it. Otherwise the query's value applies, as for table functions such as `icebergS3` and for tables of a +`DataLakeCatalog` database. On a cluster (`object_storage_cluster`), a table sends its own value to the other nodes, +so all of them must know the setting. + +`ALTER TABLE ... EXPORT PART` and `ALTER TABLE ... EXPORT PARTITION` move states from an `AggregatingMergeTree` table +into such a table without finalizing them. `EXPORT PARTITION` records the query's value with the task, so every +replica that executes it uses that value. + +```sql +ALTER TABLE mt EXPORT PART 'all_1_1_0' TO TABLE agg; +ALTER TABLE rmt EXPORT PARTITION ID '1' TO TABLE agg; +``` + +Data files also record the types in their Parquet metadata, see +[aggregate function states in Parquet](/reference/formats/Parquet/Parquet#aggregate-function-states). + ## Schema and write compatibility limitations {#schema-and-write-compatibility-limitations} The data type mappings above apply to reads. The following limitations apply when ClickHouse creates or evolves Iceberg schemas and writes data: diff --git a/src/Storages/StorageFile.cpp b/src/Storages/StorageFile.cpp index 3f2594796372c..064d0654266b6 100644 --- a/src/Storages/StorageFile.cpp +++ b/src/Storages/StorageFile.cpp @@ -1359,6 +1359,7 @@ StorageFile::StorageFile(CommonArguments args) : IStorage(args.table_id) , format_name(args.format_name) , format_settings(args.format_settings) + , table_allow_aggregate_function_states(args.table_allow_aggregate_function_states) , compression_method(args.compression_method) , base_path(args.getContext()->getPath()) { @@ -1388,10 +1389,12 @@ void StorageFile::setStorageMetadata(CommonArguments args) } else { + const auto inference_format_settings + = withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, args.getContext()); if (format_name == "auto") - std::tie(columns, format_name) = getTableStructureAndFormatFromFile(paths, compression_method, format_settings, args.getContext(), archive_info); + std::tie(columns, format_name) = getTableStructureAndFormatFromFile(paths, compression_method, inference_format_settings, args.getContext(), archive_info); else - columns = getTableStructureFromFile(format_name, paths, compression_method, format_settings, args.getContext(), archive_info); + columns = getTableStructureFromFile(format_name, paths, compression_method, inference_format_settings, args.getContext(), archive_info); if (!args.columns.empty() && args.columns != columns) throw Exception(ErrorCodes::INCOMPATIBLE_COLUMNS, "Table structure and file structure are different"); @@ -1401,7 +1404,12 @@ void StorageFile::setStorageMetadata(CommonArguments args) else { if (format_name == "auto") - format_name = getTableStructureAndFormatFromFile(paths, compression_method, format_settings, args.getContext(), archive_info).second; + format_name = getTableStructureAndFormatFromFile( + paths, + compression_method, + withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, args.getContext()), + args.getContext(), + archive_info).second; /// We don't allow special columns in File storage. if (!args.columns.hasOnlyOrdinary()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Table engine File doesn't support special columns like MATERIALIZED, ALIAS or EPHEMERAL"); @@ -2872,6 +2880,8 @@ SinkToStoragePtr StorageFile::write( ContextPtr context, bool /*async_insert*/) { + const auto query_format_settings = withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, context); + if (!use_table_fd && archive_info.has_value()) throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing to archives is not supported"); @@ -2910,7 +2920,7 @@ SinkToStoragePtr StorageFile::write( base_path, path_for_partitioned_write, chooseCompressionMethod(path_for_partitioned_write, compression_method), - format_settings, + query_format_settings, format_name, context, flags); @@ -2974,7 +2984,7 @@ SinkToStoragePtr StorageFile::write( base_path, path, chooseCompressionMethod(path, compression_method), - format_settings, + query_format_settings, format_name, context, flags); @@ -3071,6 +3081,7 @@ void registerStorageFile(StorageFactory & factory) factory_args.constraints, factory_args.comment, {}, + std::nullopt, }; ASTs & engine_args_ast = factory_args.engine_args; @@ -3099,6 +3110,8 @@ void registerStorageFile(StorageFactory & factory) { storage_args.format_settings = getFormatSettings(factory_args.getContext()); } + storage_args.table_allow_aggregate_function_states = extractTableAllowAggregateFunctionStates( + *storage_args.format_settings, factory_args.storage_def->settings ? &factory_args.storage_def->settings->changes : nullptr); if (engine_args_ast.size() == 1) /// Table in database return std::make_shared(factory_args.relative_data_path, storage_args); diff --git a/src/Storages/StorageFile.h b/src/Storages/StorageFile.h index 41ec5c59e236b..5d3e2e55dd6f4 100644 --- a/src/Storages/StorageFile.h +++ b/src/Storages/StorageFile.h @@ -44,6 +44,8 @@ class StorageFile final : public IStorage const ConstraintsDescription & constraints; const String & comment; const std::string rename_after_processing; + /// The table's own `allow_aggregate_function_states_in_open_formats`, when its `SETTINGS` give one. + std::optional table_allow_aggregate_function_states; }; struct ArchiveInfo @@ -197,6 +199,8 @@ class StorageFile final : public IStorage // For `file` table function, we use format settings from current user context, // in this case, format_settings is not set. std::optional format_settings; + /// The table's own `allow_aggregate_function_states_in_open_formats`, when its `SETTINGS` give one. + std::optional table_allow_aggregate_function_states; int table_fd = -1; String compression_method; diff --git a/src/Storages/StorageMergeTree.cpp b/src/Storages/StorageMergeTree.cpp index 95f86733f58d5..1408dd0d645cd 100644 --- a/src/Storages/StorageMergeTree.cpp +++ b/src/Storages/StorageMergeTree.cpp @@ -148,6 +148,7 @@ namespace Setting extern const SettingsTimezone iceberg_partition_timezone; extern const SettingsMergeTreePartExportSchemaMatchMode export_merge_tree_part_schema_match_mode; extern const SettingsBool export_merge_tree_part_ignore_extra_source_columns; + extern const SettingsBool allow_aggregate_function_states_in_open_formats; } namespace ServerSetting @@ -4149,6 +4150,8 @@ void StorageMergeTree::exportPartitionToTable(const PartitionCommand & command, descriptor.filename_pattern = query_context->getSettingsRef()[Setting::export_merge_tree_part_filename_pattern].value; descriptor.write_full_path_in_iceberg_metadata = query_context->getSettingsRef()[Setting::write_full_path_in_iceberg_metadata]; descriptor.allow_lossy_cast = query_context->getSettingsRef()[Setting::export_merge_tree_part_allow_lossy_cast]; + descriptor.allow_aggregate_function_states_in_open_formats + = query_context->getSettingsRef()[Setting::allow_aggregate_function_states_in_open_formats].value; descriptor.iceberg_partition_timezone = query_context->getSettingsRef()[Setting::iceberg_partition_timezone].toString(); descriptor.schema_match_mode = query_context->getSettingsRef()[Setting::export_merge_tree_part_schema_match_mode].value; descriptor.ignore_extra_source_columns = query_context->getSettingsRef()[Setting::export_merge_tree_part_ignore_extra_source_columns].value; diff --git a/src/Storages/StorageReplicatedMergeTree.cpp b/src/Storages/StorageReplicatedMergeTree.cpp index 7662861e46f79..ed10487876651 100644 --- a/src/Storages/StorageReplicatedMergeTree.cpp +++ b/src/Storages/StorageReplicatedMergeTree.cpp @@ -255,6 +255,7 @@ namespace Setting extern const SettingsUInt64 iceberg_insert_max_bytes_in_data_file; extern const SettingsUInt64 iceberg_insert_max_rows_in_data_file; extern const SettingsTimezone iceberg_partition_timezone; + extern const SettingsBool allow_aggregate_function_states_in_open_formats; } @@ -8877,6 +8878,8 @@ void StorageReplicatedMergeTree::exportPartitionToTable(const PartitionCommand & manifest.filename_pattern = query_context->getSettingsRef()[Setting::export_merge_tree_part_filename_pattern].value; manifest.write_full_path_in_iceberg_metadata = query_context->getSettingsRef()[Setting::write_full_path_in_iceberg_metadata]; manifest.allow_lossy_cast = query_context->getSettingsRef()[Setting::export_merge_tree_part_allow_lossy_cast]; + manifest.allow_aggregate_function_states_in_open_formats + = query_context->getSettingsRef()[Setting::allow_aggregate_function_states_in_open_formats].value; manifest.iceberg_partition_timezone = query_context->getSettingsRef()[Setting::iceberg_partition_timezone].toString(); manifest.schema_match_mode = query_context->getSettingsRef()[Setting::export_merge_tree_part_schema_match_mode].value; manifest.ignore_extra_source_columns = query_context->getSettingsRef()[Setting::export_merge_tree_part_ignore_extra_source_columns].value; diff --git a/src/Storages/StorageURL.cpp b/src/Storages/StorageURL.cpp index 9aaf8dcaa8408..1dc0c4f260203 100644 --- a/src/Storages/StorageURL.cpp +++ b/src/Storages/StorageURL.cpp @@ -193,12 +193,14 @@ IStorageURLBase::IStorageURLBase( const HTTPHeaderEntries & headers_, const String & http_method_, ASTPtr partition_by_, - bool distributed_processing_) + bool distributed_processing_, + std::optional table_allow_aggregate_function_states_) : IStorage(table_id_) , uri(uri_) , compression_method(chooseCompressionMethod(Poco::URI(uri_).getPath(), compression_method_)) , format_name(format_name_) , format_settings(format_settings_) + , table_allow_aggregate_function_states(table_allow_aggregate_function_states_) , headers(headers_) , http_method(http_method_) , partition_by(partition_by_) @@ -212,17 +214,24 @@ IStorageURLBase::IStorageURLBase( if (columns_.empty()) { ColumnsDescription columns; + const auto inference_format_settings + = withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, context_); if (format_name == "auto") - std::tie(columns, format_name) = getTableStructureAndFormatFromData(uri, compression_method, headers, format_settings, context_); + std::tie(columns, format_name) = getTableStructureAndFormatFromData(uri, compression_method, headers, inference_format_settings, context_); else - columns = getTableStructureFromData(format_name, uri, compression_method, headers, format_settings, context_); + columns = getTableStructureFromData(format_name, uri, compression_method, headers, inference_format_settings, context_); storage_metadata.setColumns(columns); } else { if (format_name == "auto") - format_name = getTableStructureAndFormatFromData(uri, compression_method, headers, format_settings, context_).second; + format_name = getTableStructureAndFormatFromData( + uri, + compression_method, + headers, + withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, context_), + context_).second; /// We don't allow special columns in URL storage. if (!columns_.hasOnlyOrdinary()) @@ -1500,6 +1509,8 @@ void StorageURLWithFailover::read( SinkToStoragePtr IStorageURLBase::write(const ASTPtr & query, const StorageMetadataPtr & metadata_snapshot, ContextPtr context, bool /*async_insert*/) { + const auto query_format_settings = withAllowAggregateFunctionStatesForQuery(format_settings, table_allow_aggregate_function_states, context); + if (http_method.empty()) http_method = Poco::Net::HTTPRequest::HTTP_POST; @@ -1524,7 +1535,7 @@ SinkToStoragePtr IStorageURLBase::write(const ASTPtr & query, const StorageMetad partition_strategy, uri, format_name, - format_settings, + query_format_settings, metadata_snapshot->getSampleBlock(), context, getHTTPTimeouts(context), @@ -1538,7 +1549,7 @@ SinkToStoragePtr IStorageURLBase::write(const ASTPtr & query, const StorageMetad return std::make_shared( uri, format_name, - format_settings, + query_format_settings, metadata_snapshot->getSampleBlock(), context, getHTTPTimeouts(context), @@ -1589,7 +1600,8 @@ StorageURL::StorageURL( const HTTPHeaderEntries & headers_, const String & http_method_, ASTPtr partition_by_, - bool distributed_processing_) + bool distributed_processing_, + std::optional table_allow_aggregate_function_states_) : IStorageURLBase( uri_, context_, @@ -1603,7 +1615,8 @@ StorageURL::StorageURL( headers_, http_method_, partition_by_, - distributed_processing_) + distributed_processing_, + table_allow_aggregate_function_states_) { context_->getRemoteHostFilter().checkURL(Poco::URI(uri)); context_->getHTTPHeaderFilter().checkAndNormalizeHeaders(headers); @@ -2584,6 +2597,8 @@ void registerStorageURL(StorageFactory & factory) ASTs & engine_args = args.engine_args; auto format_settings = StorageURL::getFormatSettingsFromArgs(args); + const auto table_allow_aggregate_function_states = extractTableAllowAggregateFunctionStates( + format_settings, args.storage_def->settings ? &args.storage_def->settings->changes : nullptr); auto context = args.getLocalContext(); ASTPtr partition_by; @@ -2610,7 +2625,8 @@ void registerStorageURL(StorageFactory & factory) config.headers, config.http_method, partition_by, - /* distributed_processing */ false); + /* distributed_processing */ false, + table_allow_aggregate_function_states); } if (args.mode <= LoadingStrictnessLevel::CREATE) @@ -2665,7 +2681,10 @@ void registerStorageURL(StorageFactory & factory) partition_by, /* order_by */ nullptr, /* is_table_function */ false, - /* lazy_init */ false); + /* lazy_init */ false, + /* updated_configuration */ false, + /* sample_path */ std::nullopt, + table_allow_aggregate_function_states); }, { .supports_settings = true, diff --git a/src/Storages/StorageURL.h b/src/Storages/StorageURL.h index b6c5cdd25b7d3..f54d14b906495 100644 --- a/src/Storages/StorageURL.h +++ b/src/Storages/StorageURL.h @@ -98,7 +98,8 @@ class IStorageURLBase : public IStorage const HTTPHeaderEntries & headers_ = {}, const String & method_ = "", ASTPtr partition_by = nullptr, - bool distributed_processing_ = false); + bool distributed_processing_ = false, + std::optional table_allow_aggregate_function_states_ = std::nullopt); String uri; CompressionMethod compression_method; @@ -108,6 +109,8 @@ class IStorageURLBase : public IStorage // For `url` table function, we use settings from current query context. // In this case, format_settings is not set. std::optional format_settings; + /// The table's own `allow_aggregate_function_states_in_open_formats`, when its `SETTINGS` give one. + std::optional table_allow_aggregate_function_states; HTTPHeaderEntries headers; String http_method; /// For insert can choose Put instead of default Post. ASTPtr partition_by; @@ -355,7 +358,8 @@ class StorageURL : public IStorageURLBase const HTTPHeaderEntries & headers_ = {}, const String & method_ = "", ASTPtr partition_by_ = nullptr, - bool distributed_processing_ = false); + bool distributed_processing_ = false, + std::optional table_allow_aggregate_function_states_ = std::nullopt); String getName() const override { diff --git a/src/TableFunctions/TableFunctionFile.cpp b/src/TableFunctions/TableFunctionFile.cpp index fe32bf92b003c..d558ac951d46f 100644 --- a/src/TableFunctions/TableFunctionFile.cpp +++ b/src/TableFunctions/TableFunctionFile.cpp @@ -159,6 +159,7 @@ StoragePtr TableFunctionFile::getStorage( ConstraintsDescription{}, String{}, global_context->getSettingsRef()[Setting::rename_files_after_processing], + std::nullopt /*table_allow_aggregate_function_states*/, }; if (fd >= 0) diff --git a/src/TableFunctions/TableFunctionFileCluster.cpp b/src/TableFunctions/TableFunctionFileCluster.cpp index fc326d76faf3c..7a75b486b7673 100644 --- a/src/TableFunctions/TableFunctionFileCluster.cpp +++ b/src/TableFunctions/TableFunctionFileCluster.cpp @@ -32,7 +32,8 @@ StoragePtr TableFunctionFileCluster::getStorage( columns, ConstraintsDescription{}, String{}, - context->getSettingsRef()[Setting::rename_files_after_processing]}; + context->getSettingsRef()[Setting::rename_files_after_processing], + std::nullopt /*table_allow_aggregate_function_states*/}; storage = std::make_shared(StorageFile::FileSource::parse(filename, context), /* distributed_processing = */ true, args); } diff --git a/tests/integration/helpers/export_partition_helpers.py b/tests/integration/helpers/export_partition_helpers.py index d0cb8eb3d379b..757d782d95afc 100644 --- a/tests/integration/helpers/export_partition_helpers.py +++ b/tests/integration/helpers/export_partition_helpers.py @@ -335,6 +335,7 @@ def make_iceberg_s3( url=None, s3_retry_attempts=3, if_not_exists=False, + settings=None, ): """Create an IcebergS3 table at a MinIO prefix. @@ -350,7 +351,8 @@ def make_iceberg_s3( ENGINE = IcebergS3('{url}', '{MINIO_USER}', '{MINIO_PASS}') {pclause} SETTINGS s3_retry_attempts = {s3_retry_attempts} - """ + """, + settings=settings, ) diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index 13af9d8a780de..032634389e1d1 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -4249,3 +4249,66 @@ def test_datalake_catalog_wrapper_object_storage_cluster(started_cluster, engine node2.query(f"DROP DATABASE IF EXISTS {catalog_db}") if cluster_mode == "database": node.query(f"DROP DATABASE IF EXISTS {cluster_catalog_name}") + + +def test_clickhouse_type_annotation_survives_catalog(started_cluster): + node = started_cluster.instances["node1"] + ns, tbl = f"ann_{uuid.uuid4().hex}", "t" + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + node.query( + f""" +CREATE TABLE {CATALOG_NAME}.`{ns}.{tbl}` (id Int64, s SimpleAggregateFunction(sum, Int64)) +ENGINE = IcebergS3('http://minio1:9001/warehouse-rest/{ns}/', '{minio_access_key}', '{minio_secret_key}') + """, + settings={ + "allow_experimental_database_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + catalog = load_catalog_impl(started_cluster) + + def metadata(): + loc = catalog.load_table(f"{ns}.{tbl}").metadata_location + bucket, key = loc[len("s3://"):].split("/", 1) + return json.loads(get_file_contents(started_cluster.minio_client, bucket, key)) + + def annotations(schema_id=None): + # The `clickhouse.type..` entry with the greatest schema id not above `schema_id` is in effect. + # A field without an entry is `None`, and an empty entry records that the field has no ClickHouse type any more. + meta = metadata() + if schema_id is None: + schema_id = meta["current-schema-id"] + schema = next(s for s in meta["schemas"] if s["schema-id"] == schema_id) + entries = {} + for key, value in meta.get("properties", {}).items(): + parts = key.split(".") + if len(parts) == 4 and parts[:2] == ["clickhouse", "type"] and parts[2].isdigit() and parts[3].isdigit(): + field_id, entry_schema_id = int(parts[2]), int(parts[3]) + if entry_schema_id <= schema_id and entry_schema_id >= entries.get(field_id, (-1, None))[0]: + entries[field_id] = (entry_schema_id, value) + return {f["name"]: entries.get(f["id"], (None, None))[1] for f in schema["fields"]} + + # 1. Survives CREATE through the REST catalog? + assert annotations()["s"] == "SimpleAggregateFunction(sum, Int64)" + # 2. Survives a commit by another engine? + arrow_schema = pa.schema([pa.field("id", pa.int64(), nullable=False), + pa.field("s", pa.int64(), nullable=False)]) + catalog.load_table(f"{ns}.{tbl}").append( + pa.Table.from_pylist([{"id": 1, "s": 2}], schema=arrow_schema)) + assert annotations()["s"] == "SimpleAggregateFunction(sum, Int64)" + # 3. ClickHouse still sees the type + assert "SimpleAggregateFunction" in node.query(f"DESCRIBE {CATALOG_NAME}.`{ns}.{tbl}`") + # 4. ALTER through the catalog records the annotation and clears it + alter_settings = {"allow_insert_into_iceberg": 1} + node.query( + f"ALTER TABLE {CATALOG_NAME}.`{ns}.{tbl}` ADD COLUMN m SimpleAggregateFunction(max, Nullable(Int64))", + settings=alter_settings) + assert annotations()["m"] == "SimpleAggregateFunction(max, Nullable(Int64))" + schema_id_before_modify = metadata()["current-schema-id"] + node.query(f"ALTER TABLE {CATALOG_NAME}.`{ns}.{tbl}` MODIFY COLUMN s Int64", settings=alter_settings) + # Only the annotation changes, so the catalog keeps the current schema. + assert metadata()["current-schema-id"] == schema_id_before_modify + assert annotations() == {"id": None, "s": "", "m": "SimpleAggregateFunction(max, Nullable(Int64))"} + # The schema the first rows were written with keeps its annotation. + assert annotations(0) == {"id": None, "s": "SimpleAggregateFunction(sum, Int64)"} + assert node.query(f"SELECT id, s, toTypeName(s) FROM {CATALOG_NAME}.`{ns}.{tbl}`") == "1\t2\tInt64\n" diff --git a/tests/integration/test_export_merge_tree_part_to_iceberg/test.py b/tests/integration/test_export_merge_tree_part_to_iceberg/test.py index c1197373be39a..90d3c17cc1a3d 100644 --- a/tests/integration/test_export_merge_tree_part_to_iceberg/test.py +++ b/tests/integration/test_export_merge_tree_part_to_iceberg/test.py @@ -16,6 +16,7 @@ test_export_part_multi_column_partition_key_success – composite (a, b, c) partition key round-trips test_export_part_partition_key_mismatch_variants_are_rejected (parametrized) – partition key column reordering, cardinality mismatches, and transform-expression reordering between src/dst are all rejected synchronously + test_export_part_aggregate_function_states – AggregateFunction / SimpleAggregateFunction states survive the export """ import logging @@ -1508,3 +1509,39 @@ def test_export_part_tuple_subcolumn_partition_key_iceberg_rejected(cluster): node.query(f"DROP TABLE IF EXISTS {mt} SYNC") node.query(f"DROP TABLE IF EXISTS {iceberg}") + + +def test_export_part_aggregate_function_states(cluster): + node = cluster.instances["node1"] + sfx = unique_suffix() + mt = f"mt_agg_states_{sfx}" + iceberg = f"iceberg_agg_states_{sfx}" + states = {"allow_aggregate_function_states_in_open_formats": 1} + + columns = ( + "k Int32, u AggregateFunction(uniq, UInt64), s SimpleAggregateFunction(sum, UInt64)" + ) + + make_mt(node, mt, columns, "k", order_by="k") + make_iceberg_s3(node, iceberg, columns, "k", settings=states) + + node.query( + f"INSERT INTO {mt} " + f"SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)), sumSimpleState(number) " + f"FROM numbers(200) GROUP BY number % 2" + ) + + part = get_part(node, mt, "0") + export_part(node, mt, part, iceberg, extra_settings="allow_aggregate_function_states_in_open_formats = 1") + wait_for_export_part(node, mt, part) + assert_part_log(node, mt, part) + + exported = node.query( + f"SELECT k, uniqMerge(u), sum(s) FROM {iceberg} GROUP BY k ORDER BY k", settings=states + ) + assert exported == node.query( + f"SELECT k, uniqMerge(u), sum(s) FROM {mt} WHERE k = 0 GROUP BY k ORDER BY k" + ), f"Exported states do not match the source table:\n{exported}" + + node.query(f"DROP TABLE IF EXISTS {mt} SYNC") + node.query(f"DROP TABLE IF EXISTS {iceberg}") diff --git a/tests/integration/test_export_partition_to_iceberg/configs/users.d/profile.xml b/tests/integration/test_export_partition_to_iceberg/configs/users.d/profile.xml index 518f297089297..12b233f2753b9 100644 --- a/tests/integration/test_export_partition_to_iceberg/configs/users.d/profile.xml +++ b/tests/integration/test_export_partition_to_iceberg/configs/users.d/profile.xml @@ -2,6 +2,8 @@ 3 + + 0 diff --git a/tests/integration/test_export_partition_to_iceberg/test_schema_match.py b/tests/integration/test_export_partition_to_iceberg/test_schema_match.py index 32de3888ec755..4718411516ff0 100644 --- a/tests/integration/test_export_partition_to_iceberg/test_schema_match.py +++ b/tests/integration/test_export_partition_to_iceberg/test_schema_match.py @@ -983,3 +983,49 @@ def test_export_partition_all_iceberg_types_lossy(cluster, source_engine): f"SELECT abs(f - 2.718281828459045) < 1e-6, abs(f - 2.718281828459045) > 1e-9 FROM {iceberg_table}" ).strip() assert f_checks == "1\t1", f"Expected Float32 precision loss within tolerance, got: {f_checks!r}" + + +def test_export_partition_aggregate_function_states(cluster, source_engine): + node = cluster.instances["replica1"] + + uid = unique_suffix() + mt_table = f"mt_agg_states_{uid}" + iceberg_table = f"iceberg_agg_states_{uid}" + + columns = ( + "k Int32, u AggregateFunction(uniq, UInt64), s SimpleAggregateFunction(sum, UInt64)" + ) + # The profile disables the setting, so the export worker can write the states only with the value the + # export query recorded for it. + states = {"allow_aggregate_function_states_in_open_formats": 1} + + make_source(node, mt_table, columns, "k", engine=source_engine, order_by="k", replica_name="replica1") + make_iceberg_s3( + node, + iceberg_table, + columns, + partition_by="k", + settings=states, + ) + + node.query( + f"INSERT INTO {mt_table} " + f"SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)), sumSimpleState(number) " + f"FROM numbers(200) GROUP BY number % 2" + ) + + node.query( + f"ALTER TABLE {mt_table} EXPORT PARTITION ID '0' TO TABLE {iceberg_table}", + settings={ + "allow_insert_into_iceberg": 1, + **states, + }, + ) + wait_for_export_status(node, mt_table, iceberg_table, "0", "COMPLETED") + + exported = node.query( + f"SELECT k, uniqMerge(u), sum(s) FROM {iceberg_table} GROUP BY k ORDER BY k", settings=states + ) + assert exported == node.query( + f"SELECT k, uniqMerge(u), sum(s) FROM {mt_table} WHERE k = 0 GROUP BY k ORDER BY k" + ), f"Exported states do not match the source partition:\n{exported}" diff --git a/tests/integration/test_storage_iceberg_with_spark/test_aggregate_function_states.py b/tests/integration/test_storage_iceberg_with_spark/test_aggregate_function_states.py new file mode 100644 index 0000000000000..1c6e666d0adf1 --- /dev/null +++ b/tests/integration/test_storage_iceberg_with_spark/test_aggregate_function_states.py @@ -0,0 +1,183 @@ +import glob +import json +import os +import re + +import pytest + +from helpers.iceberg_utils import ( + create_iceberg_table, + default_download_directory, + default_upload_directory, + get_uuid_str, +) + + +STATES = {"allow_aggregate_function_states_in_open_formats": 1} +WRITE_SETTINGS = {**STATES, "allow_insert_into_iceberg": 1} + +# Spark's Arrow reader does not accept the UINT_64 converted type written for UInt64. +SPARK_SCHEMA = "(k Int32, u AggregateFunction(uniq, UInt64), s SimpleAggregateFunction(sum, Int64))" + +WAREHOUSE = "/var/lib/clickhouse/user_files/iceberg_data/default" + + +def insert_states(instance, table_name): + instance.query( + f""" + INSERT INTO {table_name} (k, u, s) + SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)), sumSimpleState(toInt64(number)) + FROM numbers(200) + GROUP BY number % 2 + """, + settings=WRITE_SETTINGS, + ) + + +def latest_metadata(table_name): + files = glob.glob(os.path.join(WAREHOUSE, table_name, "metadata", "v*.metadata.json")) + assert files, f"No metadata JSON downloaded for {table_name}" + newest = max(files, key=lambda path: int(re.fullmatch(r"v(\d+)\.metadata\.json", os.path.basename(path)).group(1))) + with open(newest) as f: + return json.load(f) + + +def fields_by_name(metadata): + schema_id = metadata["current-schema-id"] + for schema in metadata["schemas"]: + if schema["schema-id"] == schema_id: + return {field["name"]: field for field in schema["fields"]} + raise AssertionError(f"Schema {schema_id} not found in {metadata['schemas']}") + + +@pytest.mark.parametrize("storage_type", ["s3"]) +def test_aggregate_states_with_spark(started_cluster_iceberg_with_spark, storage_type): + instance = started_cluster_iceberg_with_spark.instances["node1"] + spark = started_cluster_iceberg_with_spark.spark_session + TABLE_NAME = "test_agg_states_spark_" + storage_type + "_" + get_uuid_str() + + create_iceberg_table( + storage_type, + instance, + TABLE_NAME, + started_cluster_iceberg_with_spark, + SPARK_SCHEMA, + format_version=2, + settings=STATES, + ) + insert_states(instance, TABLE_NAME) + + default_download_directory( + started_cluster_iceberg_with_spark, + storage_type, + f"{WAREHOUSE}/{TABLE_NAME}/", + f"{WAREHOUSE}/{TABLE_NAME}/", + ) + + with open(f"{WAREHOUSE}/{TABLE_NAME}/metadata/version-hint.text", "wb") as f: + f.write(b"1") + + df = spark.read.format("iceberg").load(f"{WAREHOUSE}/{TABLE_NAME}") + assert dict(df.dtypes) == {"k": "int", "u": "binary", "s": "bigint"} + spark_rows = {row["k"]: (bytes(row["u"]).hex().upper(), row["s"]) for row in df.collect()} + expected = instance.query( + f"SELECT k, hex(u), s FROM {TABLE_NAME} ORDER BY k FORMAT TSV", settings=STATES + ).strip() + assert spark_rows == { + int(k): (state_hex, int(sum_value)) + for k, state_hex, sum_value in (line.split("\t") for line in expected.split("\n")) + } + + appended = instance.query( + "SELECT toInt32(number % 2) AS k, hex(uniqState(toUInt64(number % 23))), sum(toInt64(number))" + " FROM numbers(200, 100) GROUP BY k ORDER BY k FORMAT TSV" + ).strip() + values = ", ".join( + f"({k}, X'{state_hex}', {sum_value})" + for k, state_hex, sum_value in (line.split("\t") for line in appended.split("\n")) + ) + spark.sql(f"INSERT INTO {TABLE_NAME} VALUES {values}") + + # The appended file must carry bounds for the column holding the states. + u_field_id = fields_by_name(latest_metadata(TABLE_NAME))["u"]["id"] + spark_files = spark.sql( + f"SELECT lower_bounds, upper_bounds FROM spark_catalog.default.{TABLE_NAME}.files WHERE lower_bounds IS NOT NULL" + ).collect() + assert any( + u_field_id in (row["lower_bounds"] or {}) and u_field_id in (row["upper_bounds"] or {}) for row in spark_files + ), f"No data file has bounds for field {u_field_id}: {spark_files}" + + default_upload_directory( + started_cluster_iceberg_with_spark, + storage_type, + f"{WAREHOUSE}/{TABLE_NAME}/", + f"{WAREHOUSE}/{TABLE_NAME}/", + ) + + assert instance.query( + f"SELECT k, uniqMerge(u), sum(s) FROM {TABLE_NAME} GROUP BY k ORDER BY k", settings=STATES + ) == instance.query( + "SELECT toInt32(number % 2) AS k, uniq(toUInt64(number % 23)), sum(number)" + " FROM numbers(300) GROUP BY k ORDER BY k" + ) + + # A filter on the states makes pruning consider the bounds Spark wrote for them, which are not ClickHouse values. + assert instance.query( + f"SELECT k, uniqMerge(u) FROM {TABLE_NAME} WHERE finalizeAggregation(u) > 0 GROUP BY k ORDER BY k", settings=STATES + ) == instance.query( + "SELECT toInt32(number % 2) AS k, uniq(toUInt64(number % 23)) FROM numbers(300) GROUP BY k ORDER BY k" + ) + + +@pytest.mark.parametrize("storage_type", ["s3"]) +def test_aggregate_states_after_spark_schema_evolution(started_cluster_iceberg_with_spark, storage_type): + """Spark evolves annotated fields as the Iceberg spec allows: the table stays readable, and the evolved fields read as their Iceberg types.""" + instance = started_cluster_iceberg_with_spark.instances["node1"] + spark = started_cluster_iceberg_with_spark.spark_session + TABLE_NAME = "test_agg_states_spark_evolution_" + storage_type + "_" + get_uuid_str() + + create_iceberg_table( + storage_type, + instance, + TABLE_NAME, + started_cluster_iceberg_with_spark, + "(k Int32, u AggregateFunction(uniq, UInt64), m SimpleAggregateFunction(max, Int32))", + format_version=2, + settings=STATES, + ) + instance.query( + f""" + INSERT INTO {TABLE_NAME} (k, u, m) + SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)), maxSimpleState(toInt32(number)) + FROM numbers(200) + GROUP BY number % 2 + """, + settings=WRITE_SETTINGS, + ) + expected = instance.query(f"SELECT k, hex(u), m FROM {TABLE_NAME} ORDER BY k", settings=STATES) + + default_download_directory( + started_cluster_iceberg_with_spark, + storage_type, + f"{WAREHOUSE}/{TABLE_NAME}/", + f"{WAREHOUSE}/{TABLE_NAME}/", + ) + + with open(f"{WAREHOUSE}/{TABLE_NAME}/metadata/version-hint.text", "wb") as f: + f.write(b"1") + + spark.sql(f"ALTER TABLE {TABLE_NAME} ALTER COLUMN u DROP NOT NULL") + spark.sql(f"ALTER TABLE {TABLE_NAME} ALTER COLUMN m TYPE BIGINT") + + default_upload_directory( + started_cluster_iceberg_with_spark, + storage_type, + f"{WAREHOUSE}/{TABLE_NAME}/", + f"{WAREHOUSE}/{TABLE_NAME}/", + ) + + assert ( + instance.query(f"SELECT toTypeName(u), toTypeName(m) FROM {TABLE_NAME} LIMIT 1", settings=STATES) + == "Nullable(String)\tInt64\n" + ) + assert instance.query(f"SELECT k, hex(u), m FROM {TABLE_NAME} ORDER BY k", settings=STATES) == expected diff --git a/tests/queries/0_stateless/02902_topKGeneric_deserialization_memory.sql b/tests/queries/0_stateless/02902_topKGeneric_deserialization_memory.sql index 3228810e0baa1..8f5c0731948e7 100644 --- a/tests/queries/0_stateless/02902_topKGeneric_deserialization_memory.sql +++ b/tests/queries/0_stateless/02902_topKGeneric_deserialization_memory.sql @@ -6,4 +6,5 @@ SELECT topKResampleState(1048576, 257, 65536, 10)(toString(number), number) FROM numbers(3) -FORMAT Parquet; -- { clientError UNKNOWN_TYPE } +SETTINGS allow_aggregate_function_states_in_open_formats = 0 +FORMAT Parquet; -- { clientError SUPPORT_IS_DISABLED } diff --git a/tests/queries/0_stateless/04673_parquet_aggregate_function_state.reference b/tests/queries/0_stateless/04673_parquet_aggregate_function_state.reference new file mode 100644 index 0000000000000..70cd6447ed809 --- /dev/null +++ b/tests/queries/0_stateless/04673_parquet_aggregate_function_state.reference @@ -0,0 +1,78 @@ +-- with the setting disabled writing a state is refused +1 +-- a SimpleAggregateFunction is an ordinary value of its storage type, so it needs no setting +s SimpleAggregateFunction(sum, UInt64) +-- states round-trip: merged per group +0 17 1683 +1 17 1617 +2 17 1650 +-- an explicit structure overrides the recorded type, so the states read as their bytes +String 17 +-- a column chunk holding both a dictionary page and a plain page +['PLAIN','RLE_DICTIONARY'] +500 1 +-- a state pinned to a non-default version keeps that version +AggregateFunction(sumMap, Array(UInt8), Array(UInt32)) +1 +-- an annotation naming an aggregate function this server does not have breaks only its column +1 +k UInt8 +s SimpleAggregateFunction(sum, UInt64) +3 +-- every annotated type this writer can produce still reads back, values intact +num SimpleAggregateFunction(sum, UInt64) +str SimpleAggregateFunction(anyLast, String) +nullable SimpleAggregateFunction(anyLast, Nullable(String)) +low_cardinality SimpleAggregateFunction(anyLast, LowCardinality(String)) +arr SimpleAggregateFunction(anyLast, Array(UInt64)) +m SimpleAggregateFunction(anyLast, Map(String, UInt64)) +d SimpleAggregateFunction(anyLast, Date) +dt SimpleAggregateFunction(anyLast, DateTime(\'UTC\')) +dt64 SimpleAggregateFunction(anyLast, DateTime64(4, \'UTC\')) +e SimpleAggregateFunction(anyLast, Enum8(\'a\' = 1, \'b\' = 2)) +ip4 SimpleAggregateFunction(anyLast, IPv4) +ip6 SimpleAggregateFunction(anyLast, IPv6) +i128 SimpleAggregateFunction(anyLast, Int128) +fs SimpleAggregateFunction(anyLast, FixedString(16)) +uu SimpleAggregateFunction(anyLast, UUID) +dec SimpleAggregateFunction(anyLast, Decimal(18, 4)) +state AggregateFunction(uniq, UInt64) +tup Tuple(AggregateFunction(uniq, UInt64), UInt64) +arr_state Array(AggregateFunction(uniq, UInt64)) +Row 1: +────── +num: 3 +str: abc +nullable: xyz +low_cardinality: lc +arr: [1,2] +m: {'k':7} +d: 2020-01-02 +dt: 2020-01-02 03:04:05 +dt64: 2020-01-02 03:04:05.1234 +e: b +ip4: 1.2.3.4 +ip6: ::1 +i128: 170141183460469231731687303715884105727 +hex(fs): 66697865640000000000000000000000 +uu: 00000000-0000-0000-0000-000000000001 +dec: 1.25 +uniq_state: 3 +uniq_in_tuple: 3 +plain_in_tuple: 7 +uniq_in_array: [3,3] +-- the nullability the reader is told to infer applies to plain columns, not to recorded types +k Nullable(UInt8) +u AggregateFunction(uniq, UInt8) +s SimpleAggregateFunction(sum, UInt64) +k UInt8 +u AggregateFunction(uniq, UInt8) +s SimpleAggregateFunction(sum, UInt64) +1 +-- a recorded type that re-reads the stored bytes as something else is refused +1 +-- with the setting disabled a state column reads as String, even if a schema inferred with it enabled is cached +k UInt8 +u AggregateFunction(uniq, UInt8) +k UInt8 +u String diff --git a/tests/queries/0_stateless/04673_parquet_aggregate_function_state.sh b/tests/queries/0_stateless/04673_parquet_aggregate_function_state.sh new file mode 100755 index 0000000000000..29cd99bc1eaf0 --- /dev/null +++ b/tests/queries/0_stateless/04673_parquet_aggregate_function_state.sh @@ -0,0 +1,186 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +. "$CUR_DIR"/../shell_config.sh + +SUFFIX="${CLICKHOUSE_DATABASE}_${RANDOM}" +FILE="agg_state_${SUFFIX}.parquet" +MIXED="agg_state_mixed_${SUFFIX}.parquet" +VERSIONED="agg_state_versioned_${SUFFIX}.parquet" +REFUSED="agg_state_refused_${SUFFIX}.parquet" +SIMPLE="agg_state_simple_${SUFFIX}.parquet" +UNKNOWN="agg_state_unknown_${SUFFIX}.parquet" +MATRIX="agg_state_matrix_${SUFFIX}.parquet" +RETYPED_SOURCE="agg_state_retyped_source_${SUFFIX}.parquet" +RETYPED="agg_state_retyped_${SUFFIX}.parquet" +CACHED="agg_state_cached_${SUFFIX}.parquet" + +cleanup() +{ + rm -f "${USER_FILES_PATH}/${FILE}" "${USER_FILES_PATH}/${MIXED}" \ + "${USER_FILES_PATH}/${VERSIONED}" "${USER_FILES_PATH}/${REFUSED}" \ + "${USER_FILES_PATH}/${SIMPLE}" "${USER_FILES_PATH}/${UNKNOWN}" "${USER_FILES_PATH}/${MATRIX}" \ + "${USER_FILES_PATH}/${RETYPED_SOURCE}" "${USER_FILES_PATH}/${RETYPED}" \ + "${USER_FILES_PATH}/${CACHED}" +} +trap cleanup EXIT + +STATES="--allow_aggregate_function_states_in_open_formats=1" +NO_STATES="--allow_aggregate_function_states_in_open_formats=0" +SKIP="--input_format_parquet_skip_columns_with_unsupported_types_in_schema_inference=1" +NO_CACHE="--schema_inference_use_cache_for_file=0" + +echo '-- with the setting disabled writing a state is refused' +if ${CLICKHOUSE_CLIENT} ${NO_STATES} --query " + INSERT INTO FUNCTION file('${REFUSED}', Parquet) SELECT uniqState(number) AS u FROM numbers(10) +" 2>&1 | grep -q "allow_aggregate_function_states_in_open_formats" +then + echo 1 +fi + +echo '-- a SimpleAggregateFunction is an ordinary value of its storage type, so it needs no setting' +${CLICKHOUSE_CLIENT} ${NO_STATES} --query " + INSERT INTO FUNCTION file('${SIMPLE}', Parquet) SELECT sumSimpleState(number) AS s FROM numbers(10) +" +${CLICKHOUSE_CLIENT} ${NO_STATES} --query "DESC file('${SIMPLE}', Parquet)" + +${CLICKHOUSE_CLIENT} ${STATES} --query " + INSERT INTO FUNCTION file('${FILE}', Parquet) + SELECT + number % 3 AS k, + uniqState(toUInt8(number % 17)) AS u, + sumSimpleState(number) AS s + FROM numbers(100) + GROUP BY k +" + + +echo '-- states round-trip: merged per group' +${CLICKHOUSE_CLIENT} ${STATES} --query " + SELECT k, uniqMerge(u), sum(s) FROM file('${FILE}', Parquet) GROUP BY k ORDER BY k +" + +echo '-- an explicit structure overrides the recorded type, so the states read as their bytes' +${CLICKHOUSE_CLIENT} ${NO_STATES} --query " + SELECT any(toTypeName(u)), uniqMerge(CAST(u AS AggregateFunction(uniq, UInt8))) FROM file('${FILE}', Parquet, 'u String') +" + +echo '-- a column chunk holding both a dictionary page and a plain page' +${CLICKHOUSE_CLIENT} ${STATES} --query " + INSERT INTO FUNCTION file('${MIXED}', Parquet) + SELECT uniqState(number) AS u FROM numbers(2000) + GROUP BY number % 500 + SETTINGS output_format_parquet_max_dictionary_size = 20000, output_format_parquet_row_group_size = 100000 +" +${CLICKHOUSE_CLIENT} ${STATES} --query " + SELECT arraySort(tupleElement(arrayJoin(columns), 'encodings')) FROM file('${MIXED}', ParquetMetadata) +" +${CLICKHOUSE_CLIENT} ${STATES} --query " + SELECT count(), uniqMerge(u) = (SELECT uniq(number) FROM numbers(2000)) AS matches + FROM file('${MIXED}', Parquet) +" + +echo '-- a state pinned to a non-default version keeps that version' +${CLICKHOUSE_CLIENT} ${STATES} --query " + INSERT INTO FUNCTION file('${VERSIONED}', Parquet) + SELECT CAST(sumMapState([number % 3], [toUInt32(number)]) AS AggregateFunction(0, sumMap, Array(UInt8), Array(UInt32))) AS m + FROM numbers(100) +" +grep -ao 'AggregateFunction([0-9, ]*sumMap[^"]*' "${USER_FILES_PATH}/${VERSIONED}" +${CLICKHOUSE_CLIENT} ${STATES} --query " + SELECT sumMapMerge(m) = (SELECT sumMap([number % 3], [toUInt32(number)]) FROM numbers(100)) AS matches + FROM file('${VERSIONED}', Parquet) +" + +echo '-- an annotation naming an aggregate function this server does not have breaks only its column' +python3 -c " +import sys +data = open(sys.argv[1], 'rb').read() +open(sys.argv[2], 'wb').write(data.replace(b'AggregateFunction(uniq,', b'AggregateFunction(zzzz,')) +" "${USER_FILES_PATH}/${FILE}" "${USER_FILES_PATH}/${UNKNOWN}" +if ${CLICKHOUSE_CLIENT} ${STATES} ${NO_CACHE} --query "DESC file('${UNKNOWN}', Parquet)" 2>&1 \ + | grep -q "for column u in its .* metadata, which this server cannot resolve" +then + echo 1 +fi +${CLICKHOUSE_CLIENT} ${STATES} ${SKIP} ${NO_CACHE} --query "DESC file('${UNKNOWN}', Parquet)" +${CLICKHOUSE_CLIENT} ${STATES} ${SKIP} ${NO_CACHE} --query "SELECT sum(k) FROM file('${UNKNOWN}', Parquet)" + +echo '-- every annotated type this writer can produce still reads back, values intact' +${CLICKHOUSE_CLIENT} ${STATES} --query " + INSERT INTO FUNCTION file('${MATRIX}', Parquet) + SELECT + sumSimpleState(number) AS num, + anyLastSimpleState('abc') AS str, + anyLastSimpleState(CAST('xyz', 'Nullable(String)')) AS nullable, + CAST(anyLastSimpleState(toLowCardinality('lc')), + 'SimpleAggregateFunction(anyLast, LowCardinality(String))') AS low_cardinality, + anyLastSimpleState([toUInt64(1), toUInt64(2)]) AS arr, + anyLastSimpleState(map('k', toUInt64(7))) AS m, + anyLastSimpleState(toDate('2020-01-02')) AS d, + anyLastSimpleState(toDateTime('2020-01-02 03:04:05', 'UTC')) AS dt, + anyLastSimpleState(toDateTime64('2020-01-02 03:04:05.1234', 4, 'UTC')) AS dt64, + anyLastSimpleState(CAST('b', 'Enum8(''a'' = 1, ''b'' = 2)')) AS e, + anyLastSimpleState(toIPv4('1.2.3.4')) AS ip4, + anyLastSimpleState(toIPv6('::1')) AS ip6, + anyLastSimpleState(toInt128('170141183460469231731687303715884105727')) AS i128, + anyLastSimpleState(CAST('fixed', 'FixedString(16)')) AS fs, + anyLastSimpleState(toUUID('00000000-0000-0000-0000-000000000001')) AS uu, + anyLastSimpleState(toDecimal64('1.25', 4)) AS dec, + uniqState(number) AS state, + tuple(uniqState(number), toUInt64(7)) AS tup, + [uniqState(number), uniqState(number + 100)] AS arr_state + FROM numbers(3) +" +${CLICKHOUSE_CLIENT} ${STATES} --query "DESC file('${MATRIX}', Parquet)" +${CLICKHOUSE_CLIENT} ${STATES} --query " + SELECT num, str, nullable, low_cardinality, arr, m, d, dt, dt64, e, ip4, ip6, toString(i128) AS i128, hex(fs), uu, dec, + finalizeAggregation(state) AS uniq_state, finalizeAggregation(tup.1) AS uniq_in_tuple, tup.2 AS plain_in_tuple, + arrayMap(x -> finalizeAggregation(x), arr_state) AS uniq_in_array + FROM file('${MATRIX}', Parquet) + FORMAT Vertical +" + +echo '-- the nullability the reader is told to infer applies to plain columns, not to recorded types' +for nullable in 1 0; do + ${CLICKHOUSE_CLIENT} ${STATES} ${NO_CACHE} --schema_inference_make_columns_nullable=${nullable} --query "DESC file('${FILE}', Parquet)" \ + | cut -f1,2 +done +if diff \ + <(${CLICKHOUSE_CLIENT} ${STATES} ${NO_CACHE} --schema_inference_make_columns_nullable=1 --query "DESC file('${MATRIX}', Parquet)") \ + <(${CLICKHOUSE_CLIENT} ${STATES} ${NO_CACHE} --schema_inference_make_columns_nullable=0 --query "DESC file('${MATRIX}', Parquet)") \ + > /dev/null +then + echo 1 +fi + +echo '-- a recorded type that re-reads the stored bytes as something else is refused' +${CLICKHOUSE_CLIENT} ${STATES} --query " + INSERT INTO FUNCTION file('${RETYPED_SOURCE}', Parquet) + SELECT toUInt8(number) AS k, sumWithOverflowSimpleState(toInt64(number)) AS v FROM numbers(3) GROUP BY k +" +python3 -c " +import sys +old = b'SimpleAggregateFunction(sumWithOverflow, Int64)' +new = b'SimpleAggregateFunction(anyLast, DateTime64(9))' +assert len(old) == len(new) +data = open(sys.argv[1], 'rb').read() +assert old in data +open(sys.argv[2], 'wb').write(data.replace(old, new)) +" "${USER_FILES_PATH}/${RETYPED_SOURCE}" "${USER_FILES_PATH}/${RETYPED}" +if ${CLICKHOUSE_CLIENT} ${STATES} ${NO_CACHE} --query "DESC file('${RETYPED}', Parquet)" 2>&1 \ + | grep -q "reads as Int64" +then + echo 1 +fi + +echo '-- with the setting disabled a state column reads as String, even if a schema inferred with it enabled is cached' +${CLICKHOUSE_CLIENT} ${STATES} --query " + INSERT INTO FUNCTION file('${CACHED}', Parquet) + SELECT toUInt8(number % 3) AS k, uniqState(toUInt8(number)) AS u FROM numbers(30) GROUP BY k +" +# Ensure the file predates the cache entry despite one-second timestamp granularity. +touch -t 200001010000 "${USER_FILES_PATH}/${CACHED}" +${CLICKHOUSE_CLIENT} ${STATES} --query "DESC file('${CACHED}', Parquet)" +${CLICKHOUSE_CLIENT} ${NO_STATES} --query "DESC file('${CACHED}', Parquet)" diff --git a/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.reference b/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.reference new file mode 100644 index 0000000000000..b1a5823548d80 --- /dev/null +++ b/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.reference @@ -0,0 +1,18 @@ +widen +k Int32 +x SimpleAggregateFunction(max, Int64) +1 10 SimpleAggregateFunction(max, Int64) +2 20 SimpleAggregateFunction(max, Int64) +1 10 SimpleAggregateFunction(max, Int64) +2 20 SimpleAggregateFunction(max, Int64) +time travel +1 10 SimpleAggregateFunction(max, Int32) +drop the annotation +k Int32 +x Int64 +1 10 Int64 +2 20 Int64 +1 10 Int64 +2 20 Int64 +time travel +1 10 SimpleAggregateFunction(max, Int32) diff --git a/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.sh b/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.sh new file mode 100755 index 0000000000000..8849b2b521803 --- /dev/null +++ b/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# The ClickHouse type annotation of an Iceberg field is recorded per schema id, so after `MODIFY COLUMN` +# the older schema keeps the type its data was written with. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -euo pipefail + +TABLE="t_${CLICKHOUSE_DATABASE}_${RANDOM}_annotation" +TABLE_PATH="${USER_FILES_PATH}/${TABLE}/" + +cleanup() +{ + ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE}" + rm -rf "${TABLE_PATH}" +} +trap cleanup EXIT + +CLIENT="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1" + +${CLIENT} --query " + CREATE TABLE ${TABLE} (k Int32, x SimpleAggregateFunction(max, Int32)) + ENGINE = IcebergLocal('${TABLE_PATH}')" +${CLIENT} --query "INSERT INTO ${TABLE} VALUES (1, 10)" +SNAPSHOT=$(${CLIENT} --query "SELECT snapshot_id FROM system.iceberg_history WHERE database = currentDatabase() AND table = '${TABLE}'") + +check() +{ + ${CLIENT} --query "DESCRIBE TABLE ${TABLE}" | cut -f1,2 + ${CLIENT} --query "SELECT k, x, toTypeName(x) FROM ${TABLE} ORDER BY k" + ${CLIENT} --query "SELECT k, x, toTypeName(x) FROM icebergLocal('${TABLE_PATH}') ORDER BY k" + echo "time travel" + ${CLIENT} --query "SELECT k, x, toTypeName(x) FROM ${TABLE} ORDER BY k SETTINGS iceberg_snapshot_id = ${SNAPSHOT}" +} + +echo "widen" +${CLIENT} --query "ALTER TABLE ${TABLE} MODIFY COLUMN x SimpleAggregateFunction(max, Int64)" +${CLIENT} --query "INSERT INTO ${TABLE} VALUES (2, 20)" +check + +echo "drop the annotation" +${CLIENT} --query "ALTER TABLE ${TABLE} MODIFY COLUMN x Int64" +check diff --git a/tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.reference b/tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.reference new file mode 100644 index 0000000000000..b39305ce26d04 --- /dev/null +++ b/tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.reference @@ -0,0 +1,2 @@ +2026-01-01 00:00:00.123 +1 diff --git a/tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.sh b/tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.sh new file mode 100755 index 0000000000000..a997caa23b9d6 --- /dev/null +++ b/tests/queries/0_stateless/05429_iceberg_aggregate_function_state_annotated_bounds.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Iceberg bounds of an annotated `DateTime64(3)` field are microseconds and must not be read at scale 3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -euo pipefail + +TABLE="t_${CLICKHOUSE_DATABASE}_${RANDOM}_annotated_bounds" +TABLE_PATH="${USER_FILES_PATH}/${TABLE}/" + +cleanup() +{ + ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE}" + rm -rf "${TABLE_PATH}" +} +trap cleanup EXIT + +CLIENT="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1" + +${CLIENT} --query " + CREATE TABLE ${TABLE} (x SimpleAggregateFunction(max, DateTime64(3, 'UTC'))) + ENGINE = IcebergLocal('${TABLE_PATH}')" +${CLIENT} --query "INSERT INTO ${TABLE} VALUES ('2026-01-01 00:00:00.123')" +${CLIENT} --query "SELECT x FROM ${TABLE}" +${CLIENT} --query "SELECT count() FROM ${TABLE} WHERE x = toDateTime64('2026-01-01 00:00:00.123', 3, 'UTC')" diff --git a/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.reference b/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.reference new file mode 100644 index 0000000000000..bc33adaf2fcae --- /dev/null +++ b/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.reference @@ -0,0 +1,24 @@ +-- Iceberg, setting stored in the table, queries disable it +1 +0 23 19800 +1 23 20000 +2 +1 +0 23 19800 +1 23 20000 +1 23 20000 +10 23 19800 +-- Iceberg, setting not stored in the table +refused +0 +refused +refused +-- File, setting stored in the table, queries disable it +0 23 9900 +1 23 10000 +-- File, setting not stored in the table +refused +-- Iceberg, setting 0 stored in the table, queries enable it +refused +-- File, setting 0 stored in the table, queries enable it +refused diff --git a/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.sh b/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.sh new file mode 100755 index 0000000000000..c5ce2ac01182d --- /dev/null +++ b/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# `allow_aggregate_function_states_in_open_formats` in a table's `SETTINGS` is stored with the table and decides +# for every query on it, also after the table is re-attached. Without it in the table, the query setting decides. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -eu + +SETTING="allow_aggregate_function_states_in_open_formats" +OFF="--${SETTING}=0" +ICEBERG="t_${CLICKHOUSE_DATABASE}_${RANDOM}_states" +ICEBERG_PATH="${USER_FILES_PATH}/${ICEBERG}/" +ICEBERG_NOT_STORED="${ICEBERG}_not_stored" +ICEBERG_NOT_STORED_PATH="${USER_FILES_PATH}/${ICEBERG_NOT_STORED}/" +ICEBERG_REFUSED="${ICEBERG}_refused" + +cleanup() +{ + for table in "${ICEBERG}" "${ICEBERG_NOT_STORED}" "${ICEBERG_REFUSED}" file_states file_states_not_stored \ + file_states_refused; do + ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${table}" + done + rm -rf "${ICEBERG_PATH}" "${ICEBERG_NOT_STORED_PATH}" +} +trap cleanup EXIT + +CLIENT="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1" +COLUMNS="k Int32, u AggregateFunction(uniq, UInt64), s SimpleAggregateFunction(sum, Int64)" + +insert_states() +{ + local table=$1 + shift + ${CLIENT} "$@" --query " + INSERT INTO ${table} SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)), sumSimpleState(toInt64(number)) + FROM numbers(200) GROUP BY 1" 2>&1 +} + +select_states() +{ + local table=$1 + shift + ${CLIENT} "$@" --query "SELECT k, uniqMerge(u), sum(s) FROM ${table} GROUP BY k ORDER BY k" 2>&1 +} + +run() +{ + ${CLIENT} "$@" 2>&1 +} + +reattach() +{ + ${CLIENT} --query "DETACH TABLE $1" + ${CLIENT} --query "ATTACH TABLE $1" +} + +# Each gate names what it refuses, which the query text does not contain. +CREATE_OR_ALTER_REFUSED="has type .*, which Iceberg cannot express natively" +READ_REFUSED="Iceberg field with id [0-9]* records ClickHouse type" +PARQUET_WRITE_REFUSED="Writing aggregate function states of column 'u' into Parquet data format is disabled" + +expect_refusal() +{ + local message=$1 + shift + if "$@" | grep -q "${message}"; then echo "refused"; else echo "not refused"; fi +} + +echo "-- Iceberg, setting stored in the table, queries disable it" +${CLIENT} ${OFF} --query "CREATE TABLE ${ICEBERG} (${COLUMNS}) ENGINE = IcebergLocal('${ICEBERG_PATH}') SETTINGS ${SETTING} = 1" +${CLIENT} --query "SHOW CREATE TABLE ${ICEBERG}" | grep -c "${SETTING} = 1" +reattach "${ICEBERG}" +insert_states "${ICEBERG}" ${OFF} +insert_states "${ICEBERG}" ${OFF} +select_states "${ICEBERG}" ${OFF} +${CLIENT} ${OFF} --query "SELECT uniqExact(_path) FROM ${ICEBERG}" +${CLIENT} ${OFF} --allow_experimental_iceberg_compaction=1 --query "OPTIMIZE TABLE ${ICEBERG}" +${CLIENT} ${OFF} --query "SELECT uniqExact(_path) FROM ${ICEBERG}" +select_states "${ICEBERG}" ${OFF} +${CLIENT} ${OFF} --query "ALTER TABLE ${ICEBERG} UPDATE k = k + 10 WHERE k = 0" +select_states "${ICEBERG}" ${OFF} + +echo "-- Iceberg, setting not stored in the table" +expect_refusal "${CREATE_OR_ALTER_REFUSED}" run ${OFF} --query "CREATE TABLE ${ICEBERG_NOT_STORED} (${COLUMNS}) ENGINE = IcebergLocal('${ICEBERG_NOT_STORED_PATH}')" +${CLIENT} "--${SETTING}=1" --query "CREATE TABLE ${ICEBERG_NOT_STORED} (${COLUMNS}) ENGINE = IcebergLocal('${ICEBERG_NOT_STORED_PATH}')" +${CLIENT} --query "SHOW CREATE TABLE ${ICEBERG_NOT_STORED}" | grep -c "${SETTING}" || true +reattach "${ICEBERG_NOT_STORED}" +expect_refusal "Column 'extra' ${CREATE_OR_ALTER_REFUSED}" run ${OFF} --query "ALTER TABLE ${ICEBERG_NOT_STORED} ADD COLUMN extra AggregateFunction(max, UInt64)" +# A `SimpleAggregateFunction` holds ordinary values of its storage type, so it needs no setting. +run ${OFF} --query "ALTER TABLE ${ICEBERG_NOT_STORED} ADD COLUMN simple SimpleAggregateFunction(anyLast, Nullable(String))" +expect_refusal "${READ_REFUSED}" select_states "${ICEBERG_NOT_STORED}" ${OFF} + +echo "-- File, setting stored in the table, queries disable it" +${CLIENT} --query "CREATE TABLE file_states (${COLUMNS}) ENGINE = File(Parquet) SETTINGS ${SETTING} = 1" +reattach file_states +insert_states file_states ${OFF} +select_states file_states ${OFF} + +echo "-- File, setting not stored in the table" +${CLIENT} --query "CREATE TABLE file_states_not_stored (${COLUMNS}) ENGINE = File(Parquet)" +expect_refusal "${PARQUET_WRITE_REFUSED}" insert_states file_states_not_stored ${OFF} + +echo "-- Iceberg, setting 0 stored in the table, queries enable it" +expect_refusal "${READ_REFUSED}" run "--${SETTING}=1" --query " + CREATE TABLE ${ICEBERG_REFUSED} ENGINE = IcebergLocal('${ICEBERG_NOT_STORED_PATH}') SETTINGS ${SETTING} = 0" + +echo "-- File, setting 0 stored in the table, queries enable it" +${CLIENT} --query "CREATE TABLE file_states_refused (${COLUMNS}) ENGINE = File(Parquet) SETTINGS ${SETTING} = 0" +expect_refusal "${PARQUET_WRITE_REFUSED}" insert_states file_states_refused "--${SETTING}=1" diff --git a/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.reference b/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.reference new file mode 100644 index 0000000000000..6af1e5393b669 --- /dev/null +++ b/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.reference @@ -0,0 +1,3 @@ +-- the query disables the setting, the table enables it +0 23 +1 23 diff --git a/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.sh b/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.sh new file mode 100755 index 0000000000000..002d72eebb1e1 --- /dev/null +++ b/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# An Iceberg table read on a cluster passes its own `allow_aggregate_function_states_in_open_formats` to the other nodes +# together with its other settings, such as `iceberg_metadata_file_path`, so they decide over the query's value there too. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -eu + +SETTING="allow_aggregate_function_states_in_open_formats" +TABLE="t_${CLICKHOUSE_DATABASE}_${RANDOM}_states" +TABLE_PATH="${USER_FILES_PATH}/${TABLE}/" +PINNED="${TABLE}_pinned" + +cleanup() +{ + for table in "${TABLE}" "${PINNED}"; do + ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${table}" + done + rm -rf "${TABLE_PATH}" +} +trap cleanup EXIT + +CLIENT="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1" + +${CLIENT} --query " + CREATE TABLE ${TABLE} (k Int32, u AggregateFunction(uniq, UInt64)) + ENGINE = IcebergLocal('${TABLE_PATH}') + SETTINGS ${SETTING} = 1" +${CLIENT} --query "INSERT INTO ${TABLE} SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)) FROM numbers(200) GROUP BY 1" + +METADATA_FILE=$(cd "${TABLE_PATH}" && ls metadata/*.metadata.json | sort -V | tail -n 1) + +${CLIENT} --query " + CREATE TABLE ${PINNED} ENGINE = IcebergLocal('${TABLE_PATH}') + SETTINGS ${SETTING} = 1, iceberg_metadata_file_path = '${METADATA_FILE}'" + +echo "-- the query disables the setting, the table enables it" +${CLIENT} --query " + SELECT k, uniqMerge(u) FROM ${PINNED} GROUP BY k ORDER BY k + SETTINGS ${SETTING} = 0, object_storage_cluster = 'test_cluster_two_shards_localhost'" diff --git a/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.reference b/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.reference new file mode 100644 index 0000000000000..656ee1f9ceed9 --- /dev/null +++ b/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.reference @@ -0,0 +1,9 @@ +AggregateFunction(1, quantileDeterministic(0.5), Float64, UInt64) 49.5 +same type without the version +BAD_ARGUMENTS +AggregateFunction(1, quantileDeterministic(0.5), Float64, UInt64) 49.5 +explicit version 0 +BAD_ARGUMENTS +AggregateFunction(1, quantileDeterministic(0.5), Float64, UInt64) 49.5 +same version +AggregateFunction(1, quantileDeterministic(0.5), Float64, UInt64) 49.5 diff --git a/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.sh b/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.sh new file mode 100755 index 0000000000000..6233a4e124926 --- /dev/null +++ b/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# `MODIFY COLUMN` of an Iceberg table cannot change the state version of an `AggregateFunction` column, +# because the existing data files would be read with the new state layout. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -euo pipefail + +TABLE="t_${CLICKHOUSE_DATABASE}_${RANDOM}_state_version" +TABLE_PATH="${USER_FILES_PATH}/${TABLE}/" + +cleanup() +{ + ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE}" + rm -rf "${TABLE_PATH}" +} +trap cleanup EXIT + +CLIENT="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1 --allow_aggregate_function_states_in_open_formats=1" + +${CLIENT} --query " + CREATE TABLE ${TABLE} (k Int32, q AggregateFunction(quantileDeterministic(0.5), Float64, UInt64)) + ENGINE = IcebergLocal('${TABLE_PATH}')" +${CLIENT} --query " + INSERT INTO ${TABLE} SELECT 1, quantileDeterministicState(0.5)(toFloat64(number), number) FROM numbers(100)" + +check() +{ + ${CLIENT} --query "SELECT toTypeName(q), quantileDeterministicMerge(0.5)(q) FROM ${TABLE} GROUP BY 1" +} + +check + +echo "same type without the version" +(${CLIENT} --query " + ALTER TABLE ${TABLE} MODIFY COLUMN q AggregateFunction(quantileDeterministic(0.5), Float64, UInt64)" 2>&1 || true) \ + | grep -q "BAD_ARGUMENTS" && echo "BAD_ARGUMENTS" +check + +echo "explicit version 0" +(${CLIENT} --query " + ALTER TABLE ${TABLE} MODIFY COLUMN q AggregateFunction(0, quantileDeterministic(0.5), Float64, UInt64)" 2>&1 || true) \ + | grep -q "BAD_ARGUMENTS" && echo "BAD_ARGUMENTS" +check + +echo "same version" +${CLIENT} --query " + ALTER TABLE ${TABLE} MODIFY COLUMN q AggregateFunction(1, quantileDeterministic(0.5), Float64, UInt64)" +check diff --git a/tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.reference b/tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.reference new file mode 100644 index 0000000000000..d7f511c30520f --- /dev/null +++ b/tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.reference @@ -0,0 +1,3 @@ +2026-01-01 00:00:00.123 SimpleAggregateFunction(max, DateTime64(3, \'UTC\')) +1 +0 diff --git a/tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.sh b/tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.sh new file mode 100755 index 0000000000000..0ffe0ec12c7c0 --- /dev/null +++ b/tests/queries/0_stateless/05817_iceberg_aggregate_function_state_annotated_partition.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Iceberg partition values of an annotated `DateTime64(3)` field are microseconds and must not be read at scale 3. +# The annotation is added the way another engine could leave it: to a field that already is a partition source. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -euo pipefail + +TABLE="t_${CLICKHOUSE_DATABASE}_${RANDOM}_annotated_partition" +TABLE_PATH="${USER_FILES_PATH}/${TABLE}/" + +cleanup() +{ + ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE}" + rm -rf "${TABLE_PATH}" +} +trap cleanup EXIT + +CLIENT="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1 --session_timezone=UTC" + +${CLIENT} --query " + CREATE TABLE ${TABLE} (k UInt32, x DateTime64(6, 'UTC')) + ENGINE = IcebergLocal('${TABLE_PATH}') + PARTITION BY x" +${CLIENT} --query "INSERT INTO ${TABLE} VALUES (1, '2026-01-01 00:00:00.123')" +${CLIENT} --query "DROP TABLE ${TABLE}" + +# Write the next metadata version with the type annotation of field `x` (id 2) for schema 0. +python3 - "${TABLE_PATH}metadata" <<'EOF' +import glob, json, re, sys +directory = sys.argv[1] +version = max(int(re.search(r'/v(\d+)\.metadata\.json$', f).group(1)) for f in glob.glob(directory + '/v*.metadata.json')) +with open(f'{directory}/v{version}.metadata.json') as f: + metadata = json.load(f) +metadata.setdefault('properties', {})['clickhouse.type.2.0'] = "SimpleAggregateFunction(max, DateTime64(3, 'UTC'))" +with open(f'{directory}/v{version + 1}.metadata.json', 'w') as f: + json.dump(metadata, f) +EOF + +${CLIENT} --query "SELECT x, toTypeName(x) FROM icebergLocal('${TABLE_PATH}')" +${CLIENT} --query "SELECT count() FROM icebergLocal('${TABLE_PATH}') WHERE x = toDateTime64('2026-01-01 00:00:00.123', 3, 'UTC')" +${CLIENT} --query "SELECT count() FROM icebergLocal('${TABLE_PATH}') WHERE x != toDateTime64('2026-01-01 00:00:00.123', 3, 'UTC')"