diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 4951eda47549b..dfc81fa359d7b 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -1742,6 +1742,22 @@ 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"( +Apply the ClickHouse types recorded in Parquet files and Iceberg tables, and allow writing `AggregateFunction` states to +them. 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, the recorded types are not applied, so a `SimpleAggregateFunction(f, T)` column is `T` and a state column +reads as `String`. Writing an `AggregateFunction` column throws `SUPPORT_IS_DISABLED`. `SimpleAggregateFunction` types are +recorded on write either way. + +A table (for example with the `S3`, `File` or `IcebergS3` engine) takes the value from the `SETTINGS` clause of its +engine, or the server's value (from the server settings profile) without one. The query's value does not apply to a +table, only to a table function. +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 f93c54df707b1..66f09e460250a 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -52,6 +52,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() }); 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, the ClickHouse types recorded in them are not applied, a state column reads as `String`, and writing a state throws `SUPPORT_IS_DISABLED`."}, {"export_merge_tree_part_check_destination_schema_staleness_ms", 0, 5000, "New setting: how stale the latest Iceberg destination metadata version may be when each part export task checks that the destination schema and partition spec did not change since the export was scheduled."}, {"export_merge_tree_part_allow_lossy_cast", false, false, "The setting is obsolete. `EXPORT PART` and `EXPORT PARTITION` cast values the way `INSERT ... SELECT` does."}, }); diff --git a/src/DataTypes/DataTypeAggregateFunction.cpp b/src/DataTypes/DataTypeAggregateFunction.cpp index e2bfc0240759a..f23351bec9914 100644 --- a/src/DataTypes/DataTypeAggregateFunction.cpp +++ b/src/DataTypes/DataTypeAggregateFunction.cpp @@ -534,12 +534,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 +552,21 @@ 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; + }); +} + +} diff --git a/src/DataTypes/DataTypeAggregateFunction.h b/src/DataTypes/DataTypeAggregateFunction.h index 6774c89ae812b..5d10f0aad7353 100644 --- a/src/DataTypes/DataTypeAggregateFunction.h +++ b/src/DataTypes/DataTypeAggregateFunction.h @@ -102,4 +102,7 @@ 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); + } diff --git a/src/Databases/DataLake/GlueCatalog.cpp b/src/Databases/DataLake/GlueCatalog.cpp index e6cb3c06bf9b9..1035edb3446b2 100644 --- a/src/Databases/DataLake/GlueCatalog.cpp +++ b/src/Databases/DataLake/GlueCatalog.cpp @@ -87,6 +87,7 @@ namespace DB::FailPoints namespace DB::Setting { extern const SettingsBool allow_experimental_geo_types_in_iceberg; + extern const SettingsBool allow_aggregate_function_states_in_open_formats; extern const SettingsUInt64 s3_max_connections; extern const SettingsUInt64 s3_max_redirects; extern const SettingsUInt64 s3_retry_attempts; @@ -724,7 +725,10 @@ bool GlueCatalog::tryGetTableMetadata( auto metadata_object = getOrFetchMetadataObject(client, table_specific_properties->iceberg_metadata_file_location, result); const bool allow_geo_parser = getContext()->getSettingsRef()[DB::Setting::allow_experimental_geo_types_in_iceberg].value; - auto schema_processor = DB::Iceberg::IcebergSchemaProcessor(context_, allow_geo_parser); + auto schema_processor = DB::Iceberg::IcebergSchemaProcessor( + context_, + allow_geo_parser, + context_->getSettingsRef()[DB::Setting::allow_aggregate_function_states_in_open_formats].value); auto id = DB::IcebergMetadata::parseTableSchema(metadata_object, schema_processor, context_, log); auto parsed_schema = schema_processor.getClickHouseTableSchemaById(id); if (parsed_schema) @@ -1345,6 +1349,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 b672a53ae9936..5901ef8ddfdf9 100644 --- a/src/Databases/DataLake/RestCatalog.cpp +++ b/src/Databases/DataLake/RestCatalog.cpp @@ -87,6 +87,7 @@ namespace DB::ErrorCodes namespace DB::Setting { extern const SettingsBool allow_experimental_geo_types_in_iceberg; + extern const SettingsBool allow_aggregate_function_states_in_open_formats; } namespace DB::FailPoints @@ -356,7 +357,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; { @@ -384,11 +386,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); @@ -402,6 +407,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()) { @@ -410,7 +445,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; @@ -427,6 +462,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; } @@ -2490,7 +2564,8 @@ bool RestCatalog::getTableMetadataImpl( { const bool allow_geo_parser = getContext()->getSettingsRef()[DB::Setting::allow_experimental_geo_types_in_iceberg].value; - auto schema_processor = DB::Iceberg::IcebergSchemaProcessor(context_, allow_geo_parser); + auto schema_processor = DB::Iceberg::IcebergSchemaProcessor( + context_, allow_geo_parser, context_->getSettingsRef()[DB::Setting::allow_aggregate_function_states_in_open_formats].value); auto id = DB::IcebergMetadata::parseTableSchema(metadata_object, schema_processor, context_, log); auto schema = schema_processor.getClickHouseTableSchemaById(id); result.setSchema(*schema); @@ -2746,6 +2821,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 @@ -2846,6 +2927,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; }); @@ -2856,7 +2938,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/ClickHouseTypeAnnotationUtils.cpp b/src/Formats/ClickHouseTypeAnnotationUtils.cpp new file mode 100644 index 0000000000000..4eac89289e3e5 --- /dev/null +++ b/src/Formats/ClickHouseTypeAnnotationUtils.cpp @@ -0,0 +1,22 @@ +#include + +#include +#include + +namespace DB +{ + +String getAggregateFunctionTypeAnnotation(const DataTypePtr & type) +{ + return hasAggregateFunctionOrSimpleAggregateFunctionType(type) ? type->getName() : String{}; +} + +DataTypePtr getAnnotatedDataType(const String & type_name) +{ + auto type = DataTypeFactory::instance().get(type_name); + /// 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/Formats/ClickHouseTypeAnnotationUtils.h b/src/Formats/ClickHouseTypeAnnotationUtils.h new file mode 100644 index 0000000000000..f389b05daf494 --- /dev/null +++ b/src/Formats/ClickHouseTypeAnnotationUtils.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +namespace DB +{ + +/// The ClickHouse type name to record in the metadata of a Parquet file or an Iceberg table for `type`: +/// the name of `type` if it has an `AggregateFunction` or `SimpleAggregateFunction`, empty otherwise. +String getAggregateFunctionTypeAnnotation(const DataTypePtr & type); + +/// The data type named `type_name`. A state without an explicit version has version 0. +DataTypePtr getAnnotatedDataType(const String & type_name); + +} diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index c169db9af1df1..f657a7b86d0c0 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -105,6 +105,18 @@ FormatSettings getFormatSettings(const ContextPtr & context) return getFormatSettings(context, settings); } +void setTableAllowAggregateFunctionStates( + FormatSettings & table_format_settings, const SettingsChanges * table_settings, const ContextPtr & global_context) +{ + bool table_allow = global_context->getSettingsRef()[Setting::allow_aggregate_function_states_in_open_formats]; + 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; +} + FormatSettings getFormatSettings(const ContextPtr & context, const Settings & settings) { FormatSettings format_settings; @@ -265,6 +277,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..c4d503fc48728 100644 --- a/src/Formats/FormatFactory.h +++ b/src/Formats/FormatFactory.h @@ -63,6 +63,10 @@ using BucketSplitter = std::shared_ptr; FormatSettings getFormatSettings(const ContextPtr & context); FormatSettings getFormatSettings(const ContextPtr & context, const Settings & settings); +/// Stores a table's `allow_aggregate_function_states_in_open_formats` in `table_format_settings`: the value its `SETTINGS` +/// (`table_settings`) give, or the server's (`global_context`) without one. A query does not change it. +void setTableAllowAggregateFunctionStates( + FormatSettings & table_format_settings, const SettingsChanges * table_settings, const ContextPtr & global_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..4057bb458f872 --- /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 = getAggregateFunctionTypeAnnotation(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..5a7671d68f48d 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,124 @@ 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; +} + +/// The parquet writer stores some ClickHouse types as parquet types that the reader maps to a different +/// ClickHouse type, e.g. `Date` is read back as `Date32`. Lists those pairs, so the type from +/// `clickhouse.column_types` metadata can be checked against the parquet schema of a file we wrote. +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..467d8d6ae0599 100644 --- a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp +++ b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp @@ -17,9 +17,13 @@ #include #include #include +#include #include #include #include +#include +#include +#include #include #include @@ -58,6 +62,20 @@ SchemaConverter::SchemaConverter( } } } + + /// An explicit structure takes precedence over type annotations in the footer. Without + /// allow_aggregate_function_states_in_open_formats they are not looked at, and every column has its parquet type. + if (!sample_block && options.format.parquet.allow_aggregate_function_states) + { + 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 +146,32 @@ 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 = getAnnotatedDataType(type_name); + } + 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()); + } + + 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 +186,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 +509,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 +1273,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..b0b02fec0a00e 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; +``` + +The recorded types are applied only with [`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, schema inference ignores the `clickhouse.column_types` key, so a state column reads as `String` and a `SimpleAggregateFunction(f, T)` column as `T`, and writing a state throws `SUPPORT_IS_DISABLED`. `SimpleAggregateFunction` types are recorded on write either way. Files without the key read as before. A table, such as one with the `File`, `URL` or `S3` engine, takes the value from its `SETTINGS` clause, or the server's value (from the server settings profile) without one; the query's value applies only to table functions. + +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 c0f7303b37366..4c2cbd73c2714 100644 --- a/src/Storages/ExportReplicatedMergeTreePartitionManifest.h +++ b/src/Storages/ExportReplicatedMergeTreePartitionManifest.h @@ -173,6 +173,7 @@ struct ExportReplicatedMergeTreePartitionManifest MergeTreePartExportManifest::FileAlreadyExistsPolicy file_already_exists_policy; String filename_pattern; bool write_full_path_in_iceberg_metadata = 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("retry_max_backoff_seconds", retry_max_backoff_seconds); json.set("task_timeout_seconds", task_timeout_seconds); json.set("write_full_path_in_iceberg_metadata", write_full_path_in_iceberg_metadata); + 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) @@ -303,6 +306,11 @@ struct ExportReplicatedMergeTreePartitionManifest manifest.write_full_path_in_iceberg_metadata = json->getValue("write_full_path_in_iceberg_metadata"); + 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 c453a5df8fd85..04ec5189f1f5d 100644 --- a/src/Storages/MergeTree/ExportPartitionUtils.cpp +++ b/src/Storages/MergeTree/ExportPartitionUtils.cpp @@ -306,6 +306,10 @@ namespace ExportPartitionUtils /// stalls when the setting is only set at the query level. context_copy->setSetting("allow_insert_into_iceberg", true); + 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/MergeTreePartitionExportScheduler.cpp b/src/Storages/MergeTree/MergeTreePartitionExportScheduler.cpp index 275ef1fc05f5b..8470227e4f6d9 100644 --- a/src/Storages/MergeTree/MergeTreePartitionExportScheduler.cpp +++ b/src/Storages/MergeTree/MergeTreePartitionExportScheduler.cpp @@ -616,13 +616,14 @@ void MergeTreePartitionExportScheduler::tryCommit(const String & transaction_id) } else { - auto destination_storage = DatabaseCatalog::instance().tryGetTable(destination_storage_id, storage.getContext()); + /// Catalog destinations must be resolved with the settings persisted by the initiating query. + auto context = ExportPartitionUtils::getContextCopyWithTaskSettings(storage.getContext(), descriptor_copy); + + auto destination_storage = DatabaseCatalog::instance().tryGetTable(destination_storage_id, context); if (!destination_storage) throw Exception(ErrorCodes::UNKNOWN_TABLE, "Destination table {} not found for export commit", destination_storage_id.getNameForLogs()); - auto context = ExportPartitionUtils::getContextCopyWithTaskSettings(storage.getContext(), descriptor_copy); - LOG_INFO(storage.log, "ExportPartition: all parts exported for task {}, committing", transaction_id); destination_commit_info = ExportPartitionUtils::commitExportOnDestination( diff --git a/src/Storages/MergeTree/MergeTreePartitionExportTask.h b/src/Storages/MergeTree/MergeTreePartitionExportTask.h index de144014eb3da..c30479db434c5 100644 --- a/src/Storages/MergeTree/MergeTreePartitionExportTask.h +++ b/src/Storages/MergeTree/MergeTreePartitionExportTask.h @@ -81,6 +81,7 @@ struct MergeTreePartitionExportTask FileAlreadyExistsPolicy file_already_exists_policy = FileAlreadyExistsPolicy::skip; String filename_pattern; bool write_full_path_in_iceberg_metadata = 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("file_already_exists_policy", String(magic_enum::enum_name(file_already_exists_policy))); json.set("filename_pattern", filename_pattern); json.set("write_full_path_in_iceberg_metadata", write_full_path_in_iceberg_metadata); + 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) @@ -285,6 +288,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"); + 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..f51a0551421bd 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,18 @@ class DataLakeConfiguration : public BaseStorageConfiguration, public std::enabl { auto res = BaseStorageConfiguration::createArgsWithAccessData(); - auto iceberg_metadata_file_path = (*settings)[DataLakeStorageSetting::iceberg_metadata_file_path]; - - if (iceberg_metadata_file_path.changed) + /// 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); + /// Only an enabled value is passed on, so a node of an older version is not sent a setting it may not know. + /// `StorageObjectStorageCluster` disables it in the query when the table has it disabled but the query enables it. + if (const auto & allow_aggregate_function_states = (*settings)[DataLakeStorageSetting::allow_aggregate_function_states_in_open_formats]; + allow_aggregate_function_states.changed && allow_aggregate_function_states.value) + table_settings.setSetting("allow_aggregate_function_states_in_open_formats", true); + + if (!table_settings.empty()) { auto * arguments = res->template as(); if (!arguments) @@ -496,7 +506,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 +516,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 bfaccb87fc40d..c49f294e0f2c7 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.cpp @@ -391,8 +391,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); @@ -665,9 +664,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, @@ -732,6 +729,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) @@ -755,7 +753,7 @@ RewriteResult rewriteBins( path_resolver, object_storage, context, - std::nullopt, /// format_settings + format_settings, write_format, sample_block, [&](const std::string & path) @@ -1315,6 +1313,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) { @@ -1411,7 +1410,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 c256b65541aed..e30afc55dcffa 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp @@ -251,6 +251,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; @@ -546,6 +549,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. @@ -591,10 +598,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 9ff0fcf02a1ee..6f827335f4286 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" @@ -305,7 +306,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(), context_)), .metadata_cache = cache_ptr, .format_version = format_version, .table_location = table_location, @@ -341,7 +344,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) { @@ -351,11 +354,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( @@ -421,8 +424,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) @@ -453,19 +458,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 @@ -473,7 +486,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) @@ -483,7 +496,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 " @@ -510,18 +523,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) @@ -587,14 +597,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); @@ -682,6 +693,7 @@ bool IcebergMetadata::optimize( data_lake_settings, context, write_format, + format_settings, catalog, storage_id); @@ -738,7 +750,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; @@ -779,18 +791,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}; @@ -802,13 +814,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; @@ -825,7 +838,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; @@ -1107,6 +1120,23 @@ void IcebergMetadata::alterPartitionDropImpl( executor.run(); } +static void checkAggregateFunctionStatesAllowed(const String & column_name, const DataTypePtr & type, bool allow_aggregate_function_states) +{ + if (!type || !hasAggregateFunctionType(type)) + return; + if (allow_aggregate_function_states) + 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 (for a table function or a `DataLakeCatalog` " + "table, in the query)", + column_name, + type->getName()); +} + void IcebergMetadata::alter( const AlterCommands & params, ContextPtr context, @@ -1121,6 +1151,10 @@ 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, persistent_components.schema_processor->useClickHouseTypeAnnotations()); + Iceberg::alter(params, context, storage_id, object_storage, data_lake_settings, persistent_components, write_format, catalog); } @@ -1264,6 +1298,10 @@ void IcebergMetadata::createInitial( } } + for (const auto & column : columns->getAll()) + checkAggregateFunctionStatesAllowed( + column.name, column.type, getTableAllowAggregateFunctionStates(configuration_ptr->getDataLakeSettings(), local_context)); + String location_path = configuration_ptr->getRawPath().path; if (!location_path.contains("://") && !location_path.starts_with('/')) location_path = "/" + location_path; @@ -1384,7 +1422,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); } @@ -2890,8 +2928,14 @@ IcebergMetadata::getExportDestinationInfo(const std::string & iceberg_metadata_j /// A scratch processor: the live one of the table is not touched. It derives the columns the way a reader does, for /// example `int` is `Int32` and `long` is `Int64`. The table already exists with these types, so geometry and /// geography are accepted without `allow_experimental_geo_types_in_iceberg`, which a replica may not have set. - IcebergSchemaProcessor schema_processor(context, /* allow_geo_parser_ */ true); - schema_processor.addIcebergTableSchema(lookupSchema(metadata_json, info->schema_id), context); + IcebergSchemaProcessor schema_processor( + context, + /* allow_geo_parser_ */ true, + persistent_components.schema_processor->useClickHouseTypeAnnotations()); + schema_processor.addIcebergTableSchema( + lookupSchema(metadata_json, info->schema_id), + context, + getClickHouseTypeAnnotations(metadata_json, static_cast(info->schema_id))); info->columns = *schema_processor.getClickHouseTableSchemaById(static_cast(info->schema_id)); std::lock_guard lock(export_destination_cache_mutex); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.h index c3b2ecc118431..3d3f36d57407d 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; } @@ -259,10 +266,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 { @@ -282,12 +293,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..f8b67e722aafc 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include #include #include #include @@ -11,7 +14,6 @@ #include #include -#include #include #include @@ -150,99 +152,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 +178,68 @@ Int32 getNextSchemaId(Poco::JSON::Object::Ptr metadata_object) return max_id + 1; } +void collectFieldsById(const Poco::JSON::Array::Ptr & fields, std::unordered_map & result); + +/// Collects the struct fields nested in Iceberg type `type` by their ids. +void collectNestedFieldsById(const Poco::Dynamic::Var & type, std::unordered_map & result) +{ + if (type.isString()) + return; + const auto type_object = type.extract(); + const auto kind = type_object->getValue(Iceberg::f_type); + if (kind == Iceberg::f_list) + collectNestedFieldsById(type_object->get(Iceberg::f_element), result); + else if (kind == Iceberg::f_map) + { + collectNestedFieldsById(type_object->get(Iceberg::f_key), result); + collectNestedFieldsById(type_object->get(Iceberg::f_value), result); + } + else if (kind == Iceberg::f_struct) + collectFieldsById(type_object->getArray(Iceberg::f_fields), result); +} + +/// Collects `fields` and the struct fields nested in their types by their ids. +void collectFieldsById(const Poco::JSON::Array::Ptr & fields, std::unordered_map & result) +{ + for (UInt32 i = 0; i < fields->size(); ++i) + { + const auto field = fields->getObject(i); + result.emplace(field->getValue(Iceberg::f_id), field); + collectNestedFieldsById(field->get(Iceberg::f_type), result); + } +} + +/// 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. With `allow_aggregate_function_states`, +/// an annotation that no longer fits the Iceberg type of its field is dropped. Without it, the annotations are not applied, +/// so they are kept as they are without being parsed. +void addCurrentSchema( + Poco::JSON::Object::Ptr metadata_object, Poco::JSON::Object::Ptr schema, Int32 schema_id, bool allow_aggregate_function_states) +{ + const auto previous_annotations + = Iceberg::getClickHouseTypeAnnotations(metadata_object, metadata_object->getValue(Iceberg::f_current_schema_id)); + std::unordered_map fields_by_id; + collectFieldsById(schema->getArray(Iceberg::f_fields), fields_by_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))) + { + String annotation; + if (const auto it = previous_annotations.find(static_cast(field_id)); it != previous_annotations.end()) + { + const auto field = fields_by_id.find(static_cast(field_id)); + if (!allow_aggregate_function_states || field == fields_by_id.end() + || Iceberg::clickHouseTypeAnnotationFitsField( + getAnnotatedDataType(it->second.type_name), + field->second->get(Iceberg::f_type), + field->second->getValue(Iceberg::f_required))) + annotation = it->second.type_name; + } + Iceberg::setClickHouseTypeAnnotation(metadata_object, static_cast(field_id), schema_id, annotation); + } +} + /// 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 +316,41 @@ 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) == getAggregateFunctionTypeAnnotation(type); +} + +/// Whether a `MODIFY COLUMN` to `type` changes the annotation of `field`. Without allow_aggregate_function_states_in_open_formats +/// the recorded annotations are not applied, so a type that records none leaves the one of the field as it is. +static bool clickHouseTypeAnnotationChanges( + const Poco::JSON::Object::Ptr & metadata_object, + const Poco::JSON::Object::Ptr & field, + const DataTypePtr & type, + bool allow_aggregate_function_states) +{ + if (!allow_aggregate_function_states && getAggregateFunctionTypeAnnotation(type).empty()) + return false; + return !clickHouseTypeAnnotationMatches(metadata_object, field, 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 +370,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; @@ -404,7 +411,8 @@ bool MetadataGenerator::isRenameColumnApplied(const String & column_name, const return found_new_name; } -bool MetadataGenerator::isModifyColumnApplied(const String & column_name, DataTypePtr type, bool first, const String & after_column) const +bool MetadataGenerator::isModifyColumnApplied( + const String & column_name, DataTypePtr type, bool first, const String & after_column, bool allow_aggregate_function_states) const { auto current_schema = findCurrentSchema(); if (!current_schema) @@ -424,7 +432,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) + || clickHouseTypeAnnotationChanges(metadata_object, field, type, allow_aggregate_function_states)) return false; } @@ -773,7 +782,7 @@ MetadataGenerator::NextMetadataResult MetadataGenerator::generateReplaceSnapshot /*data_files_delta=*/added_data_files - removed_data_files); } -void MetadataGenerator::generateDropColumnMetadata(const String & column_name) +void MetadataGenerator::generateDropColumnMetadata(const String & column_name, bool allow_aggregate_function_states) { const auto next_schema_id = getNextSchemaId(metadata_object); @@ -876,12 +885,11 @@ 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, allow_aggregate_function_states); } -void MetadataGenerator::generateAddColumnMetadata(const String & column_name, DataTypePtr type, bool first, const String & after_column) +void MetadataGenerator::generateAddColumnMetadata( + const String & column_name, DataTypePtr type, bool first, const String & after_column, bool allow_aggregate_function_states) { if (!type->isNullable()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Iceberg spec doesn't allow to add non-nullable columns"); @@ -943,12 +951,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, allow_aggregate_function_states); + Iceberg::setClickHouseTypeAnnotation(metadata_object, new_field_id, next_schema_id, getAggregateFunctionTypeAnnotation(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, + bool allow_aggregate_function_states) { if (type) Iceberg::checkUnknownTypeAllowed(column_name, type, metadata_object->getValue(Iceberg::f_format_version)); @@ -961,6 +974,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 +988,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], + 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 +1008,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 (clickHouseTypeAnnotationChanges(metadata_object, current_field, type, allow_aggregate_function_states)) + annotation_changed = true; + else if (!needs_reposition) return false; } else @@ -1018,8 +1051,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), + getAggregateFunctionTypeAnnotation(type)); + return true; + } const auto next_schema_id = getNextSchemaId(metadata_object); current_schema = Iceberg::deepCopy(current_schema); @@ -1065,13 +1110,14 @@ 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, allow_aggregate_function_states); + if (type_changed || annotation_changed) + Iceberg::setClickHouseTypeAnnotation(metadata_object, target_field_id, next_schema_id, getAggregateFunctionTypeAnnotation(type)); return true; } -void MetadataGenerator::generateRenameColumnMetadata(const String & column_name, const String & new_column_name) +void MetadataGenerator::generateRenameColumnMetadata( + const String & column_name, const String & new_column_name, bool allow_aggregate_function_states) { auto current_schema = Iceberg::deepCopy(getCurrentSchema()); @@ -1098,10 +1144,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), allow_aggregate_function_states); } } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h index aeec2e00c8f33..ed89bddf2402f 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.h @@ -48,7 +48,13 @@ class MetadataGenerator SnapshotOperation operation = SnapshotOperation::Append, bool is_truncate = false); - void generateAddColumnMetadata(const String & column_name, DataTypePtr type, bool first = false, const String & after_column = {}); + /// `allow_aggregate_function_states` is the table's `allow_aggregate_function_states_in_open_formats`. + void generateAddColumnMetadata( + const String & column_name, + DataTypePtr type, + bool first = false, + const String & after_column = {}, + bool allow_aggregate_function_states = false); /// Create a manifest-only rewrite snapshot (`replace` operation) carrying `total-*` counters forward so `OPTIMIZE ... MANIFEST` is idempotent. NextMetadataResult generateManifestOnlySnapshot( FileNamesGenerator & generator, @@ -71,13 +77,21 @@ class MetadataGenerator /// Records the metadata file that the generated one replaces. void appendMetadataLog(const Iceberg::IcebergPathFromMetadata & previous_metadata_file_path, Int64 timestamp_ms); - void generateDropColumnMetadata(const String & column_name); + void generateDropColumnMetadata(const String & column_name, bool allow_aggregate_function_states = false); /// 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 = {}); - void generateRenameColumnMetadata(const String & column_name, const String & new_column_name); + /// type (the timestamptz timezone and whether geo types are allowed). `allow_aggregate_function_states` + /// is the table's `allow_aggregate_function_states_in_open_formats`. + bool generateModifyColumnMetadata( + const String & column_name, + DataTypePtr type, + ContextPtr context, + bool first = false, + const String & after_column = {}, + bool allow_aggregate_function_states = false); + void generateRenameColumnMetadata( + const String & column_name, const String & new_column_name, bool allow_aggregate_function_states = false); /// A commit attempt can land in the catalog even when the client observes a failure /// (the Iceberg "commit state unknown" case, e.g. a proxy returning 5xx after the catalog @@ -88,7 +102,13 @@ class MetadataGenerator bool isDropColumnApplied(const String & column_name) const; bool isRenameColumnApplied(const String & column_name, const String & new_column_name) const; /// `type` may be null for a position-only `MODIFY COLUMN`; `first` and `after_column` are checked against the field order. - bool isModifyColumnApplied(const String & column_name, DataTypePtr type, bool first = false, const String & after_column = {}) const; + /// `allow_aggregate_function_states` is the table's `allow_aggregate_function_states_in_open_formats`. + bool isModifyColumnApplied( + const String & column_name, + DataTypePtr type, + bool first = false, + const String & after_column = {}, + bool allow_aggregate_function_states = false) const; private: Poco::JSON::Object::Ptr metadata_object; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp index 47ddf975bdc11..cd0c514c962c3 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp @@ -110,7 +110,7 @@ static Int32 getHighestFieldIdFromType(const Poco::Dynamic::Var & type_var) /// unknown: the catalog may have applied the update and still reported a failure, in which case /// re-applying the same command on the refreshed metadata would fail with "Column already exists" /// or "Not found column" for an ALTER that actually succeeded. -static bool alterAlreadyApplied(const MetadataGenerator & generator, const AlterCommand & command) +static bool alterAlreadyApplied(const MetadataGenerator & generator, const AlterCommand & command, bool allow_aggregate_function_states) { switch (command.type) { @@ -121,7 +121,8 @@ static bool alterAlreadyApplied(const MetadataGenerator & generator, const Alter case AlterCommand::Type::RENAME_COLUMN: return generator.isRenameColumnApplied(command.column_name, command.rename_to); case AlterCommand::Type::MODIFY_COLUMN: - return generator.isModifyColumnApplied(command.column_name, command.data_type, command.first, command.after_column); + return generator.isModifyColumnApplied( + command.column_name, command.data_type, command.first, command.after_column, allow_aggregate_function_states); default: return false; } @@ -835,6 +836,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,10 +947,14 @@ 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); - if (commit_attempted && alterAlreadyApplied(metadata_json_generator, params[0])) + if (commit_attempted && alterAlreadyApplied( + metadata_json_generator, params[0], persistent_table_components.schema_processor->useClickHouseTypeAnnotations())) { LOG_WARNING( log, @@ -960,23 +968,36 @@ void alter( switch (params[0].type) { case AlterCommand::Type::ADD_COLUMN: - metadata_json_generator.generateAddColumnMetadata(params[0].column_name, params[0].data_type, params[0].first, params[0].after_column); + metadata_json_generator.generateAddColumnMetadata( + params[0].column_name, + params[0].data_type, + params[0].first, + params[0].after_column, + persistent_table_components.schema_processor->useClickHouseTypeAnnotations()); break; case AlterCommand::Type::DROP_COLUMN: if (params[0].clear) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Clear column is not supported for iceberg. Please use UPDATE instead"); - metadata_json_generator.generateDropColumnMetadata(params[0].column_name); + metadata_json_generator.generateDropColumnMetadata( + params[0].column_name, persistent_table_components.schema_processor->useClickHouseTypeAnnotations()); 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, + persistent_table_components.schema_processor->useClickHouseTypeAnnotations())) { succeeded = true; } break; } case AlterCommand::Type::RENAME_COLUMN: - metadata_json_generator.generateRenameColumnMetadata(params[0].column_name, params[0].rename_to); + metadata_json_generator.generateRenameColumnMetadata( + params[0].column_name, params[0].rename_to, persistent_table_components.schema_processor->useClickHouseTypeAnnotations()); break; default: throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown type of alter {}", params[0].type); @@ -1034,7 +1055,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..07a3a1a43fcd8 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,7 @@ #include #include +#include namespace DB { @@ -455,13 +457,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 +477,9 @@ void IcebergSchemaProcessor::addIcebergTableSchema( if (!schema_ptr->isArray(f_fields) || schema_ptr->getArray(f_fields)->size() == 0) return; + auto schema_annotations + = getAppliedClickHouseTypeAnnotations(getClickHouseTypeAnnotationsOfSchema(schema_ptr, clickhouse_type_annotations)); + std::unordered_map type_mapping; if (allow_geo_parser) { @@ -486,7 +496,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 +506,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 +584,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 +601,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 +746,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 +756,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 +788,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 +811,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 = getAnnotatedDataType(annotated_name); + + if (!clickHouseTypeAnnotationFitsField(annotated_type, field->get(type_key), required)) { - 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_, + getAppliedClickHouseTypeAnnotations(clickhouse_type_annotations), + field->getValue(f_required)); } /** @@ -828,6 +904,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 +920,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 +929,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 +948,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 +989,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 +1038,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 +1122,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 +1191,34 @@ 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; +} + +ClickHouseTypeAnnotations +IcebergSchemaProcessor::getAppliedClickHouseTypeAnnotations(const ClickHouseTypeAnnotations & clickhouse_type_annotations) const +{ + if (use_clickhouse_type_annotations) + return clickhouse_type_annotations; + return {}; +} + +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..48cebd3c7bfb4 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,20 @@ 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, bool use_clickhouse_type_annotations_ = false) + : WithContext(context_) + , allow_geo_parser(allow_geo_parser_) + , use_clickhouse_type_annotations(use_clickhouse_type_annotations_) + { + } + + bool useClickHouseTypeAnnotations() const { return use_clickhouse_type_annotations; } + /// `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 +139,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 +177,44 @@ 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); + /// All of `clickhouse_type_annotations` with allow_aggregate_function_states_in_open_formats, and none without it, so + /// that every field has its Iceberg type. + ClickHouseTypeAnnotations getAppliedClickHouseTypeAnnotations(const ClickHouseTypeAnnotations & clickhouse_type_annotations) const; + 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 +225,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; + /// allow_aggregate_function_states_in_open_formats of the table: whether the ClickHouse types recorded in table properties apply. + const bool use_clickhouse_type_annotations; }; using IcebergSchemaProcessorPtr = std::shared_ptr; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp index 9e49fc6eda602..ac2ce8cc0e89d 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -54,10 +56,276 @@ #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::Int32: + return {"int", true}; + case TypeIndex::UInt32: + case TypeIndex::Int64: + return {"long", true}; + case TypeIndex::UInt64: + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Type {} cannot be stored in Iceberg: the widest Iceberg integer type is the signed 64-bit `long`, " + "which cannot represent every UInt64 value. Use Int64 or Decimal(20, 0) instead", + type->getName()); + 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; +} + +/// The format version affects only whether `timestamp_ns` may be written, so the latest one is used and the field's own type decides. +bool clickHouseTypeAnnotationFitsField(const DataTypePtr & annotated_type, const Poco::Dynamic::Var & iceberg_type, bool required) +{ + Int32 unused_field_id = 0; + const auto [annotated_iceberg_type, annotated_required] = getIcebergType(annotated_type, unused_field_id, /*format_version=*/ 3); + return annotated_required == required && icebergTypesEqualIgnoringIds(iceberg_type, annotated_iceberg_type); +} + +} + #if USE_AVRO #include -#include #include #include #include @@ -84,7 +352,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,11 +364,13 @@ 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 { extern const SettingsString iceberg_metadata_compression_method; +extern const SettingsBool allow_aggregate_function_states_in_open_formats; extern const SettingsBool datalake_ignore_unsupported_table_properties; } @@ -721,153 +990,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::Int32: - return {"int", true}; - case TypeIndex::UInt32: - case TypeIndex::Int64: - return {"long", true}; - case TypeIndex::UInt64: - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Type {} cannot be stored in Iceberg: the widest Iceberg integer type is the signed 64-bit `long`, " - "which cannot represent every UInt64 value. Use Int64 or Decimal(20, 0) instead", - type->getName()); - 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) @@ -1358,6 +1554,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 = getAggregateFunctionTypeAnnotation(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); } @@ -1620,6 +1818,14 @@ std::optional getMaxMetadataFileVersionInDirectory(const ObjectStoragePtr return max_version; } +bool getTableAllowAggregateFunctionStates(const DataLakeStorageSettings & data_lake_settings, const ContextPtr & context) +{ + const auto & setting = data_lake_settings[DataLakeStorageSetting::allow_aggregate_function_states_in_open_formats]; + if (setting.changed) + return setting.value; + return context->getSettingsRef()[Setting::allow_aggregate_function_states_in_open_formats].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 cb6a425029621..cea6112141581 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.h @@ -16,6 +16,24 @@ #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); + +/// Whether a ClickHouse type annotation of type `annotated_type` is valid for a field of Iceberg type `iceberg_type`: +/// ClickHouse writes that Iceberg type for it. +bool clickHouseTypeAnnotationFitsField(const DataTypePtr & annotated_type, const Poco::Dynamic::Var & iceberg_type, bool required); + +} #if USE_AVRO @@ -126,15 +144,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 +184,10 @@ std::pair createEmptyMetadataFile( UInt64 format_version = 2, bool is_catalog_table = false); +/// The table's `allow_aggregate_function_states_in_open_formats`. A table function or a `DataLakeCatalog` table has none +/// and takes the query's (`context`). +bool getTableAllowAggregateFunctionStates(const DataLakeStorageSettings & data_lake_settings, const ContextPtr & context); + 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 60ef59832ec9e..99da4db8f06a9 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 = {}, + bool allow_aggregate_function_states = false) { 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, allow_aggregate_function_states); FAIL() << "MODIFY COLUMN " << column << " " << requested_type->getName() << " cannot be recorded in Iceberg and must be rejected"; } @@ -1233,4 +1262,65 @@ 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, bool allow_aggregate_function_states = true) + { + return MetadataGenerator(metadata).generateModifyColumnMetadata( + "s", DataTypeFactory::instance().get(type), getContext().context, + /* first */ false, /* after_column */ {}, allow_aggregate_function_states); + }; + + 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)"); + /// Without the setting the column reads as `Int64`, so modifying it to `Int64` changes nothing. + EXPECT_FALSE(modify("Int64", /* allow_aggregate_function_states */ false)); + EXPECT_TRUE(MetadataGenerator(metadata).isModifyColumnApplied( + "s", DataTypeFactory::instance().get("Int64"), /* first */ false, /* after_column */ {}, + /* allow_aggregate_function_states */ false)); + 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 */ {}, /* allow_aggregate_function_states */ true)); + expectModifyRejected( + metadata, "u", DataTypeFactory::instance().get("AggregateFunction(sum, UInt64)"), + /* first */ false, /* after_column */ {}, /* 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..886166b3d5093 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 @@ -22,6 +30,21 @@ Poco::JSON::Object::Ptr parseSchema(const std::string & json) Poco::JSON::Parser parser; return parser.parse(json).extract(); } + +void expectAnnotatedSchemaRejected(const Poco::JSON::Object::Ptr & schema, const ClickHouseTypeAnnotations & annotations) +{ + auto context = getContext().context; + IcebergSchemaProcessor processor(context, /*allow_geo_parser_=*/ false, /*use_clickhouse_type_annotations_=*/ true); + 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 +164,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 +188,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 +218,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 +228,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 +242,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 +258,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 +272,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 +286,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 +300,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 +319,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 +335,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 +356,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 +377,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 +391,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 +403,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 +416,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 +429,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 +442,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 +459,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 +470,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 +488,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 +511,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 +527,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 +538,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 +554,168 @@ 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 = getContext().context; + IcebergSchemaProcessor processor(context, /*allow_geo_parser_=*/ false, /*use_clickhouse_type_annotations_=*/ true); + + 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 = getContext().context; + IcebergSchemaProcessor processor(context, /*allow_geo_parser_=*/ false, /*use_clickhouse_type_annotations_=*/ true); + + 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 `UInt32` as `long`. + auto context = getContext().context; + IcebergSchemaProcessor processor(context, /*allow_geo_parser_=*/ false, /*use_clickhouse_type_annotations_=*/ true); + processor.addIcebergTableSchema(schema, context, {{1, {"SimpleAggregateFunction(max, UInt32)"}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "SimpleAggregateFunction(max, UInt32)"); + + /// 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 = getContext().context; + IcebergSchemaProcessor processor(context, /*allow_geo_parser_=*/ false, /*use_clickhouse_type_annotations_=*/ true); + + /// `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)"); +} + +/// Without allow_aggregate_function_states_in_open_formats the annotations are not applied, so a field has its Iceberg type, +/// and a field with aggregate function states reads as `String`. +TEST(IcebergSchemaProcessor, AnnotationsAreNotAppliedWithoutTheSetting) +{ + tryRegisterAggregateFunctions(); + auto context = getContext().context; + 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, UInt64)"}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "Int64"); + EXPECT_FALSE(processor.hasClickHouseTypeAnnotation(0, 1)); + + processor.addIcebergTableSchema( + parseSchema(R"json({"schema-id":1,"fields":[{"id":2,"name":"u","required":true,"type":"binary"}]})json"), + context, + {{2, {"AggregateFunction(uniq, UInt64)"}}}); + EXPECT_EQ(processor.getClickHouseTableSchemaById(1)->front().type->getName(), "String"); + EXPECT_FALSE(processor.hasClickHouseTypeAnnotation(1, 2)); +} + +#if USE_AVRO +TEST(IcebergSchemaProcessor, SkippingTheSchemaDoesNotPublishIt) +{ + 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 = getContext().context; + 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()); + + DB::IcebergMetadata::parseTableSchema(metadata, processor, context, log, DB::IcebergMetadata::SchemaParsing::Parse); + EXPECT_EQ(processor.getClickHouseTableSchemaById(0)->front().type->getName(), "String"); +} + +/// 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..7219cdd903e3a 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,11 +5,16 @@ #include #include +#include +#include +#include +#include #include #include #include #include #include +#include #include using namespace DB; @@ -176,4 +181,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(getAnnotatedDataType(v0->getName())), 0u); + + auto array_v0 = DataTypeFactory::instance().get("Array(AggregateFunction(0, sumMap, Array(UInt8), Array(UInt8)))"); + EXPECT_EQ( + version_of(assert_cast(*getAnnotatedDataType(array_v0->getName())).getNestedType()), + 0u); + + auto latest = DataTypeFactory::instance().get("AggregateFunction(sumMap, Array(UInt8), Array(UInt8))"); + EXPECT_EQ(version_of(getAnnotatedDataType(latest->getName())), version_of(latest)); +} + #endif diff --git a/src/Storages/ObjectStorage/StorageObjectStorage.cpp b/src/Storages/ObjectStorage/StorageObjectStorage.cpp index 40880c2e8329b..2e10ebc8961d4 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorage.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorage.cpp @@ -911,6 +911,11 @@ 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_ : format_settings; + if (format_settings_ && format_settings) + import_format_settings->parquet.allow_aggregate_function_states = format_settings->parquet.allow_aggregate_function_states; + if (isDataLake()) { configuration->lazyInitializeIfNeeded(object_storage, local_context); @@ -920,7 +925,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)); } @@ -983,7 +988,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)); } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp b/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp index bcbe0f22c32fe..27f1e776e650a 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -53,6 +54,12 @@ namespace Setting extern const SettingsInt64 delta_lake_snapshot_start_version; extern const SettingsInt64 delta_lake_snapshot_end_version; extern const SettingsUInt64 lock_object_storage_task_distribution_ms; + extern const SettingsBool allow_aggregate_function_states_in_open_formats; +} + +namespace DataLakeStorageSetting +{ + extern const DataLakeStorageSettingsBool allow_aggregate_function_states_in_open_formats; } namespace ErrorCodes @@ -192,7 +199,7 @@ 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, format_settings_, sample_path, context_); else validateSupportedColumns(columns, *configuration); @@ -433,6 +440,26 @@ bool StorageObjectStorageCluster::updateQueryForDistributedEngineIfNeeded(ASTPtr function_ast->name = table_function_name; function_ast->arguments = configuration->createArgsWithAccessData(); + + /// The table function on the other nodes is passed the table's `allow_aggregate_function_states_in_open_formats` only + /// when it is enabled, and takes the query's value otherwise, so the query has to carry a disabled one. + if (configuration->isDataLakeConfiguration() && context->getSettingsRef()[Setting::allow_aggregate_function_states_in_open_formats]) + { + const auto & table_allow + = configuration->getDataLakeSettings()[DataLakeStorageSetting::allow_aggregate_function_states_in_open_formats]; + if (table_allow.changed && !table_allow.value) + { + if (auto settings = select_query->settings()) + settings->as().changes.setSetting("allow_aggregate_function_states_in_open_formats", false); + else + { + auto settings_ast = make_intrusive(); + settings_ast->is_standalone = false; + settings_ast->changes.setSetting("allow_aggregate_function_states_in_open_formats", false); + select_query->setExpression(ASTSelectQuery::Expression::SETTINGS, std::move(settings_ast)); + } + } + } function_ast->children.push_back(function_ast->arguments); function_ast->setAlias(table_alias); diff --git a/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp b/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp index 1c7921b2065f7..384fd8b6b8d63 100644 --- a/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp +++ b/src/Storages/ObjectStorage/registerStorageObjectStorage.cpp @@ -34,11 +34,13 @@ namespace Setting { extern const SettingsBool write_full_path_in_iceberg_metadata; extern const SettingsBool allow_experimental_paimon_storage_engine; + extern const SettingsBool allow_aggregate_function_states_in_open_formats; } namespace DataLakeStorageSetting { extern const DataLakeStorageSettingsString disk; + extern const DataLakeStorageSettingsBool allow_aggregate_function_states_in_open_formats; } namespace @@ -80,6 +82,9 @@ createStorageObjectStorage(const StorageFactory::Arguments & args, StorageObject format_settings = getFormatSettings(context); } + setTableAllowAggregateFunctionStates( + *format_settings, args.storage_def->settings ? &args.storage_def->settings->changes : nullptr, args.getContext()); + ASTPtr partition_by; if (args.storage_def->partition_by) partition_by = args.storage_def->partition_by->clone(); @@ -1095,6 +1100,11 @@ void registerStorageObjectStorage(StorageFactory & factory) auto storage_settings = std::make_shared(); if (storage_def.settings) storage_settings->loadFromQuery(*storage_def.settings); + /// A table has the value from its own `SETTINGS`, or the server's without one, and never the query's. + auto & allow_aggregate_function_states = (*storage_settings)[DataLakeStorageSetting::allow_aggregate_function_states_in_open_formats]; + if (!allow_aggregate_function_states.changed) + allow_aggregate_function_states + = Context::getGlobalContextInstance()->getSettingsRef()[Setting::allow_aggregate_function_states_in_open_formats].value; return storage_settings; } @@ -1257,6 +1267,56 @@ 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; +``` + +The recorded types are applied only with +[`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, the `clickhouse.type` properties are not applied, so a +`SimpleAggregateFunction(f, T)` column reads as `T` and a state column as `String`, the serialized state. Creating or +adding an `AggregateFunction` column throws `SUPPORT_IS_DISABLED`. `SimpleAggregateFunction` types are recorded either +way, and `MODIFY COLUMN` to a type without one keeps the recorded type of the column. + +A table takes the value from its `SETTINGS` clause, or the server's value (from the server settings profile) without +one; the query's value does not change it. The query's value applies to table functions such as `icebergS3` and to +tables of a `DataLakeCatalog` database. On a cluster (`object_storage_cluster`), a table that enables the setting sends +it 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. The destination table uses its own value. For a table function or a +`DataLakeCatalog` table the query's value applies, and `EXPORT PARTITION` records it 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/StorageMergeTree.cpp b/src/Storages/StorageMergeTree.cpp index 293bb2f8cb466..cac1af15a1449 100644 --- a/src/Storages/StorageMergeTree.cpp +++ b/src/Storages/StorageMergeTree.cpp @@ -147,6 +147,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; extern const SettingsUInt64 export_merge_tree_part_check_destination_schema_staleness_ms; } @@ -4153,6 +4154,8 @@ void StorageMergeTree::exportPartitionToTable(const PartitionCommand & command, descriptor.file_already_exists_policy = query_context->getSettingsRef()[Setting::export_merge_tree_part_file_already_exists_policy].value; 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_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 f0da57190f464..6ded219b72ddf 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; } @@ -8881,6 +8882,8 @@ void StorageReplicatedMergeTree::exportPartitionToTable(const PartitionCommand & manifest.file_already_exists_policy = query_context->getSettingsRef()[Setting::export_merge_tree_part_file_already_exists_policy].value; 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_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/tests/integration/helpers/export_partition_helpers.py b/tests/integration/helpers/export_partition_helpers.py index d0cb8eb3d379b..95fba30af2f30 100644 --- a/tests/integration/helpers/export_partition_helpers.py +++ b/tests/integration/helpers/export_partition_helpers.py @@ -335,10 +335,12 @@ def make_iceberg_s3( url=None, s3_retry_attempts=3, if_not_exists=False, + settings=None, + table_settings="", ): """Create an IcebergS3 table at a MinIO prefix. - *url* defaults to ``http://minio1:9001/root/data/{name}/``. + *url* defaults to ``http://minio1:9001/root/data/{name}/``. *table_settings* are added to its ``SETTINGS`` clause. """ if url is None: url = f"http://minio1:9001/root/data/{name}/" @@ -349,8 +351,9 @@ def make_iceberg_s3( CREATE TABLE {ine}{name} ({columns}) ENGINE = IcebergS3('{url}', '{MINIO_USER}', '{MINIO_PASS}') {pclause} - SETTINGS s3_retry_attempts = {s3_retry_attempts} - """ + SETTINGS s3_retry_attempts = {s3_retry_attempts}{", " + table_settings if table_settings else ""} + """, + settings=settings, ) diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index 798b7ca8e6eba..6ee0e9dcacae9 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -4971,3 +4971,67 @@ 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. A catalog table applies it with the query's setting. + states = {"allow_aggregate_function_states_in_open_formats": 1} + assert "SimpleAggregateFunction" in node.query(f"DESCRIBE {CATALOG_NAME}.`{ns}.{tbl}`", settings=states) + # 4. ALTER through the catalog records the annotation and clears it + alter_settings = {"allow_insert_into_iceberg": 1, **states} + 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 48c8da7340c80..0d8a2e2e9bf4f 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 @@ -1461,3 +1462,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(max, UInt32)" + ) + + make_mt(node, mt, columns, "k", order_by="k") + make_iceberg_s3(node, iceberg, columns, "k", table_settings="allow_aggregate_function_states_in_open_formats = 1") + + node.query( + f"INSERT INTO {mt} " + f"SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)), maxSimpleState(toUInt32(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 afd834f84fca6..b7de125b6751e 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 @@ -913,3 +913,48 @@ 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(max, UInt32)" + ) + # The destination enables the setting in its own `SETTINGS`, which decide over the profile and the query. + 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", + table_settings="allow_aggregate_function_states_in_open_formats = 1", + ) + + node.query( + f"INSERT INTO {mt_table} " + f"SELECT toInt32(number % 2), uniqState(toUInt64(number % 23)), maxSimpleState(toUInt32(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..64662f11acf86 --- /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, + additional_settings=["allow_aggregate_function_states_in_open_formats = 1"], + ) + 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, + additional_settings=["allow_aggregate_function_states_in_open_formats = 1"], + ) + 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..6cc597be58da8 --- /dev/null +++ b/tests/queries/0_stateless/04673_parquet_aggregate_function_state.reference @@ -0,0 +1,78 @@ +-- a SimpleAggregateFunction is an ordinary value of its storage type, so writing it needs no setting +-- its recorded type is applied only with the setting +s UInt64 +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..e022c3bebe0ad --- /dev/null +++ b/tests/queries/0_stateless/04673_parquet_aggregate_function_state.sh @@ -0,0 +1,179 @@ +#!/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" +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}/${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 '-- a SimpleAggregateFunction is an ordinary value of its storage type, so writing it needs no setting' +${CLICKHOUSE_CLIENT} ${NO_STATES} --query " + INSERT INTO FUNCTION file('${SIMPLE}', Parquet) SELECT sumSimpleState(number) AS s FROM numbers(10) +" +echo '-- its recorded type is applied only with the setting' +${CLICKHOUSE_CLIENT} ${NO_STATES} --query "DESC file('${SIMPLE}', Parquet)" +${CLICKHOUSE_CLIENT} ${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..8278f2f1d88dd --- /dev/null +++ b/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.reference @@ -0,0 +1,16 @@ +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 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..0b7eb2ed58328 --- /dev/null +++ b/tests/queries/0_stateless/05428_iceberg_aggregate_function_state_annotation_per_schema.sh @@ -0,0 +1,49 @@ +#!/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}') + SETTINGS allow_aggregate_function_states_in_open_formats = 1" +${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 + SETTINGS allow_aggregate_function_states_in_open_formats = 1" +} + +echo "widen" +${CLIENT} --query "ALTER TABLE ${TABLE} MODIFY COLUMN x SimpleAggregateFunction(max, Int64)" +${CLIENT} --query "INSERT INTO ${TABLE} VALUES (2, 20)" +check +echo "time travel" +${CLIENT} --query "SELECT k, x, toTypeName(x) FROM ${TABLE} ORDER BY k SETTINGS iceberg_snapshot_id = ${SNAPSHOT}" + +echo "drop the annotation" +${CLIENT} --query "ALTER TABLE ${TABLE} MODIFY COLUMN x Int64" +check 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..a9412d0bf30e1 --- /dev/null +++ b/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.reference @@ -0,0 +1,22 @@ +-- 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, queries enable it +refused +String Int64 +SimpleAggregateFunction(sum, Int64) +0 +Int64 Nullable(String) 45 +SimpleAggregateFunction(sum, Int64) SimpleAggregateFunction(anyLast, Nullable(String)) 45 +-- File, setting stored in the table, queries disable it +0 23 9900 +1 23 10000 +-- File, setting not 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..a638aac073de8 --- /dev/null +++ b/tests/queries/0_stateless/05814_aggregate_function_states_table_setting.sh @@ -0,0 +1,115 @@ +#!/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, the table has the server's value, disabled by +# default, whatever the query sets: the recorded types are not applied, so a state column is `String`. + +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_ENABLED="${ICEBERG}_enabled" +ICEBERG_DISABLED="${ICEBERG}_disabled" + +cleanup() +{ + for table in "${ICEBERG}" "${ICEBERG_NOT_STORED}" "${ICEBERG_ENABLED}" "${ICEBERG_DISABLED}" file_states file_states_not_stored; 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" +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, queries enable it" +ON="--${SETTING}=1" +expect_refusal "${CREATE_OR_ALTER_REFUSED}" run ${ON} --query "CREATE TABLE ${ICEBERG_NOT_STORED} (${COLUMNS}) ENGINE = IcebergLocal('${ICEBERG_NOT_STORED_PATH}')" +# The same data as `${ICEBERG}`, through a table without the setting: the columns have their Iceberg types. +${CLIENT} ${ON} --query "CREATE TABLE ${ICEBERG_DISABLED} ENGINE = IcebergLocal('${ICEBERG_PATH}')" +run ${ON} --query "SELECT toTypeName(u), toTypeName(s) FROM ${ICEBERG_DISABLED} LIMIT 1" +# A `MODIFY COLUMN` to the type the column has without the setting keeps its recorded type. +run ${ON} --query "ALTER TABLE ${ICEBERG_DISABLED} MODIFY COLUMN s Int64 FIRST" +run ${ON} --query "SELECT toTypeName(s) FROM icebergLocal('${ICEBERG_PATH}') LIMIT 1" +# A `SimpleAggregateFunction` holds ordinary values of its storage type, so it needs no setting. Its type is recorded, +# but only a table with the setting applies it. +${CLIENT} ${ON} --query " + CREATE TABLE ${ICEBERG_NOT_STORED} (k Int32, s SimpleAggregateFunction(sum, Int64)) ENGINE = IcebergLocal('${ICEBERG_NOT_STORED_PATH}')" +${CLIENT} --query "SHOW CREATE TABLE ${ICEBERG_NOT_STORED}" | grep -c "${SETTING}" || true +reattach "${ICEBERG_NOT_STORED}" +run ${ON} --query "INSERT INTO ${ICEBERG_NOT_STORED} SELECT toInt32(number % 2), toInt64(number) FROM numbers(10)" +run ${ON} --query "ALTER TABLE ${ICEBERG_NOT_STORED} ADD COLUMN simple SimpleAggregateFunction(anyLast, Nullable(String))" +run ${ON} --query "SELECT toTypeName(s), toTypeName(simple), sum(s) FROM ${ICEBERG_NOT_STORED} GROUP BY ALL" +${CLIENT} --query "CREATE TABLE ${ICEBERG_ENABLED} ENGINE = IcebergLocal('${ICEBERG_NOT_STORED_PATH}') SETTINGS ${SETTING} = 1" +run ${OFF} --query "SELECT toTypeName(s), toTypeName(simple), sum(s) FROM ${ICEBERG_ENABLED} GROUP BY ALL" + +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, queries enable it" +${CLIENT} --query "CREATE TABLE file_states_not_stored (${COLUMNS}) ENGINE = File(Parquet)" +expect_refusal "${PARQUET_WRITE_REFUSED}" insert_states file_states_not_stored ${ON} 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..501a40eeb7b95 --- /dev/null +++ b/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.reference @@ -0,0 +1,6 @@ +-- the query disables the setting, the table enables it +0 23 +1 23 +-- the query enables the setting, the table disables it +0 20 +1 25 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..6e903fd7f2bfd --- /dev/null +++ b/tests/queries/0_stateless/05815_iceberg_aggregate_function_states_table_setting_on_cluster.sh @@ -0,0 +1,58 @@ +#!/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. +# A table with the setting disabled has the other nodes disable it as well, though the query enables it. + +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" +SIMPLE="${TABLE}_simple" +SIMPLE_PATH="${USER_FILES_PATH}/${SIMPLE}/" + +cleanup() +{ + for table in "${TABLE}" "${PINNED}" "${SIMPLE}"; do + ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${table}" + done + rm -rf "${TABLE_PATH}" "${SIMPLE_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'" + +# `UInt32` is stored as Iceberg `long`, and the recorded `SimpleAggregateFunction(max, UInt32)` applies only with the +# setting, so every node must read `s` as `Int64`, as the table does. +${CLIENT} --query " + CREATE TABLE ${SIMPLE} (k Int32, s SimpleAggregateFunction(max, UInt32)) + ENGINE = IcebergLocal('${SIMPLE_PATH}')" +${CLIENT} --query "INSERT INTO ${SIMPLE} SELECT toInt32(number % 2), number FROM numbers(10)" + +echo "-- the query enables the setting, the table disables it" +${CLIENT} --query " + SELECT k, sum(s) FROM ${SIMPLE} GROUP BY k ORDER BY k + SETTINGS ${SETTING} = 1, 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..4c44448a6dab5 --- /dev/null +++ b/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.reference @@ -0,0 +1,6 @@ +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..424912bb5e055 --- /dev/null +++ b/tests/queries/0_stateless/05816_iceberg_modify_column_aggregate_function_state_version.sh @@ -0,0 +1,47 @@ +#!/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" + +${CLIENT} --query " + CREATE TABLE ${TABLE} (k Int32, q AggregateFunction(quantileDeterministic(0.5), Float64, UInt64)) + ENGINE = IcebergLocal('${TABLE_PATH}') + SETTINGS allow_aggregate_function_states_in_open_formats = 1" +${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 "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..09a96f96f07c1 --- /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 --allow_aggregate_function_states_in_open_formats=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')" diff --git a/tests/queries/0_stateless/05818_iceberg_aggregate_function_state_annotation_schema_rollback.reference b/tests/queries/0_stateless/05818_iceberg_aggregate_function_state_annotation_schema_rollback.reference new file mode 100644 index 0000000000000..f22a166b81268 --- /dev/null +++ b/tests/queries/0_stateless/05818_iceberg_aggregate_function_state_annotation_schema_rollback.reference @@ -0,0 +1,4 @@ +k Int32 +x Int64 +y Nullable(Int32) +w Nullable(Int32) diff --git a/tests/queries/0_stateless/05818_iceberg_aggregate_function_state_annotation_schema_rollback.sh b/tests/queries/0_stateless/05818_iceberg_aggregate_function_state_annotation_schema_rollback.sh new file mode 100755 index 0000000000000..a5dc16e15aa3e --- /dev/null +++ b/tests/queries/0_stateless/05818_iceberg_aggregate_function_state_annotation_schema_rollback.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# A schema added after `current-schema-id` was rolled back to a lower schema must not record an annotation +# that became stale after another engine evolved the field. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +TABLE="t_${CLICKHOUSE_DATABASE}_${RANDOM}_rollback" +TABLE_PATH="${USER_FILES_PATH}/${TABLE}/" +CLIENT="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1 --iceberg_metadata_staleness_ms=0" + +${CLIENT} --query " + CREATE TABLE ${TABLE} (k Int32, x SimpleAggregateFunction(max, Int32)) + ENGINE = IcebergLocal('${TABLE_PATH}') + SETTINGS allow_aggregate_function_states_in_open_formats = 1" +${CLIENT} --query "ALTER TABLE ${TABLE} ADD COLUMN y Nullable(Int32)" +${CLIENT} --query "ALTER TABLE ${TABLE} ADD COLUMN z Nullable(Int32)" + +# Another engine promoted `x` to `long` in schemas 1 and 2, cleared its annotation in schema 2 and rolled back to schema 1. +LATEST=$(ls "${TABLE_PATH}metadata/" | grep -E '^v[0-9]+\.metadata\.json$' | sort -t v -k2 -n | tail -1) +python3 - "${TABLE_PATH}metadata" "${LATEST}" <<'PY' +import json, os, re, sys +metadata_dir, latest_file = sys.argv[1], sys.argv[2] +with open(os.path.join(metadata_dir, latest_file)) as f: + metadata = json.load(f) +for schema in metadata["schemas"]: + if schema["schema-id"] > 0: + next(field for field in schema["fields"] if field["id"] == 2)["type"] = "long" +metadata["properties"]["clickhouse.type.2.2"] = "" +metadata["current-schema-id"] = 1 +version = int(re.match(r"v(\d+)\.metadata\.json", latest_file).group(1)) + 1 +with open(os.path.join(metadata_dir, f"v{version}.metadata.json"), "w") as f: + json.dump(metadata, f) +PY + +${CLIENT} --query "ALTER TABLE ${TABLE} ADD COLUMN w Nullable(Int32)" +${CLIENT} --query "DESCRIBE TABLE ${TABLE}" | cut -f1,2 + +${CLIENT} --query "DROP TABLE ${TABLE}" +rm -rf "${TABLE_PATH}"