Skip to content

Add UUID2 data type with correct sorting - #110084

Open
alexey-milovidov wants to merge 285 commits into
masterfrom
uuid2-proper-sorting
Open

alexey-milovidov wants to merge 285 commits into
masterfrom
uuid2-proper-sorting

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 11, 2026 •

Copy link
Copy Markdown
Member

Closes: #110066

Introduces UUID2, a variant of the UUID data type with correct (lexicographic) sorting.

Motivation

For historical reasons, the UUID data type sorts by the second half of the value. This is unexpected and, in particular, hurts the performance of primary indexes built on UUIDv7 columns, 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

UUID2 stores 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 the UUID column and Field representation (like DateTime reuses UInt32), so sorting is correct with no extra comparison code, and its binary/interchange serialization is the canonical big-endian byte order.

  • UUID1 is an alias of the current UUID type.
  • A new setting uuid_type_version (default 1) controls whether the bare name UUID resolves to UUID (1) or UUID2 (2) at CREATE/ALTER time. The resolved concrete type is materialized into the stored table definition (including nested types such as Array(UUID)), so reads never depend on the session setting and existing tables are never rewritten. The default will be flipped to 2 in a later, separate change.
  • Conversions to/from String, UInt128, FixedString(16) and UUID, plus toUUID2 / toUUID2OrZero / toUUID2OrNull.
  • Parity across functions (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_filter skip index).

The UUID type is unchanged (verified: still sorts by second half, identical conversions, default uuid_type_version = 1).

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added a new data type UUID2, a variant of UUID that sorts by its textual (lexicographic) representation instead of by the second half of the value. The setting uuid_type_version (default 1) selects whether the type name UUID resolves to UUID or UUID2.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/110084]

@mintlify

mintlify Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 24, 2026, 8:10 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c690415]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds UUID2 with lexicographic ordering, conversions, format support, and creation-time resolution through uuid_type_version. Block: two earlier fixes remain incomplete and can change query results. Replied once and reopened those existing threads; no new review threads were created. Two deliberately dismissed findings remain below for a human decision.

Findings

❌ Blockers

  • src/Parsers/ASTDataType.cpp:250-270: Schema normalization still changes ordinary data arguments. The positional-only exemption fixes values, but the generic structure = ... scan also reaches numbers and arbitrary parameterized views. With uuid_type_version = 2, persisting WITH 'id UUID' AS structure SELECT count() FROM numbers(structure = 'id UUID') rewrites the comparison operand into a declaration containing UUID2, changing the limit from 1 to 0. Restrict schema recognition to signatures that support it. Existing thread reopened after the fixed claim.

  • src/Functions/ifNull.cpp:109-113, src/Functions/coalesce.cpp:121-125: The monotonicity fix misses nested UUID types. Nullable(Tuple(UUID1)) with a Tuple(UUID2) fallback passes the scalar-only guard, although execution changes the element's order. With allow_key_condition_coalesce_rewrite = 0, primary-key analysis trusts this declaration and can prune matching rows. Concrete trace: a historical-order granule containing canonical values 2^64 + 1 and 2, bounded by the next mark 2^64 + 3, becomes the asserted interval [2^64 + 1, 2^64 + 3], losing its interior match for <= 2. Account for nested leaves or the actual input/result conversion. Existing thread reopened after the fixed claim.

  • src/Processors/Formats/Impl/BSONEachRowRowOutputFormat.cpp:440-443 [dismissed by author -- https://github.com/Add UUID2 data type with correct sorting #110084#discussion_r4285608847]: Inferred-schema BSON round-trips still change the identifier: UUID2 writes canonical bytes, while inference selects historical UUID and decodes the other layout. Preserving historical files explains the tradeoff but does not preserve the exported identifier on inferred import. No further inline reply or thread action was taken.

⚠️ Majors

  • src/Processors/Formats/Impl/ValuesBlockInputFormat.cpp:704 [dismissed by author -- https://github.com/Add UUID2 data type with correct sorting #110084#discussion_r4285608852]: The retained typed-column cast rejects a nested NULL beside a Variant-carried UUID2 despite input_format_null_as_default = 1 when expression templates are disabled. The author accepts this exception for the rare combination; the setting's behavior still differs on this path. No further inline reply or thread action was taken.
Tests
  • ⚠️ Add direct-versus-persisted coverage for a positional comparison in numbers and a parameterized view's ordinary structure argument.
  • ⚠️ Compare indexed results with use_primary_key = 0 for ifNull and coalesce over Nullable(Tuple(UUID1)), using opposite-order identifiers, granularity 2, and allow_key_condition_coalesce_rewrite = 0.
Missing context / blind spots
  • ⚠️ The two residual fixes are verified by concrete source traces, without runtime execution: this review job has no ClickHouse binary and prohibits nested test runs. The requested focused regressions would close that gap. The fetched Praktika reports list 15,479 passed tests, zero failed, and 4,600 skipped; they do not cover these traces.

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 Verdict

Status: ❌ 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-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

@ClickHouse/integrations team, please, take a look

alexey-milovidov added a commit that referenced this pull request Jul 12, 2026
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]>
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
alexey-milovidov added a commit that referenced this pull request Jul 12, 2026
`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]>
alexey-milovidov added a commit that referenced this pull request Jul 12, 2026
`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]>
alexey-milovidov added a commit that referenced this pull request Jul 12, 2026
`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]>
Comment thread src/Parsers/ASTDataType.h Resolved
Comment thread src/Functions/array/mapOp.cpp Resolved
alexey-milovidov added a commit that referenced this pull request Jul 12, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Jul 12, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Jul 12, 2026
…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]>
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
Comment thread src/DataTypes/DataTypesBinaryEncoding.h Resolved
alexey-milovidov added a commit that referenced this pull request Jul 13, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Jul 13, 2026
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, the La Casa Del Dolor (amd_msan) shutdown timeout is tracked in #129956 (and #129908).

Pushed bb84123: merged master (resolved the conflicts with the -WithMemoryTracking container migration of src/Processors/Formats) and addressed the three latest review threads: nested UDF expansion inside APPLY respects scoped lambdas, UUID1 survives data_type_default_nullable in ALTER, and groupArraySorted over Variant / Dynamic / JSON uses a column-backed state.

Comment thread src/Interpreters/convertFieldToType.cpp Resolved
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
alexey-milovidov and others added 2 commits November 10, 2026 07:00
…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]>
Comment thread src/DataTypes/DataTypeUUID2.h Resolved
alexey-milovidov and others added 2 commits November 11, 2026 12:35
…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]>
alexey-milovidov and others added 2 commits November 12, 2026 20:04
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 3376166:

  • Merged master. Resolved the conflicts with output_format_arrow_uuid_as_fixed_byte_array in the native Arrow writer: with the setting, neither UUID nor UUID2 carries field metadata, and UUID2 still writes the canonical bytes. Also resolved the parquet:: namespace cleanup in Parquet/Write.cpp.
  • Addressed the two latest review threads: a fresh binder for the synthesized APPLY lambda, and argument substitution into UDF bodies that respects the scope of nested lambdas.

The previous red was only Performance Comparison (arm_release), which did not run because of an infrastructure problem: test selection unavailable: GitHub API 403 Client Error: rate limit exceeded.

… 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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed e91ff12: merged master. Resolved the conflicts:

  • IDataType.h: kept isUUID2 alongside the new [[nodiscard]] predicates of WhichDataType.
  • AvroRowInputFormat.cpp: kept the path argument of createDeserializeFn together with the new target_type capture in the null_as_default union branch.
  • AvroRowOutputFormat.h: kept getUUID2Paths next to the now [[nodiscard]] getSchema.
  • Parquet/SchemaConverter.h: kept both the new addLevelsOnlyPrimitive / addMissingElementOfTupleInArray declarations and the uuid2_preferred comment.
  • MergeTreeIndexBloomFilter.cpp: tryResolveMapIndexInfo now takes both key_field_type (this PR) and index_nodes / map_node (master, structural matching of index expressions).

The clickhouse binary builds. 04550_uuid2_map_bloom_filter and 04551_uuid2_map_subscript_lookup pass, and an Avro / Parquet UUID2 round-trip still works. All open review threads already have replies.

alexey-milovidov and others added 2 commits November 19, 2026 06:49
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 800eabc: merged master and fixed the red from the previous run.

  • Conflicts: LogicalExpressionOptimizerPass keeps the new Variant opaque-filter check from master before the UUID/UUID2 layout check. transform keeps the String/FixedString exemption from master inside entry_converted_exactly. AvroDeserializer takes both the Iceberg initial-default arguments from master and the UUID2 paths. docs/_migration/slug-map.csv is dropped, as on master.
  • Build (arm_tidy): marked UUID2Converter::convertField and getUUID2Paths [[nodiscard]].
  • Fast test 05453_uuid2_apply_udf_loop_identity_values: master now rejects loop in CREATE TABLE ... AS, so the two-argument loop(database, table) case is nested in remote. It still checks that the scalar database argument is not rewritten. A one-argument control does get rewritten.

Comment thread src/DataTypes/DataTypeUUID2.h Resolved
Comment on lines +257 to +259
const auto * name = equals->arguments->children[0]->as<ASTIdentifier>();
if (name && equalsCaseInsensitiveString(name->name(), "structure"))
return {&equals->arguments->children[1]};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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; -- 0

A 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

alexey-milovidov and others added 4 commits November 21, 2026 22:14
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 6db09da:

  • Merged master. The only conflict was in ProtobufSerializerUUID::readRow: kept the UUID2 half swap together with the new columnRef accessor from master.
  • Addressed the three review threads from 2026-11-19: nested map summation with UUID2 keys in SummingMergeTree, structure = ... as an ordinary comparison in values, and UUID2 in the Parquet variant encoder. Each has a new stateless test.

The previous red was only the review-threads gate in Finish Workflow (the full CI suite was skipped). Three older threads remain open on purpose: they have replies explaining why the change is not made (the BSON byte layout of the historical UUID, a nested NULL next to a Variant-carried UUID2 in Values, and TimeSeries version 9 with the legacy ON CLUSTER format). They need a human decision, and they keep the gate blocked until resolved.

alexey-milovidov and others added 3 commits November 24, 2026 18:21
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed c690415:

  • Merged master (no conflicts).
  • Style check / settings_changes_history: the uuid_type_version record is now under 26.12, the current version.
  • Fast test (04402_uuid2_data_type, 04659_uuid2_type_version_udf_expansion): master no longer supports distributed_ddl_entry_format_version below 3, so both tests failed with UNKNOWN_FORMAT_VERSION. The explicit UUID2 materialization on that legacy ON CLUSTER path became unreachable after the merge and is removed. The tests now check the same materialization with the default format version. Both pass locally on the merged build.

Review threads: the TimeSeries legacy-cluster thread is obsolete for the same reason and is resolved. Two threads remain open on purpose, each with a reply explaining why the change is not made: the BSON byte layout of the historical UUID, and a nested NULL next to a Variant-carried UUID2 in Values. They need a human decision, and they keep the review-threads gate in Finish Workflow blocked until resolved.

This branch was successfully deployed

1 active deployment
staging - docs — c6904150 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-data-types Type system & core datatypes used across query planning/execution. pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix the wrong ordering of the UUID data type

3 participants