Skip to content

Normalize names used in plan cache key calculation - #116781

Merged
nickitat merged 33 commits into
masterfrom
autopr-build-independent-cache-keys
Oct 14, 2026
Merged

nickitat merged 33 commits into
masterfrom
autopr-build-independent-cache-keys

Conversation

@nickitat

@nickitat nickitat commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Normalized build-local analyzer qualifier names out of automatic parallel replicas plan-cache keys, so equivalent single-node and parallel-replicas plans can reuse collected dataflow statistics more often.


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

Version info

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

A query tree numbers its tables independently, so the same column is
`__table1.x` inside a shipped fragment and `__table2.x` in the plan that
encloses it, and composed names carry the qualifier too, e.g.
`in(__table1.l_orderkey, __set_...)`. `ActionsDAG` folds those names into its
hash and steps serialize them, so two builds of the same query produce different
keys for reads that are identical down to the granule - which is what stops
`considerEnablingParallelReplicas` from matching its probe plan against the
single-node plan.

Give `updateHash` and `serialize` a build-independent mode that identifies a node
by what it computes - type, function, children, constant value - and not by how
this particular plan named it. Two same-shaped expressions over same-typed
columns then share a key, costing a slightly-off `output_bytes` estimate and
never a wrong result, which is the trade `JoinStep` already makes here by hashing
its output column types and never their names.

A `Const(Set)` column is excluded the same way: each build prepares its own `Set`
object, so its value differs between plans while its identity - the
content-derived `__set_<hash>_<hash>` in `result_name` - does not. This mirrors
the `is_runtime_filter_id` carve-out directly above it.

Join keys get the same treatment, identified by their position in that side's
header and their type. A key that is not a column of the header is produced by
the join itself and contributes nothing.

On TPC-H sf=1 this makes the automatic-parallel-replicas decision reach the cost
model on `o08` and `o09`, which previously bailed without costing anything. All
44 queries return results identical to single-node.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [59bbe60]

Summary: ✅


AI Review

Summary

This PR makes the Auto-PR cache keys much more build-independent by stripping analyzer-local __tableN qualifiers and switching many step serializers over to structural identifiers. It fixes several earlier mismatches, but three real gaps remain: higher-order lambda captures still key on branch-local rendered names, lazy materialization's second read still never participates in the dataflow cache key, and the new isSerializable() guard turns non-serializable transforms into step-name-only aggregation keys instead of failing closed. I would not merge until those are addressed.

Findings

