Repository navigation
Add UUID2 data type with correct sorting - #110084
alexey-milovidov wants to merge 285 commits into
Conversation
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [c690415] Summary: ❌
AI ReviewSummaryAdds Findings❌ Blockers
Tests
Missing context / blind spots
Representation consumers traced: typed casts and common-type comparisons reconcile UUID layouts; array/map lookups preserve or normalize source types; aggregate states retain typed columns or reject ambiguous carriers; partition, bloom-filter, KV, and shard-pruning paths carry source types. Arrow native/library readers and writers preserve field metadata; Parquet values/statistics/variant encoding and Avro file paths preserve the layout; Native/RowBinary, MsgPack, CapnProto, MongoDB, and PostgreSQL use their explicit boundary conversions. BSON inference and null-function range pruning have the exceptions above. Final VerdictStatus: ❌ Block Complete the schema-signature and nested monotonicity fixes with focused regressions. The BSON compatibility and nested-NULL decisions remain visible for human disposition. |
|
@ClickHouse/integrations team, please, take a look |
The Arrow library is not compiled into the fast-test build, so `FORMAT Arrow` fails there and the query produces empty output. That made both the `UUID2` and `UUID` branches emit nothing, so the byte-identity check passed trivially while the round-trip lines were missing, and the test failed against its reference. All other Arrow tests are already tagged `no-fasttest` for the same reason. Verified locally with an Arrow-enabled build: the byte-identity check and the round-trip both produce the exact reference output. CI report: #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`convertFieldToType` treated every `Field::Types::UUID` value as already being in the destination encoding, but `UUID` and `UUID2` store the value in layouts that differ by swapping the two 64-bit halves. When a `UUID` constant is coerced into `UUID2` (or vice versa) - for example building an `IN`-set for a `UUID2` key from a `toUUID(...)` constant, which reaches `convertFieldToType` via `getSetElementsForConstantValue` with the source type passed as `from_type_hint` - the halves were not swapped, so the compared or stored value was wrong. Detect the `UUID` <-> `UUID2` crossing from `from_type_hint` and apply `UUIDHelpers::swapHalves` in that case; the same-type and no-hint cases are left unchanged. Addresses review feedback on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`uuid_type_version = 2` was ignored for `CREATE ... ON CLUSTER` when `distributed_ddl_entry_format_version < NORMALIZE_CREATE_ON_INITIATOR_VERSION`. That legacy path enqueues the query verbatim in `execute` before `createTable` normalizes it on the initiator, and each worker then treats the forwarded DDL as already-normalized internal DDL (forcing `uuid_type_version = 1`), so a bare `UUID` column was created as the historical `UUID` type instead of `UUID2`. Materialize the setting into the column-declaration ASTs on the initiator before the legacy enqueue, mirroring how `ALTER` and the modern `CREATE` path bake in the concrete stored type. Also extends `04402_uuid2_data_type` with the legacy `ON CLUSTER` case and the Field-level `UUID`/`UUID2` coercion (`IN`-set) case. Addresses review feedback on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`FunctionAnyHash` (the dispatcher behind `sipHash64`, `sipHash128`, `cityHash64`, `halfMD5`, `xxHash64`, `farmHash64`, ...) had a specialized branch only for `which.isUUID()`, hashing the value via `executeBigIntType<UUID>`. `UUID2` fell through to `executeGeneric`, which hashed `column->getDataAt(i)` - i.e. the raw in-memory bytes. Because `UUID` and `UUID2` store the same logical value in layouts that differ by swapping the two 64-bit halves, this made the hash functions return different results for `x::UUID` and `x::UUID2` even when `x` is the same textual value, breaking the hashing parity the PR promises (and that `hex`, `reinterpretAs*`, `UUIDToNum`, etc. already provide for `UUID2`). Add a `which.isUUID2()` branch that swaps the halves back into the `UUID` layout with `UUIDHelpers::swapHalves` and then hashes through the existing `executeBigIntType<UUID>` path, so `hash(x::UUID2)` equals `hash(x::UUID)`. `Nullable(UUID2)` already worked via the `Nullable` branch and now inherits the fix through the nested type. Add a hashing-parity regression to `04402_uuid2_data_type`. Addresses review feedback on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Under `uuid_type_version = 2` a nested `Map(UUID, V)` materializes to `Map(UUID2, V)`, but the `-Map` aggregate combinator (`AggregateFunctionMapCombinator::transformAggregateFunction`) dispatched only `TypeIndex::UUID`, so `sumMap` / `avgMap` / `minMap` / `uniqMap` over `Map(UUID2, ...)` threw `Map key type UUID2 is not supported by combinator Map`. `UUID2` reuses `ColumnVector<UUID>` storage, so `AggregateFunctionMap<UUID>` works verbatim; the result key type is taken from the argument, so the result stays `Map(UUID2, ...)`. Added a `TypeIndex::UUID2` branch reusing `AggregateFunctionMap<UUID>` and a `sumMap` regression over a `Map(UUID2, UInt64)` argument in `04402_uuid2_data_type`. Addresses an AI-review blocker on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The MongoDB engine handled a top-level `UUID2` column, but the BSON array reader `BSONArrayAsArray` in `BSONCXXHelper.h` dispatched only `TypeIndex::UUID`. Since `Array(UUID)` also materializes to `Array(UUID2)` under `uuid_type_version = 2`, reading a BSON UUID array into an `Array(UUID2)` column threw `Array ... has unsupported nested type UUID2`. Added a `TypeIndex::UUID2` case mirroring the `UUID` case but applying `UUIDHelpers::swapHalves` to convert the canonical big-endian bytes to the `UUID2` in-memory layout before inserting (matching the scalar `UUID2` read in `MongoDBSource`). Extended `test_storage_mongodb` with an `Array(UUID2)` column reading the same BSON binary (subtype 4) as `Array(UUID)`, plus a scalar `UUID2` read, asserting the same canonical textual values. Addresses an AI-review blocker on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…s; add end-to-end test An AI review flagged `UniqueKeyEncoding::appendColumn` as missing a `UUID2` branch, claiming a `UUID2` unique key fails at runtime. This is not the case: `UUID2` reuses `ColumnVector<UUID>` storage, and `appendColumn` dispatches on the *physical* column type (`IColumn::getDataType()`), which is `TypeIndex::UUID` for a `UUID2` column, so it already takes the `UUID` branch. Encoding the in-memory 128-bit value big-endian is order-preserving for both types (for `UUID2` it is already the canonical big-endian integer). The quoted error cannot occur — it uses `column.getName()`, which is `UUID`. The encoder is also currently reachable only from unit tests, not from a live query path. Added a clarifying comment on the `UUID` branch and an end-to-end test `04521_uuid2_unique_key` that a `UNIQUE KEY` table accepts `UUID2` key columns (explicit and materialized from a bare `UUID` under `uuid_type_version = 2`): CREATE, INSERT and canonical-order read-back. Addresses an AI-review blocker on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new `BinaryTypeIndex::UUID2` tag added a published type-encoding contract but `gtest_data_types_binary_encoding` still only round-tripped `UUID` and `Nullable(UUID)`, so `encodeDataType`/`decodeDataType` could drift for the new tag with no coverage. Add `DataTypeUUID2` and `Nullable(UUID2)` to the checked types. Addresses review feedback on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The PR updates the published `Native` specification and adds a dedicated `SerializationUUID2` binary path, but no focused stateless test asserted the on-wire bytes. Add `04540_uuid2_native_rowbinary_wire`, which checks that `RowBinary` emits the canonical big-endian 16 bytes (unlike `UUID`, which stores the two halves swapped), and that both `RowBinary` and `Native` round-trip the value and type back to the same textual `UUID2`. Addresses review feedback on #110084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🕵 Thanks @groeneai, the Pushed bb84123: merged master (resolved the conflicts with the |
…upArraySortedColumn` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…N` shared data, parsed strings with a `Dynamic` hint - `UserDefinedSQLFunctionVisitor::tryToReplaceFunction`: inside `APPLY`, the lambdas declared in the body of an expanded UDF shadow the UDFs of the same name in that body, as in the analyzer. - `SerializationDynamic::deserializeBinary(Field)` returns a `Field` without a type, with `UUID2` values in the layout of `UUID`, like `ColumnDynamic::get`. The values of the shared data of `JSON` come from it. - `convertFieldToType`: a value parsed from a string is converted with the type it was parsed as, not with the hint of the original string (a `Dynamic` hint swapped the halves of a `UUID2` once more). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Field` states, `UUID2` comparison fast path - `UserDefinedSQLFunctionVisitor` now expands SQL UDFs in the separately owned expressions of `APPLY` transformers (named `APPLY f`, lambda and aggregate parameters) found in newly expanded UDF bodies, with the same recursion detection, argument substitution (except the lambda argument) and shadowing by lambdas, so `uuid_type_version = 2` is materialized into them like into an `APPLY` of the query itself. - `assertTypeCanBeKeptInField` treats `Dynamic` and `JSON` as carriers of the historical `UUID` layout: they infer `UUID` for a value inserted from a `Field`, so `Variant(Array(Dynamic), Array(UUID2))` is rejected by `any_respect_nulls`, `groupArrayInsertAt`, `sumMap` and the like. - Same-type `UUID2` comparisons use `executeNumSameType<UUID>` like `UUID`: the integer order of `UUID2` values is their order. - `05617_uuid2_udf_nested_lambda_scope_alter_nullable` is a shell test now, with UDF names unique to the test database, so concurrent runs do not interfere. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Processors/Formats/Impl/ArrowIPC/SchemaConverter.cpp # src/Processors/Formats/Impl/Parquet/Write.cpp
…ubstitution With `uuid_type_version = 2`, `APPLY f` with a SQL UDF `f` is rewritten to `APPLY(x -> f(x))` to materialize the type into the body of `f`. The fixed binder `x` captured a free `x` in the body of `f` (as in `y -> y + x`), so a persisted query computed a different result than the direct one. The binder is now chosen so that it does not occur in the expansion of `f`, both in the query and in the bodies of UDFs. The substitution of the arguments of a UDF into its body replaced the parameters of nested lambdas too (as `x` in `x -> arrayMap(x -> x + 1, [1])`), producing `lambda(tuple(10), 10 + 1)`. Now the parameters of a nested lambda shadow the parameters of the UDF of the same name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 3376166:
The previous red was only |
… for shards When `optimize_skip_unused_shards_rewrite_in` dropped some elements of a constant `IN` tuple, the remaining elements were rebuilt from `Field`s. A `Field` does not carry the active alternative of a `Variant`, so a value stored under `UUID2` in `Variant(UUID, UUID2)` was reinserted as historical `UUID`, the shard received a different identifier and the matching row was silently lost. The new constant is now built from the retained subcolumns of the original typed `ColumnTuple`, which keeps the discriminators and the nested types of `Dynamic`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/DataTypes/IDataType.h # src/Processors/Formats/Impl/AvroRowInputFormat.cpp # src/Processors/Formats/Impl/AvroRowOutputFormat.h # src/Processors/Formats/Impl/Parquet/SchemaConverter.h # src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp
|
🕵 Pushed e91ff12: merged master. Resolved the conflicts:
The |
Resolve conflicts: keep both the `Variant` opaque-filter check from master and the `UUID`/`UUID2` layout check of the PR in `LogicalExpressionOptimizerPass`; keep the `String`/`FixedString` exemption from master inside `entry_converted_exactly` in `transform`; pass both the Iceberg `initial-default` arguments from master and the `UUID2` paths of the PR to `AvroDeserializer`; drop `docs/_migration/slug-map.csv` which was removed in master.
… merging master Mark `UUID2Converter::convertField` and `AvroSerializer::getUUID2Paths` `[[nodiscard]]` (`modernize-use-nodiscard`, now enforced for these headers by master). Master no longer allows `loop` in `CREATE TABLE ... AS table_function`, so nest the two-argument `loop(database, table)` in `remote` to keep checking that its scalar database argument is not rewritten. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110084&sha=e91ff12181866a61239f7002e42035dc2890b7f5&name_0=PR PR: #110084 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 800eabc: merged master and fixed the red from the previous run.
|
| const auto * name = equals->arguments->children[0]->as<ASTIdentifier>(); | ||
| if (name && equalsCaseInsensitiveString(name->name(), "structure")) | ||
| return {&equals->arguments->children[1]}; |
There was a problem hiding this comment.
[Blocker] Preserve ordinary comparisons in table function arguments
This recognizes structure = ... as a named schema argument before checking which table function is being called. In values, however, it can be an ordinary row expression referring to a WITH alias. Materialization then rewrites string data as a schema and changes the query result.
Reproduced with the current head's Fast test binary under the same setting:
SET uuid_type_version = 2;
WITH 'id UUID' AS structure
SELECT * FROM values('x UInt8', structure = 'id UUID'); -- 1
CREATE TABLE t ENGINE = Memory AS
WITH 'id UUID' AS structure
SELECT * FROM values('x UInt8', structure = 'id UUID');
SELECT * FROM t; -- 0A persisted view also returns 0: its stored comparison operand becomes a column declaration containing UUID2. There is no UUID declaration in this query. Please restrict named schema recognition to signatures that actually support it, preserving ordinary positional expressions, and add direct-versus-persisted coverage.
There was a problem hiding this comment.
🕵 Fixed in b5e47782e923: structure = ... is no longer recognized as a named schema argument in table functions that only have positional arguments (values, format, input, null, generateRandom). The test 05843_uuid2_values_structure_comparison compares the direct query with CREATE TABLE ... AS and a view, and checks that the real schema of values is still materialized.
There was a problem hiding this comment.
[Blocker] The signature check is still incomplete at src/Parsers/ASTDataType.cpp:250-270: only the five listed functions bypass the generic structure = ... scan. numbers also evaluates its arguments as ordinary positional expressions, so the same data rewrite remains reachable:
SET uuid_type_version = 2;
WITH 'id UUID' AS structure
SELECT count() FROM numbers(structure = 'id UUID');
CREATE TABLE t ENGINE = Memory AS
WITH 'id UUID' AS structure
SELECT * FROM numbers(structure = 'id UUID');
SELECT count() FROM t;The direct query's limit is 1; materializing the definition changes only the comparison's right operand to a declaration containing UUID2, so the persisted limit is 0. The existing 05516_table_function_key_value_argument_shadowed_by_column test establishes that numbers(x = 1) resolves x as an ordinary alias. Parameterized views with an ordinary String parameter named structure also reach this generic scan, so expanding the exemption list does not close the issue. Please recognize named schemas only for signatures that actually support them. This is verified by source tracing; no local binary is available.
# Conflicts: # src/Formats/ProtobufSerializer.cpp
The nested map key check in `SummingSortedAlgorithm` accepted only `DataTypeUUID`, so a `Nested(ID UUID2, Num UInt64)` map was treated as a non-aggregated column and a merge kept only one of the maps. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ositional-only table functions In `values`, `format`, `input`, `null` and `generateRandom` an argument of the form `structure = '...'` is an ordinary comparison, for example a row of `values` that refers to a `WITH` alias. Materializing `uuid_type_version` into a persisted query rewrote its right-hand side as a columns list and changed the result. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A `UUID2` value inside `Dynamic` or `Variant` failed with `Cannot write a value of type UUID2 into the Parquet variant column`. It is now written as the UUID primitive with the same canonical bytes as `UUID`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pushed 6db09da:
The previous red was only the review-threads gate in |
The current version on `master` is 26.12, and the `settings_changes_history` style check requires a new setting to have a record under the current version. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110084&sha=6db09da05883c410ff3398fc5bbd65866f9e8a3b&name_0=PR&name_1=Style%20check PR: #110084 Co-Authored-By: Claude Fable 5.2 <[email protected]>
`master` no longer supports `distributed_ddl_entry_format_version` below 3, so a `CREATE TABLE ... ON CLUSTER` query is always normalized on the initiator before it is enqueued. The explicit `materializeUUIDTypeVersion` call in `InterpreterCreateQuery::execute` became unreachable after the merge (it ended up inside the `is_create_database` branch), so it is removed. The tests `04402_uuid2_data_type` and `04659_uuid2_type_version_udf_expansion` set `distributed_ddl_entry_format_version = 2` and failed with `UNKNOWN_FORMAT_VERSION`. They now check the same `ON CLUSTER` materialization with the default format version. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110084&sha=6db09da05883c410ff3398fc5bbd65866f9e8a3b&name_0=PR&name_1=Fast%20test PR: #110084 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pushed c690415:
Review threads: the |
Closes: #110066
Introduces
UUID2, a variant of theUUIDdata type with correct (lexicographic) sorting.Motivation
For historical reasons, the
UUIDdata type sorts by the second half of the value. This is unexpected and, in particular, hurts the performance of primary indexes built onUUIDv7columns, whose most significant bits are a timestamp: with sorting by the second half, primary-key analysis cannot prune granules by the timestamp.What this does
UUID2stores the 128-bit value as a plain big-endian integer of the 16 canonical bytes, so that natural integer comparison of the underlying value matches the textual (lexicographic) order and the canonical byte order used by most other systems. It reuses theUUIDcolumn andFieldrepresentation (likeDateTimereusesUInt32), so sorting is correct with no extra comparison code, and its binary/interchange serialization is the canonical big-endian byte order.UUID1is an alias of the currentUUIDtype.uuid_type_version(default1) controls whether the bare nameUUIDresolves toUUID(1) orUUID2(2) atCREATE/ALTERtime. The resolved concrete type is materialized into the stored table definition (including nested types such asArray(UUID)), so reads never depend on the session setting and existing tables are never rewritten. The default will be flipped to2in a later, separate change.String,UInt128,FixedString(16)andUUID, plustoUUID2/toUUID2OrZero/toUUID2OrNull.hex/bin,reinterpretAs*,UUIDv7ToDateTime,UUIDToNum,empty/notEmpty,min/max, hashing,uniq), formats (RowBinary,Native,JSON,CSV,TSV,Arrow,Parquet,Avro,BSON,MsgPack,Protobuf,CapnProto,JSONExtract) and storage (generateRandom,bloom_filterskip index).The
UUIDtype is unchanged (verified: still sorts by second half, identical conversions, defaultuuid_type_version = 1).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new data type
UUID2, a variant ofUUIDthat sorts by its textual (lexicographic) representation instead of by the second half of the value. The settinguuid_type_version(default1) selects whether the type nameUUIDresolves toUUIDorUUID2.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/110084]