Skip to content

Enumerate and rebuild nested data types through IDataType - #119118

Merged
alexey-milovidov merged 12 commits into
masterfrom
datatype-children-interface
Oct 4, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
datatype-children-interface

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Walking the types nested in a data type was written by hand once per caller, and the copies had drifted apart:

walker descends into misses
IDataType::forEachChild Array, Tuple, Map, Nullable, LowCardinality, Variant, Object AggregateFunction arguments, QBit, Function
replaceNestedSimpleTypes Nullable, Array, Tuple, Map, Variant LowCardinality, Object, QBit
recursiveRemoveLowCardinality Nullable, Array, Tuple, Map, LowCardinality Variant, Object, QBit
hasNullable Array, Tuple, Map (value only) LowCardinality, Variant, Object
transformTypesRecursively Nullable, Array, Tuple, Map LowCardinality, Variant, Object
adoptDateTimeLeafTimezones (#113781) Nullable, LowCardinality, Array, Map, Tuple Variant, Object

Three types that have children - QBit, AggregateFunction and Function - are invisible to all of them. DataTypeMap::forEachChild visits its children in a different order from every other walk (key, value, then their subtrees, rather than depth-first), and DataTypeObject::forEachChild iterates a std::unordered_map, so its order is not stable even within one process.

The root cause is that IDataType exposes children only through kind-specific accessors (getNestedType, getElements, getKeyType, getVariants, getTypedPaths, …) and reconstruction only through kind-specific constructors that do not know the structural metadata (has_explicit_names, FixedDiscriminatorOrder, the Object limits). Every walk re-derives both halves and gets a slightly different answer.

What this does

Two operations on IDataType, so the per-type knowledge lives next to the type:

  • getNumberOfChildren / getChild - the types nested directly in this one, enumerated by index in a canonical order that is part of the contract. They return references to members the type already holds, so a walk allocates nothing and touches no reference count (getChildren remains as a non-virtual convenience that builds the whole list).
  • cloneWithChildren - rebuild the type with different children, keeping everything that is not a child: Tuple element names and explicit-name mode, Variant discriminator order, Object path names and limits.

DataTypes/TypeTree.h then writes the recursion once - forEachInTypeTree and anyInTypeTree for the read-only walks, rewriteTypeTree for the rebuild - and IDataType::forEachChild is replaced at all of its call sites and removed. rewriteTypeTree materializes a replacement list only for a node whose child actually moved, so setVersionToAggregateFunctions, which NativeWriter runs on every column of every block, allocates nothing for a type without aggregate states.

A rebuilt type cannot carry a customization over by construction, and dropping one silently is what makes a type announce a name it does not have. That decision is now explicit: IDataTypeCustomName::rederiveFor lets a custom name follow the rewrite (Nested does; the default refuses, because a Point over a Tuple that is no longer two Float64 is not a Point), and CustomizationPolicy says what to do when it cannot.

SimpleAggregateFunction needed more than a name: it keeps a second copy of its argument types inside the custom name, and both the printed name and the binary type encoding are built from that copy rather than from the storage type. So rederiveFor is handed the rewrite that produced the type, and SimpleAggregateFunction puts its copy through it. Without that, Native announces one aggregate-state version to an old peer while writing the payload with another - which is exactly what 04903_native_simple_aggregate_function_nested_state_version caught on the first CI run of this branch.

Incidental fixes that fall out of the shared walk: the new walks visit the root, which all ~25 callers previously did by hand, so a forgotten root check is no longer possible; typeCanHideTheValueType in Core/Block.cpp stops recursing inside an already recursive visitor, which had it visit each nested type once per enclosing type; and DataTypeObject's children now have a deterministic order.

What this deliberately does not do

No functional change is intended, and the parts that would change behaviour are left for follow-ups so each lands with the caller that exercises it:

  • Giving QBit, AggregateFunction and Function real children. That widens what every migrated walk sees and needs auditing per caller.
  • Re-basing recursiveRemoveLowCardinality on rewriteTypeTree. Its type half must stay in lock-step with the column half (ColumnPtr recursiveRemoveLowCardinality), which has no getChildren to follow, so widening only the type side would break the pairing.
  • The two-type lock-step walk that KeyCondition::adoptDateTimeLeafTimezones wants. It belongs in the PR that uses it rather than landing unexercised here, which is also why CustomizationPolicy::Refuse has no caller yet.

Related: #113781

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...


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

Version info

  • Merged into: 26.10.1.1531-master (included in 26.10 and later)

Walking the types nested in a data type was written by hand once per caller, and
the copies had drifted apart. Six recursions covered six different sets of
types: `recursiveRemoveLowCardinality` descends into `LowCardinality` but not
`Variant`, `replaceNestedSimpleTypes` does the opposite, `hasNullable` does
neither and looks only at the value side of a `Map`, and
`IDataType::forEachChild` covers both but visits a `Map` in a different order
from every other walk. Three types that have children - `QBit`,
`AggregateFunction` and `Function` - are invisible to all of them, and
`DataTypeObject::forEachChild` iterates a hash map, so its order is not even
stable within one process.

Give `IDataType` the two operations those walks actually need, so the per-type
knowledge lives next to the type instead of being re-derived by every caller:

- `getChildren` returns the types nested directly in this one, in a canonical
  order that is part of the contract.
- `cloneWithChildren` rebuilds the type with different children, keeping
  everything that is not a child: `Tuple` element names and explicit-name mode,
  `Variant` discriminator order, `Object` path names and limits.

`DataTypes/TypeTree.h` then writes the recursion once: `forEachInTypeTree` and
`anyInTypeTree` for the read-only walks, `rewriteTypeTree` for the rebuild.

A rebuilt type cannot carry a customization over by construction, and dropping
one silently is what makes a type announce a name it no longer has. That
decision is now explicit rather than implied: `IDataTypeCustomName::rederiveFor`
lets a custom name follow the rewrite - `Nested` does, while the default refuses
because a `Point` over a `Tuple` that is no longer two `Float64` is not a
`Point` - and `CustomizationPolicy` says what to do when it cannot.

`IDataType::forEachChild` is replaced at all of its call sites and removed. The
new walks visit the root, which every caller previously did by hand, so a
missing root check is no longer possible. `typeCanHideTheValueType` in
`Core/Block.cpp` also stops recursing inside an already recursive visitor, which
had it visit each nested type once per enclosing type.

`callOnNestedSimpleTypes` and `replaceNestedSimpleTypes` are subsumed by
`rewriteTypeTree` and removed; their only caller,
`setVersionToAggregateFunctions`, now uses it directly.

No functional change is intended. Widening coverage to the types that no walk
reaches today, and the two-type lock-step walk that `KeyCondition` needs for
`adoptDateTimeLeafTimezones`, are left for follow-ups so that each lands with
the caller that exercises it.
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa31229]

