Repository navigation
Enumerate and rebuild nested data types through IDataType - #119118
Conversation
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.
|
Workflow [PR], commit [fa31229] Summary: ✅
AI ReviewSummaryThis PR centralizes recursive type walking and rebuilding behind Final Verdict
LLVM Coverage ReportMeasured on commit fa31229.
Changed lines: Changed C/C++ lines covered: 259/287 (90.24%) · Uncovered code |
`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.
`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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes790 object files changed (+73.48 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units3118 translation units recompiled, 16805 s compile time in total, 3117 of them have a recent master baseline. |
…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]>
|
🕵 @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 ( |
|
Acknowledged. I'm investigating the unstable |
|
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 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is great, I like it!
`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]>
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.
…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]>
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]>
Walking the types nested in a data type was written by hand once per caller, and the copies had drifted apart:
IDataType::forEachChildArray,Tuple,Map,Nullable,LowCardinality,Variant,ObjectAggregateFunctionarguments,QBit,FunctionreplaceNestedSimpleTypesNullable,Array,Tuple,Map,VariantLowCardinality,Object,QBitrecursiveRemoveLowCardinalityNullable,Array,Tuple,Map,LowCardinalityVariant,Object,QBithasNullableArray,Tuple,Map(value only)LowCardinality,Variant,ObjecttransformTypesRecursivelyNullable,Array,Tuple,MapLowCardinality,Variant,ObjectadoptDateTimeLeafTimezones(#113781)Nullable,LowCardinality,Array,Map,TupleVariant,ObjectThree types that have children -
QBit,AggregateFunctionandFunction- are invisible to all of them.DataTypeMap::forEachChildvisits its children in a different order from every other walk (key, value, then their subtrees, rather than depth-first), andDataTypeObject::forEachChilditerates astd::unordered_map, so its order is not stable even within one process.The root cause is that
IDataTypeexposes 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, theObjectlimits). 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 (getChildrenremains as a non-virtual convenience that builds the whole list).cloneWithChildren- rebuild the type with different children, keeping everything that is not a child:Tupleelement names and explicit-name mode,Variantdiscriminator order,Objectpath names and limits.DataTypes/TypeTree.hthen writes the recursion once -forEachInTypeTreeandanyInTypeTreefor the read-only walks,rewriteTypeTreefor the rebuild - andIDataType::forEachChildis replaced at all of its call sites and removed.rewriteTypeTreematerializes a replacement list only for a node whose child actually moved, sosetVersionToAggregateFunctions, whichNativeWriterruns 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::rederiveForlets a custom name follow the rewrite (Nesteddoes; the default refuses, because aPointover aTuplethat is no longer twoFloat64is not aPoint), andCustomizationPolicysays what to do when it cannot.SimpleAggregateFunctionneeded 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. SorederiveForis handed the rewrite that produced the type, andSimpleAggregateFunctionputs its copy through it. Without that,Nativeannounces one aggregate-state version to an old peer while writing the payload with another - which is exactly what04903_native_simple_aggregate_function_nested_state_versioncaught 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;
typeCanHideTheValueTypeinCore/Block.cppstops recursing inside an already recursive visitor, which had it visit each nested type once per enclosing type; andDataTypeObject'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:
QBit,AggregateFunctionandFunctionreal children. That widens what every migrated walk sees and needs auditing per caller.recursiveRemoveLowCardinalityonrewriteTypeTree. Its type half must stay in lock-step with the column half (ColumnPtr recursiveRemoveLowCardinality), which has nogetChildrento follow, so widening only the type side would break the pairing.KeyCondition::adoptDateTimeLeafTimezoneswants. It belongs in the PR that uses it rather than landing unexercised here, which is also whyCustomizationPolicy::Refusehas no caller yet.Related: #113781
Changelog category (leave one):
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
26.10.1.1531-master(included in26.10and later)