⚠️ Majors

  • [src/Interpreters/ActionsDAG.cpp:351] Higher-order expressions still carry branch-local capture labels into the build-independent key. hash_capture hashes capture.return_name / capture.captured_names, and serializeCapture at src/Interpreters/ActionsDAG.cpp:5035 routes the same fields through writeCacheKeyColumnName, which falls back to normalized rendered text when the outer step header cannot resolve the alias. Equivalent lambdas such as plus(k, 1) vs plus(__table2.a, 1) therefore still miss the same Auto-PR entry even when the nested ActionsDAG and captured slots match. Suggested fix: omit these labels in cache-key mode, or replace them with a structural id derived from the nested DAG / captured-slot ordinals, in both the hash and serialization paths.
  • [dismissed by author -- https://github.com/Normalize names used in plan cache key calculation #116781#discussion_r4116968009] [src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp:621] The lazy-materialization read is still absent from the key. The dispatch only hashes SourceStepWithFilter, ReadFromParallelRemoteReplicasStep, and ITransformingStep, so LazilyReadFromMergeTree contributes the empty-source constant, yet considerEnablingParallelReplicas at src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp:1014 adds its bytes into the same statistics entry as the main read. Two queries with the same main scan but different deferred columns can therefore reuse one input_bytes / output_bytes sample and make the Auto-PR decision from the wrong read volume. Suggested fix: give LazilyReadFromMergeTree its own structural source hash, or make JoinLazyColumnsStep mix the lazy branch into the key explicitly.
  • [dismissed by author -- https://github.com/Normalize names used in plan cache key calculation #116781#discussion_r4116715809] [src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp:242] The new isSerializable() guard no longer fails closed on non-serializable transforms; it hashes only the step name. That is still a real collision in setAggregationHashTableCacheKeys: an aggregation above two different direct joins now stamps the same HashTablesStatistics preallocation key instead of skipping the hint, because FilledJoinStep at src/Processors/QueryPlan/JoinStep.h:147 contributes no structure beyond FilledJoin. The author reply treats this as dataflow-statistics-only, but this path feeds aggregation preallocation, not runtime dataflow collection. Suggested fix: keep non-serializable transforms out of this key, so the caller skips preallocation unless a step gets an explicit structural hash.
Final Verdict

⚠️ Needs changes before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 27, 2026
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 59bbe607d with master 2079ed3d5 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dca38d441; 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

85 object files changed (+72.61 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp.o 145.42 KiB 177.61 KiB +32.18 KiB (+22.13%)
src/CMakeFiles/dbms.dir/Analyzer/TableQualifiers.cpp.o new 24.13 KiB +24.13 KiB
src/CMakeFiles/dbms.dir/Interpreters/ActionsDAG.cpp.o 1.33 MiB 1.35 MiB +19.96 KiB (+1.47%)

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

1495 translation units recompiled, 10277 s compile time in total, 1494 of them have a recent master baseline.

Job report

nickitat and others added 2 commits August 31, 2026 14:52
The build-independent hash dropped every `result_name` and the value of every `Const(Set)`, so a
node was identified by its type and shape alone. That collapses more than the branch-local names it
was meant to drop: `PREWHERE b > 5` and `PREWHERE c > 5` hashed to one key, as did `a IN (SELECT k
FROM t1)` and `a IN (SELECT k FROM t2)`, and `a IN (1,2,3)` and `a IN (7,8,9)`. The key addresses a
process-wide statistics cache, so one predicate's row estimate was served to an unrelated one.

The set carve-out was also justified by a claim the same flag makes false: the comment said the set's
identity survives as the `__set_<hash>` in `result_name` "hashed above", but `result_name` is exactly
what build-independent mode suppresses.

Both are discriminated again without reintroducing a build-dependent key:

- An INPUT keeps its name. At a read step an input is a physical column - verified `b`, not
  `__table1.b`, even under a join - so its name is identical in every build. Only derived nodes carry
  the branch-local composed names (`in(__table1.x, ...)`) this mode exists to drop.
- A `Const(Set)` mixes in `FutureSet::getHash`, the set's content-derived identity, which is O(1) and
  equal across builds by construction (`FutureSetFromSubquery` is moved between plans keeping it).

All eight keys above are distinct now. The parallel-replicas match this branch exists for is
unaffected: on TPC-H sf=1 the same queries reach the cost model before and after (a21, o08, o09),
measured by rebuilding with and without this commit.

The key is not observable from SQL and a gtest around `updateHash` needs more DAG-construction
scaffolding than it is worth, so the collision check above is not automated.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
`ActionsDAG::serialize` stopped writing node names for a cache key, but three steps write name fields
of their own outside the DAG payload: `FilterStep` and `ObjectFilterStep` write `filter_column_name`,
and `ArrayJoinStep` writes the array-joined column names and its element-filter column. Those names
are exactly the branch-local ones this mode exists to drop - a filter column reads
`greater(__table1.x, 5_UInt8)` inside a shipped fragment and `greater(__table2.x, 5_UInt8)` in the
plan enclosing it - so two identical plans still hashed differently.

Each is replaced by a build-independent stand-in: a filter column by what its expression computes
(`ActionsDAG::getOutputIdentity`), an array-joined column by its position in the step's input header.
`updateHash` grows a `skip_input_names` mode for this: at a read an input is a physical column and its
name must be kept (see the previous commit), but above a read the inputs are `__table1.x` and hashing
them puts the drift straight back.

On TPC-H sf=1 the automatic-parallel-replicas decision now reaches the cost model on six of the nine
queries it previously reached on three: `a05`, `a07`, `a10` and `o13` are new, `o08` and `o09` still
match.

`a21` regresses - it reached the cost model before and now bails with "0 candidates of kind Join over
the same input". The result is stable and identical whether the filter column is replaced by an
output index, by a name-carrying expression identity, or by a fully name-free one, so it follows from
dropping the raw name rather than from the choice of stand-in. Not root-caused.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
nickitat and others added 2 commits August 31, 2026 18:58
`ActionsDAG::appendInputsForUnusedColumns` appends the sample-block columns a DAG does not use by
iterating an `unordered_map` keyed by those column names, so the order of the appended `INPUT` nodes
follows the hash of names like `__table1.l_orderkey`. That order is observable in the plan cache key:
`serialize` assigns node ids in `nodes` order and writes both the node records and the `inputs` id
list, so permuting appended inputs of differing types changes the key even though build-independent
mode blanks every `result_name`. Two builds of the same logical DAG that differ only in the table
index can therefore still hash differently - the drift the rest of this branch removes. A standalone
check on libc++ confirms the order does flip with the prefix: for a lineitem-shaped name list it is
stable up to five entries and differs from six on.

Appending in `sample_block` order makes the function deterministic in the names. It is also one less
thing that silently depends on a container's traversal order.

This fixes a latent drift, not a live mismatch. On TPC-H sf=1, across 44 queries (the official set
and the join-to-`IN` rewritten set) run with `automatic_parallel_replicas_mode = 2`, the set of
queries whose replicas-plan top node finds a matching hash in the single-node plan is identical
before and after (26 match, 11 miss, the rest never reach the comparison), and all 44 results are
byte-identical. An instrumented build explains why: of 1595 calls per run, 1543 append nothing and 33
append a single column, where order cannot matter. All 19 calls that append two or more do append in
an order that differs from the header order, and 14 of them append two or more distinct types, where
the permutation reaches the key - but every one of them occurs in a query that never reaches the hash
comparison (`o02`, `o17` and `o20` build no replicas plan at all, `o21` is rejected as unsupported).
Within those queries both plan builds happened to produce the same order.

So this does not recover any of the 11 remaining mismatches and is not the cause of the unexplained
`a21` regression noted in the previous commit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Appending the unused pass-through columns in header order rather than in `unordered_map` order changes
the order in which those `INPUT` nodes are printed by `EXPLAIN actions`, and with it the `Positions`
line. Two references record that order and needed re-recording: in both, the appended inputs were
previously listed in an order that is not the header order (`__table3.number` before
`__table2.number`, `__table1.name` before `__table3.name`) - a direct sighting of the name-hash order
the previous commit removes. Only the query plans printed change; no query result does.

The other 52 stateless tests whose reference contains an `Actions: INPUT` line pass unchanged (the 3
that fail here are distributed tests that need a cluster this local server does not have).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
nickitat and others added 2 commits August 31, 2026 20:54
`normalizeGenuineQualifiers` rewrites `__tableN.<tail>` to `__table.<tail>`, which is what makes a shard
column comparable with the initiator's column of the same name: `buildQueryTreeForShard` reruns
`createUniqueAliasesIfNecessary`, whose numbering restarts at 1, so the same column is `__table1.x` on one
side and `__tableK.x` on the other. Nothing else about the name differs.

The cache-key hashing has the same problem for the same reason, so the function moves to
`Analyzer/TableQualifiers.h` as `normalizeGeneratedTableQualifiers` and its `genuine_tails` argument
becomes optional. That set is what tells a real qualifier from user text that merely looks like one (a
`'__table1.'` constant, a lambda argument), and it can only be collected from a query tree; a caller
without one passes `nullptr` and normalizes every `__table<digits>.`.

Behaviour-preserving: the existing caller passes the same set it did before.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
The previous commit's `skip_input_names` dropped INPUT names for any DAG above a read, on the grounds that
those names are branch-local (`__table1.x` here, `__table2.x` there). It drops too much: an INPUT's name is
the only thing telling two same-typed inputs apart, so `WHERE a > 5` and `WHERE b > 5` over two columns of
one table hashed alike, and `serialize`'s blanket name-blanking did the same to the DAG bytes. That is the
collision `b684c76` fixed for `PREWHERE`, reintroduced one commit later for every filter that stays a
`FilterStep` - `HAVING`, a filter over a join, anything `optimize_move_to_prewhere` does not take.

Measured on TPC-H sf=1, `SELECT sum(l_tax) FROM lineitem WHERE <col> > 5` with
`optimize_move_to_prewhere = 0`, for two `Decimal(15, 2)` columns of `lineitem`:

    before   l_quantity -> 2808502039525504279     l_extendedprice -> the same entry, no lookup miss
    after    l_quantity -> 15112408067458365075    l_extendedprice -> 4930988354033854602

The branch-local part of such a name is only the index of the analyzer-generated table qualifier, so it is
normalized away (`normalizeGeneratedTableQualifiers`) instead of dropped, in `updateHash` and in `serialize`
alike. `skip_input_names` goes with it: a normalized input name is build-independent at a read and above
one, so one flag covers both callers. There is no query tree at the hashing site to tell a genuine
qualifier from user text shaped like one, and none is needed - a name that normalizes onto another still
has to survive the node's type and, for a constant, its value.

Derived names stay dropped. They differ between two builds by more than the qualifier index: the shard
rewrite inlines and renames (see `CollectAliasNameTranslationVisitor` and the `JOIN USING` inlining in
`buildQueryTreeForShard`), so keeping them would trade this collision for a new class of mismatches.

Also says what the `Const(Set)` carve-out actually does, which the old comment got wrong: `ColumnSet` is a
dummy column whose `updateHashWithValue` is empty, so there is no value being suppressed there - the branch
only ADDS `FutureSet::getHash`, and it has to, because the set's `__set_<hash>_<hash>` name is dropped with
every other derived name. Restructured accordingly; the hash bytes do not change (the branch it replaces
called a no-op). The same correction applies to the runtime-filter id carrier, whose name is likewise not
hashed in a build-independent hash. Verified still discriminating: three different `IN` subqueries produce
three different keys (12479658878681550974, 5065865790218217053, 16608854870954493476).

Auto-PR matching is unaffected: on the same 44-query TPC-H sf=1 sweep the set of queries whose
replicas-plan top node finds a match is identical (26 match, 11 miss). 53 of the 55 stateless tests whose
reference contains an `Actions: INPUT` line pass; the two that do not are distributed tests that fail
identically on the unpatched binary in this local setup, which has hand-written cluster definitions.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
nickitat and others added 5 commits September 1, 2026 11:51
`ActionsDAG` stopped putting branch-local names into the cache key, but a step's own payload still
carried them: `AggregatingStep` writes its GROUP BY keys and the aggregate descriptions (both the
aggregate's name and its argument names) verbatim, `LimitStep` writes the sort description of a
`WITH TIES` limit, and so on down the list. Those names are composed by the planner from the
`__tableN` alias `createUniqueAliasesIfNecessary` assigns, and the two plan builds number their tables
independently, so the same aggregation hashes differently. Instrumenting the two passes over TPC-H
sf=1 `q13` shows it exactly:

    parallel-replicas plan   keys=[__table3.o_custkey]  aggregates=[count(__table3.o_orderkey)]
    single-node plan         keys=[__table4.o_custkey]  aggregates=[count(__table4.o_orderkey)]

followed by `Cannot find step with matching hash in single-node plan`.

`Serialization::writeColumnName` now writes such a name through
`normalizeGeneratedTableQualifiers` when the serialization is a cache key, and the two shared
description serializers take the same flag. Every step serializer that carries a semantic column
reference goes through one or the other: `AggregatingStep` (keys, grouping-set keys, aggregates, both
sort descriptions), `MergingAggregatedStep`, `TotalsHavingStep` (aggregates and filter column),
`CubeStep`, `RollupStep`, `DistinctStep`, `LimitByStep`, `NegativeLimitByStep`, `LimitStep`,
`NegativeLimitStep`, `SortingStep`, `WindowStep`, `GatherReceiveStep` and `BuildRuntimeFilterStep`.
Exchange and shard ids are left alone - they are not column names. The transmission path is untouched:
the new parameters default to false, so a plan on the wire serializes exactly as before.

On the 44-query TPC-H sf=1 sweep the number of queries whose replicas-plan top node finds its match
goes from 26 to 28: `a13` and `o13` are recovered, and all 44 results stay byte-identical.

Three of the nine queries that still miss (`a05`, `a07`, `a10`) do show this same signature - an
`Aggregating` node present in both plans with different hashes - but names are not their only
difference: their plans also differ structurally, with `Union` and `MergingAggregated` nodes in one
and not the other, because a subquery branch is parallelized on its own. That is a separate problem.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Dropping branch-local names from the key took away the only thing separating two same-typed columns of
the same name from different sources. In a self-join the plans for `WHERE l.id > 0` and
`WHERE r.id > 0` are otherwise isomorphic - same table twice, same keys, same output types, and the
filter above the join sees a single `id` input either way - so they now share one statistics entry and
one predicate's selectivity is served to the other. `master` did not have this: it hashed
`__table1.id` against `__table2.id`. Measured on `ts AS l JOIN ts AS r ON l.x = r.x`, with the filter
kept above the join (`query_plan_filter_push_down = 0`, `enable_join_runtime_filters = 0`):

    master                       l.id -> 16992701174599696619    r.id -> 670946966953170394
    before this commit           l.id -> 10037033402945051705    r.id -> the same entry
    after                        l.id -> 13986485224826269355    r.id -> 7983524888721527377

The join step already mixes in its output column types and deliberately leaves out their names. It now
also mixes in, per output column, which side produced it - membership in the left or the right child's
header, expressed in the post-`RIGHT`->`LEFT` orientation so it stays orientation-invariant. That is a
structural property, identical in both plan builds, so it discriminates without putting a name in the
key. A column whose name is in both headers says nothing about a side and contributes an `unknown`
marker instead of an arbitrary choice.

The comment says what the rest of this key already assumed: the bit is best-effort, and the cases it
cannot separate cost nothing in correctness. A false-positive match only estimates `input_bytes` /
`output_bytes` from an isomorphic plan's sample and so enables or skips parallel replicas
sub-optimally; these statistics feed the decision, never the execution.

No match is lost to the extra bit: the 44-query TPC-H sf=1 sweep stays at 28 matching queries and all
44 results stay byte-identical to the unpatched binary. 53 of the 55 stateless tests whose reference
contains an `Actions: INPUT` line pass, the two that do not being distributed tests that fail
identically without this change in a local setup with hand-written cluster definitions.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
`03707_autopr_unsupported_cases` collects, per query shape, whether the automatic parallel replicas
optimization gathered any dataflow statistics, and its header says what to do when a shape starts
collecting them: drop the case and cover the new behaviour elsewhere. This branch makes one of them
collect:

    -unsupported_aggregation_over_aggregation	0	0
    +unsupported_aggregation_over_aggregation	4004842	13019046

The case was rejected with "Cannot find step with matching hash in single-node plan", and the reason
is the one this branch removes: the inner aggregation is what runs on the replicas, and the two plan
builds name its column differently - `__table3.number` in one and `__table4.number` in the other -
which used to reach the cache key through `AggregatingStep`'s GROUP BY keys and aggregate argument
names.

So the query moves to the supported group, where it also guards the other direction: a change that
stops the optimization from matching this shape again fails the test instead of quietly making a
case above pass. Ran 10 times, with and without settings randomization.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Three payloads were left writing plan-build-local names into a cache key:

- `WindowStep` serialized each window function's own name and its argument names verbatim, and the
  window's `window_name`, which is `calculateWindowNodeActionName`'s rendering of the whole window
  definition and so embeds the same qualified columns (`PARTITION BY __table1.x ...`). All three go
  through `Serialization::writeColumnName` now, which meant threading the context into
  `serializeWindowFunctions`.
- `FractionalLimitStep` still called the two-argument `serializeSortDescription`, leaving a
  `WITH TIES` fractional limit sensitive to the qualifier numbering. It arrived with the merge from
  master, after the sweep that fixed the other sort-bearing steps; re-running that sweep found
  `GatherSendStep` in the same state, so both are fixed here.

`ActionsDAG::getOutputIdentity` also failed open: a name that is not an output returned the hash of
an untouched `SipHash`, which is one value shared by every DAG that misses, so unrelated plans
collapsed onto a single key and could be served each other's statistics. Every caller names an output
of its own DAG - a filter column, an array-joined column - so a miss is a broken invariant: it is now
a `chassert`, and the release path mixes in a marker plus the normalized name so that a miss stays
distinguishable instead of merging everything.

The `chassert` is deliberately not a throw. This runs during plan optimization for every query while
`automatic_parallel_replicas_mode` is on, and the worst a bad key can do is estimate from the wrong
sample and enable or skip parallel replicas sub-optimally - never a wrong result. Turning that into a
failed query would be the more damaging outcome, while the assertion still surfaces the invariant
break in debug and CI builds.

TPC-H sf=1 stays at 28 matching queries of 44, the self-join pair stays discriminated, and 166 of the
168 stateless tests covering `Actions: INPUT` references, window functions and the Auto-PR shapes
pass - the two that do not are distributed tests that fail identically without this change in a local
setup with hand-written cluster definitions.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
nickitat and others added 2 commits September 1, 2026 18:14
Erasing the qualifier index makes `__table1.id` and `__table2.id` the same string, which is what lets
the two plan builds agree - and also what makes the same column name taken from two different join
inputs indistinguishable. Two mirror queries over a self-join shared one statistics entry:

    SELECT l.id, sum(r.id) FROM ts AS l JOIN ts AS r ON l.x = r.x GROUP BY l.id
    SELECT r.id, sum(l.id) FROM ts AS l JOIN ts AS r ON l.x = r.x GROUP BY r.id

Two things were needed, and the first alone is not enough.

`writeCacheKeyColumnName` now writes a column's POSITION in the step's input header before the
normalized name. The header reaches the payload through `Serialization::input_header`, set in the one
place that serializes a step for a cache key, and threaded into `serializeSortDescription` and
`serializeAggregateDescriptions`. This is the identification `ArrayJoinStep` and the join-key hashing
already use - where a key sits in the header, never what it is called.

That still left the pair above colliding, because their `Aggregating` steps group by the column at
position 0 either way: the reordering sits in an `Expression` between the join and the aggregation,
and a step that only permutes same-typed columns passes `sameByteLayout` and is treated as
transparent. So a permuting `ExpressionStep` is no longer transparent: when its outputs are its inputs
in a different order, the key mixes in that permutation. A rename-only step, whose permutation is the
identity, stays transparent - which is what keeps `__table1.a` -> `a` from breaking matching.

    before   l.id -> 8376947198283019229    r.id -> the same entry
    after    l.id -> 14096221200654257585   r.id -> 8230024904394760647

Both discriminators are kept because they cover different shapes: without the permutation the mirror
pair collides through a transparent projection, and without the position two aggregations directly
over a join, grouping by the column at different positions, would collide with no projection in
between.

Neither costs a match: TPC-H sf=1 stays at 28 of 44, all 44 results stay byte-identical, and the 301
stateless tests covering `Actions: INPUT` references, window functions, parallel replicas and the
Auto-PR shapes fail in exactly the same 34 places as the unpatched binary in this local setup - all of
them for want of a cluster or ZooKeeper.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
The step payloads got a position alongside the normalized name in the previous commit, but the DAG
kept identifying an INPUT by text alone. Two same-typed inputs whose names normalize together -
`__table1.id` and `__table2.id`, one column taken from each side of a join - therefore produced the
same `getOutputIdentity` and the same `ActionsDAG::serialize` payload, so a filter over one side was
indistinguishable from the same filter over the other as far as the DAG itself was concerned.

No end-to-end collision came of it: the surrounding key separates those plans either through the node
ids `serialize` writes (when both columns are inputs of the DAG, the predicate references a different
one) or through the join's per-output-column side bit (when only one survives the join). This makes
the DAG identity carry the discrimination itself instead of relying on what encloses it - the same
`writeCacheKeyColumnName` encoding the step payloads use, threaded in as an optional input header:

    Node::updateHash, getOutputIdentity, ActionsDAG::serialize    + const Block * input_header
    FilterStep, ObjectFilterStep, ArrayJoinStep, ExpressionStep, TotalsHavingStep   pass ctx.input_header

The read path keeps passing nothing, deliberately: a prewhere DAG at a read has one source, and its
inputs are already physical column names. The transmission path passes nothing either, so a plan on
the wire serializes exactly as before.

Nothing is lost to the extra discrimination: TPC-H sf=1 stays at 28 matching queries of 44, all 44
results stay byte-identical, and the 301 stateless tests covering `Actions: INPUT` references, window
functions, parallel replicas and the Auto-PR shapes fail in exactly the same 34 places as the
unpatched binary here, all of them for want of a cluster or ZooKeeper.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
nickitat and others added 2 commits September 2, 2026 11:56
The flaky check runs the changed test under randomized settings and caught
`supported_aggregation_over_aggregation` collecting nothing:

    -supported_aggregation_over_aggregation	1	1
    +supported_aggregation_over_aggregation	0	0

Not a matching failure - `optimizeTree` still logs "Found matching node in original plan: Aggregating"
under those settings. The randomizer picked `max_threads = 1` together with
`max_bytes_before_external_group_by = 18833856`, and neither alone does it: with one thread the whole
1e6-key table lands in a single aggregation state, exceeds the threshold and spills, and a spilling
aggregation calls `markUnsupportedCase` (`AggregatingTransform`), which is a deliberate exclusion from
statistics collection rather than anything to do with this branch. Delta-debugging the 192 randomized
settings down to that pair confirmed it, and a plain `GROUP BY` behaves the same way, so the exclusion
is not specific to this shape.

`max_bytes_before_external_group_by` is therefore pinned off for this query, the way the
`min`-over-projection case above already pins the projection settings. Ran the test 10 times with
randomization and once with the exact pair from the report.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Two more places carried planner-composed names into a cache key.

`serializeCapture` wrote `return_name` and the captured names verbatim. Both come from
`calculateActionNodeName`, so a higher-order expression capturing `__table1.a` in one plan build
captures `__table2.a` in the other and the two hashed differently. They are written through
`writeCacheKeyColumnName` now, and the nested lambda `ActionsDAG` is serialized against the same input
header, so a captured input keeps its position. The lambda's own argument names are written by the
user and identical in every build, so they stay as they are. A captured lambda inside a constant
column reaches `serializeCapture` from a second call site, which gets the same treatment without a
header - there is no step payload there to take one from.

The physical `JoinStep`'s residual cross-side predicate (`l.ts < r.ts` in `l.k = r.k AND l.ts < r.ts`)
is likewise hashed build-independently.

`calculateJoinStepCacheKeyContribution` is deliberately left hashing names, with a comment saying so.
It is not only an Auto-PR input: `optimizeJoin` recomputes the same value after reordering and keys
the hash-table-size statistics behind build-side selection with it. Making it build-independent breaks
`03279_join_choose_build_table` - the test runs one join twice with the operands swapped, the two then
share a statistics entry, and the second query is sized from the first's sample and picks the wrong
build table (`fail: 1000` / `fail: 100000` where both should be `ok`). Auto-PR can only have that
contribution build-independent once the two consumers are separated.

Verified: TPC-H sf=1 stays at 28 matching queries of 44; two higher-order queries capturing different
columns both match and keep distinct keys; two joins with different residual predicates likewise; and
the 1340 stateless tests over the `Actions: INPUT` references, window functions, parallel replicas,
joins and the Auto-PR shapes fail in exactly the same 95 places as the unpatched binary, all of them
for want of a cluster or ZooKeeper.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
nickitat and others added 2 commits September 2, 2026 15:56
`BuildRuntimeFilterStep::serialize` wrote `filter_name` verbatim. The name is
`_runtime_filter_<fingerprint>` and `calculateJoinFingerprint` folds the join keys' composed names, so
the id reads differently in the two plan builds exactly when the keys do - it is a per-build
rendezvous id between the build and the probe side, not something a build-independent key can compare.
It is now omitted in cache-key mode, the way the id carrier inside the probe's `ActionsDAG` already is.

This is a guard, not a live fix, and the comment says so. The step preserves both its rows and its
header, so `calculateHashFromStep` returns 0 for it and never reaches this serializer: an instrumented
build over TPC-H sf=1 logs `node kind=BuildRuntimeFilter own=0` for every such step. Accordingly the
44-query sweep does not move - 28 matching queries before and after - and the change matters only if
the step ever stops being transparent.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Dropping derived names in build-independent mode also dropped the only place a lambda's body appeared
in `Node::updateHash`. The node itself says nothing about it: `function_base->getName()` is just
`FunctionCapture`, and the composed name that does carry it -
`arrayExists(lambda(tuple(v), greater(v, 5)), a)` - is exactly what that mode removes. Two PREWHERE
predicates differing only inside the lambda therefore shared a read step's key:

    PREWHERE arrayExists(v -> v > 5, a)    14985721323846483935
    PREWHERE arrayExists(v -> v < 5, a)    the same entry
    PREWHERE arrayExists(v -> v > 7, a)    17119461281520951511

The third line shows how narrow the gap was: a captured constant is hashed, so 5 against 7 differed,
while `>` against `<` did not.

`updateHash` now hashes the capture and the body the way `serialize` writes them - the return and
captured names normalized, the types, the user-written argument names as they are, then the lambda's
`ActionsDAG` recursively. A lambda that arrives as a `ColumnFunction` constant rather than as the
node's function is covered too. After it the three keys are distinct.

Only in build-independent mode. An exact hash still carries the composed name, and `optimizeJoin` reads
exact hashes back to key the statistics behind build-side selection - the path
`03279_join_choose_build_table` guards - so there is no reason to disturb it.

TPC-H sf=1 stays at 28 matching queries of 44, and the earlier lambda-capture and self-join pairs are
unchanged. Of the 1372 stateless tests covering the `Actions: INPUT` references, window functions,
parallel replicas, joins, higher-order functions and the Auto-PR shapes, the two that fail beyond the
control's set are `04064_bare_function_name_as_lambda` and its `_wasm` sibling, which fail the same way
without this change: WebAssembly support is not enabled here.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
Comment thread src/Analyzer/TableQualifiers.cpp Resolved
`AggregateDescription::column_name` is the rendered call, a label rather than semantic state, and the
shard rewrite can render it differently for the same aggregate by inlining aliases. It is left out of a
cache key now, in both aggregate serializers; what the call is made of - the argument names, the function
and its parameters - is written either way, and the argument names still carry their column identity.
This is the same treatment the window function's rendered name got.

`FillingStep` wrote the `INTERPOLATE` required-columns map verbatim. With no alias,
`InterpolateDescription` fills that map straight from `actions.getRequiredColumns()`, so both halves can
be planner-composed names; they go through `writeColumnName` now.

TPC-H sf=1 stays at 30 matching queries of 44, and the mirror and lambda-body pairs stay distinct. Of
the 120 tests covering `WITH FILL`, `INTERPOLATE`, direct joins, `ROLLUP`, `CUBE`, `GROUP BY ... WITH
TOTALS` and the Auto-PR shapes - run with parallel replicas and `automatic_parallel_replicas_mode` on,
which is where these keys are actually computed - the five failures are the same five without this
change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
nickitat and others added 2 commits October 8, 2026 16:50
Four conflicts, all in files this branch owns, and `rerere` resolved all four from earlier merges. The
resolutions were reviewed rather than taken on trust - a stale one leaves no markers - and one was
wrong: master gave `Node::updateHash` a `with_variable_size_constant_values` parameter (hash a
variable-size constant by name and type but not by value, for keys where a wrong match only costs a
worse estimate; `getOutputIdentity` passes false), the child recursion forwards it, and the
lambda-capture recursion was left calling the three-argument overload. Inside a lambda body the flag
silently reverted to true, hashing exactly the heavy constants the false is there to skip. It forwards
the flag now.

Everything else came through both ways: master's new parameter, its `PrunedInput` /
`alignInputsWithPrunedChild` API and the `removeUnusedColumns` rework; and on this side the qualifier
normalization, the header-position identity, the lambda capture hashing, the `<no such output>` guard,
`Serialization::writeColumnName`, and in the key path `isByteTransparentTransform` with the permutation
hash, the `forwardsInputsInOrder` adoption guard and `step_version` inside the `isSerializable` guard.

TPC-H sf=1 stays at 30 matching queries of 44, the same queries as before the merge, and the four pairs
this branch separates - the mirror `GROUP BY`, the two sides of a self-join, the three `arrayExists`
bodies and the two same-typed PREWHERE columns - all stay distinct.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
`writeCacheKeyColumnName` wrote the normalized name next to the header position even when the header
already resolved the column. The name then only adds a way for two builds to disagree: the shard rewrite
can render the same slot as `k` in one and `plus(__table1.a, 1)` in the other by inlining an alias or a
`JOIN USING`, and normalizing erases just the qualifier's index - the reason this branch drops rendered
names elsewhere. Once the slot is known the name adds nothing either: two distinct columns of one header
sit at distinct positions, and two same-position columns of different headers are separated by the
child's own key. A name the header does not resolve still carries its normalized text, which is then all
there is.

I argued the opposite twice before measuring it, on the grounds that position plus name is strictly more
specific. The collision that would have justified that could not be produced: `sum(a)` against `sum(b)`
over a two-column table stays distinct (12341984467868293378 / 9850374709745298211), and so does
`sum(l_quantity)` against `sum(l_extendedprice)` under the same GROUP BY (1847235419050472265 /
1544612093042881198).

TPC-H sf=1 stays at 30 matching queries of 44 and the four pairs this branch separates stay distinct.
Across the 300-odd tests over the Auto-PR shapes, direct joins, `ROLLUP`, `CUBE`, `DISTINCT`,
`LIMIT BY` and `WITH FILL` - with parallel replicas and `automatic_parallel_replicas_mode` on, without
which none of this code runs - the four failures beyond the same run on the merge commit
(`01582_distinct_optimization`, `02901_parallel_replicas_rollup`,
`03254_limit_by_with_offset_parallel_replicas`, `04926_direct_join_prepared_source`) all pass on this
binary when re-run unloaded; that run took 2517s against the control's 121s.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KokE8F4umCbHS3mNb9XKrB
const auto write_name = [&](const String & name)
{
if (for_cache_key)
writeCacheKeyColumnName(name, input_header, out);

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.

writeCacheKeyColumnName only becomes structural when input_header resolves the name. capture.return_name never comes from the step input header, and a captured alias can miss it too, so cache-key mode still falls back to normalized rendered text for higher-order expressions. That leaves the same alias / JOIN USING instability the PR already had to strip from aggregate and window output labels: two equivalent lambdas can still serialize as plus(k, 1) vs plus(__table2.a, 1) even when the nested ActionsDAG and captured slots are identical. Since the nested ActionsDAG already serializes its output ids, these labels are redundant for the cache key. Please omit them in cache-key mode, and mirror the same change in hash_capture, instead of routing them through the sentinel path here.

@nickitat
nickitat added this pull request to stack #125688 October 13, 2026 21:10
@alexey-milovidov alexey-milovidov mentioned this pull request Oct 14, 2026
1 task done
@nickitat
nickitat added this pull request to the merge queue Oct 14, 2026
Merged via the queue into master with commit 47f6c0b Oct 14, 2026
327 of 328 checks passed
@nickitat
nickitat deleted the autopr-build-independent-cache-keys branch October 14, 2026 13:03
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
Since ClickHouse#116781, `FilterStep::serialize` hashes the filter with
`ActionsDAG::Node::updateHash` when it builds the hash table statistics
key of the join (`calculateHashTableCacheKeys`). That hash walks the
children of every node again, so on this chain it runs once per path, and
the first query hangs in the second optimization pass on current master
even with the fix. The merge queue run on 8d3778b (master 3389afa
+ this branch) timed out on it in Fast test and in the flaky check.

That walk is a different defect from the one fixed here, so the test turns
the statistics off and checks only the push-down probe.

Measured on master 3389afa + this branch: the test passes 50/50 with
random settings and 20/20 without (at most 0.9 s); without the new setting
it times out at 60 s. On master 2cb89c8 (no fix) the test still times
out at 60 s, stuck in `filterResultForNotMatchedRows`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 4, 2026
A row- and layout-preserving `ExpressionStep` that is not a pure
permutation contributed nothing to the hash-table statistics key, and
since ClickHouse#116781 a key column above it is identified by its header position
only. So `GROUP BY a + 1` and `GROUP BY intDiv(a, 1000000)` over the
same `UInt64` column shared one entry, and the 2-group aggregation
preallocated the 2M cells recorded by the other query. Through a
subquery (`SELECT k FROM (SELECT intDiv(a, N) AS k FROM t) GROUP BY k`)
the key column is named `__table1.k` for every expression, so that shape
already collided on 26.8 and 26.9.

Such a step now contributes `ActionsDAG::getComputedOutputsHash`: what
each output computes, with `ALIAS` nodes looked through and an `INPUT`
identified by its position in the step's input header, the way
`writeCacheKeyColumnName` identifies a column. The hash does not change
when expression merging absorbs an in-order rename into the step, which
automatic parallel replicas needs: the single-replica plan folds the
rename into the projection and the parallel-replicas plan keeps them
apart. Serializing the DAG instead writes the absorbed `ALIAS` nodes,
and `SELECT repeat(a, 100) AS a, b` at default merging then stops
collecting statistics again, the regression adcb292 removed.

`Node::updateHash` is split into the node's own content (`updateOwnHash`)
and the recursion into its children; existing hashes are byte-identical.

A lambda's captured names are still hashed by name, so a lambda that
captures a column is not rename-invariant; at worst automatic parallel
replicas does not match such a shape, the fail-closed direction.

Closes ClickHouse#125826

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@novikd novikd added the post-approved Approved, but after the PR is merged. label Nov 5, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
Conflict in `ActionsDAG::Node::updateHash`, which master split into `updateOwnHash` and whose
lambda capture and body hashing (ClickHouse#116781) runs only in build-independent mode. That block now runs
in both modes, replacing this branch's own exact-mode copy: the query condition cache keys on
exact hashes of DAGs built by `buildFilterActionsDAG`, where a lambda node is named only by its
signature, so the exact hash also needs the body. Exact mode only gains data, so no two nodes that
hashed apart before hash alike now.

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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... post-approved Approved, but after the PR is merged. pr-improvement Pull request with some product improvements 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