Summary: ✅


AI Review

Summary

This PR centralizes recursive type walking and rebuilding behind IDataType/TypeTree, migrates the existing callers to the shared walkers, and adds focused coverage for the versioned-aggregate/custom-name edge cases that previously regressed. I did not find any remaining correctness, compatibility, or hot-path performance issues in the current code after reviewing the full diff, the current implementation, and the prior discussion threads.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit fa31229.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 259/287 (90.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-data-types Type system & core datatypes used across query planning/execution. labels Sep 10, 2026
`04903_native_simple_aggregate_function_nested_state_version` caught this: for
`SimpleAggregateFunction(anyLast, Array(AggregateFunction(1, sumMap, ...)))` the
`Native` header announced state version 1 to an old peer while the payload was
written as version 0.

`SimpleAggregateFunction` is a custom name over a storage type, and it keeps a
second copy of its argument types inside the name. Both the printed name and the
binary type encoding are built from that copy rather than from the storage type,
so a rewrite that reaches an aggregate state through the storage side has to
reach the copy as well. `replaceNestedSimpleTypes` did that by recursing into the
copy with the same callback; `rederiveFor` was given only the rebuilt type and
had no way to.

Hand `rederiveFor` the rewrite that produced the type, so a custom name holding
its own nested types can put them through it. `SimpleAggregateFunction`
implements it; `Nested` ignores it, because it holds no copy that the rebuilt
`Array(Tuple(...))` does not already carry.

Only the case where the storage type is a wrapper needed this. When the storage
type is the `AggregateFunction` itself the type has no children, nothing is
rebuilt, and the callback in `setVersionToAggregateFunctions` handles its own
custom name as before.
Comment thread src/DataTypes/DataTypeObject.cpp Resolved
`VersionedLeafUnderJSONTypedPathIsNotAssigned` pinned the opposite: a versioned
state below a typed `JSON` path was left alone. That boundary was not a decision
about `JSON`, it was an artifact of the walk being hand-written per caller -
`replaceNestedSimpleTypes` had no `DataTypeObject` branch, while
`IDataType::forEachChild` did have one. Now that every walk goes through
`getChildren`, a typed path is a child like any other and the boundary is gone.

The test's own comment records why nothing depends on it: the declaration parses
but `JSON` serialization rejects it afterwards, so no column can have this
shape, and it explicitly disclaims describing a `Native` wire-format exception
because binary type encoding carries an aggregate-state version field of its
own. So the assertion is inverted rather than the traversal special-cased -
re-introducing a per-walk exception for one data type is what this change exists
to remove.
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fa312292e with master 2493c465d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

790 object files changed (+73.48 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/transformTypesRecursively.cpp.o 146.18 KiB 100.02 KiB -46.16 KiB (-31.58%)
src/CMakeFiles/dbms.dir/DataTypes/DataTypeObject.cpp.o 621.20 KiB 652.61 KiB +31.42 KiB (+5.06%)
src/CMakeFiles/dbms.dir/DataTypes/TypeTree.cpp.o new 26.57 KiB +26.57 KiB
src/CMakeFiles/dbms.dir/DataTypes/IDataType.cpp.o 203.89 KiB 222.92 KiB +19.03 KiB (+9.33%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsMinMax.cpp.o 2.55 MiB 2.53 MiB -16.59 KiB (-0.64%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3118 translation units recompiled, 16805 s compile time in total, 3117 of them have a recent master baseline.

Job report

Comment thread src/DataTypes/TypeTree.cpp Resolved
alexey-milovidov and others added 8 commits September 18, 2026 02:43
…nterface

# Conflicts:
#	src/Analyzer/Utils.cpp
Address review: `getChildren` returned a fresh `DataTypes` for every node a walk
visited, so `forEachInTypeTree`, `anyInTypeTree` and `rewriteTypeTree` allocated a
vector and bumped every child's reference count once per node, on paths that run per
block header (`setVersionToAggregateFunctions` in `NativeWriter`) and per query
(the validators migrated in this PR).

`IDataType` now exposes `getNumberOfChildren` and `getChild(index)`, which return a
reference to a member the type already holds; `getChildren` stays as a non-virtual
convenience for a caller that needs the whole list. `DataTypeObject` sorts its typed
paths once in the constructor instead of on every enumeration, and `doGetName` reuses
that order. `rewriteTypeTree` materializes the replacement list only for a node whose
child actually moved, so a rewrite that changes nothing allocates nothing.

Also migrate the two `forEachChild` callers master added in the meantime
(`filterPushDown.cpp`, `MergeTreeIndexJSONSubcolumnHelper.cpp`) and renumber the test
to `05231` to avoid a prefix collision with master.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Master grew five new callers of `IDataType::forEachChild`, which this branch
replaces: `comparisonCanMergeDistinctValues`, `equalsCanDisagreeWithHashTable`,
`hasMeaningfulFieldExtremes`, `typeContainsFloat` and the float check for
partition keys in `ReadFromMergeTree`. Each of them checked the root separately
and then accumulated a flag over the children; `anyInTypeTree` visits the root
itself and stops at the first match. The root checks through
`removeLowCardinalityAndNullable` are covered because `LowCardinality` and
`Nullable` enumerate their nested type as a child.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	src/Analyzer/Utils.cpp
`comparisonCanMergeDistinctValues` uses `anyInTypeTree` outside of `USE_EMBEDDED_COMPILER`, so the
build without the embedded compiler (Fast test) failed with an undeclared identifier.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119118&sha=6e1f006e6461a8dbb38169f9fb366b5138ae8b82&name_0=PR&name_1=Fast%20test
#119118

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eTree`

`IDataType::forEachChild` is removed by this PR, while master added more callers of it in
`InverseDictionaryLookupPass`, `DataTypeObject`, the Parquet reader, `optimizeTopK`,
`ReadFromMergeTree` and `MergeTreeWhereOptimizer`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nterface

Conflict resolution:
- `transformTypesRecursively`: keep the removal of `callOnNestedSimpleTypes` (superseded by
  `rewriteTypeTree`) and take `replaceNestedTypesInPair` added on master.
- `KeyCondition`: master moved `typeContainsFloat` into an earlier anonymous namespace and walked
  it with the removed `forEachChild`; port it to `anyInTypeTree` and drop the old copy.
- `MergeTreeIndexJSONSubcolumnHelper`: keep includes from both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119118&sha=e7bf7cca21daf64d7ff60af4392a38eee77b0e49&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%204%2F6%29 (hashed_dictionary #11, SELECT * FROM complex_key_hashed_dictionary FORMAT Null, reported +38.8% on ARM) and provide a fix in a separate PR. If the fix is already in progress, link it here. The same query was also reported slower on master itself (2026-10-03, arm 5/6) and on unrelated PRs #123059, #90740, #116692, #117346, so it looks flaky rather than caused by this change.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the unstable hashed_dictionary query #11 (SELECT * FROM complex_key_hashed_dictionary FORMAT Null) on ARM; I'll follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Fix: #123883

The slow mode depends on the ARM binary, not on this change: since mid-September some builds (official master ones and this PR's) are slow in every run of #11, adjacent builds are fast. The CPU profiles of both slow jobs put the whole difference in the single-threaded loop that deserializes all complex keys before DictionarySourceCoordinator starts reading. The PR moves that deserialization into the reading streams, one block at a time (hashed, hashed_array, range_hashed). On x86: hashed_dictionary #11 0.825 -> 0.608 s, hashed_array_dictionary #21 0.498 -> 0.282 s, range_hashed_dictionary #9 0.269 -> 0.140 s. Its own ARM perf run will be the first measurement there.

@alexey-milovidov alexey-milovidov left a comment

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.

This is great, I like it!

@alexey-milovidov alexey-milovidov self-assigned this Oct 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into master with commit a537662 Oct 4, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the datatype-children-interface branch October 4, 2026 20:12
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
alexey-milovidov added a commit that referenced this pull request Oct 5, 2026
`master` removed `IDataType::forEachChild` (#119118), so the merged tree did not compile:
`ReadFromMergeTree` and `FunctionTopKFilter` used it to look for a float or `Nullable`
anywhere inside the top-K key type. `anyInTypeTree` also checks the root, which is
equivalent here: both callers already treat a floating-point or `Nullable` root the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 12, 2026
The master merge brings ClickHouse#119118, which replaces the recursive
IDataType::forEachChild with getNumberOfChildren/getChild and the walks in
DataTypes/TypeTree.h. readsDynamicOrVariantValues checked the path type and
then every type below it through forEachChild; anyInTypeTree tests the root
and every type below it, so the predicate is unchanged.
alexey-milovidov added a commit to clickgapai/ClickHouse that referenced this pull request Oct 26, 2026
…19118

Resolve the add/add conflict in `05231_type_tree_walk_reaches_nested_types`:
take master's version of the test (from the merged PR ClickHouse#119118) and keep the
`Map` value version-pin case appended by this PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 27, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
Resolve the conflict with ClickHouse#113470, which declines a `Variant` expression in
`addComparisonFilter`: the one screen is now `comparisonOrdersTypeBeforeValue`,
which also covers `Dynamic` and `JSON` and a self-typed constant, and also keeps
such a `notEquals` out of the `notIn` merge (on master an `Array(Variant(Date,
UInt64))` chain still answers 1 there at defaults, where the answer is 0).

Port the predicate from the removed `IDataType::forEachChild` (ClickHouse#119118) to
`anyInTypeTree`, and use `getComparisonFilterExpressionNode` for the expression
type, as the key is now a template parameter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants