Skip to content

Keep same-type GROUP BY expressions apart in the hash table statistics key - #126148

Merged
fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:hash-table-stats-key-computed-expressions
Nov 4, 2026
Merged

fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:hash-table-stats-key-computed-expressions

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125826
Closes: #125825
Related: #116781

Changelog category (leave one):

  • Improvement

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

GROUP BY keys computed by different expressions of the same type, for example intDiv(a, 1000000) and a + 1 in SELECT k FROM (SELECT ... AS k FROM t) GROUP BY k, no longer share one hash table size statistics entry, so an aggregation preallocates its hash table for its own number of groups instead of for another query's. Closes #125826.

Description

Two GROUP BY queries whose key expressions keep the column type shared a statistics entry: after SELECT a + 1 AS k, count() FROM t GROUP BY k (2M groups), SELECT intDiv(a, 1000000) AS k, count() FROM t GROUP BY k preallocates 2M cells (64.14 MiB instead of 172 KiB on a debug build) and fails under max_memory_usage = 40000000. Results are not affected. On master both spellings collide (since #116781); on 26.8 and 26.9 only through a subquery, whose key is named __table1.k for every expression.

calculateHashFromStep returns 0 for a row- and layout-preserving ExpressionStep that is not a pure permutation, so a computing step leaves no trace in the key. Such a step now contributes a hash of what it computes (ActionsDAG::getComputedOutputsHash): ALIAS nodes are looked through, an input is identified by its header position, as in writeCacheKeyColumnName, and other nodes are hashed as in the build-independent updateHash. The hash does not change when expression merging folds a rename into the step, which automatic parallel replicas needs; hashing the serialized DAG instead makes SELECT repeat(a, 100) AS a, b stop collecting statistics at default merging (the regression adcb292 fixed).

Since #116781 a build-independent key also lost string and array literals: the constant's name, which spells its value, is dropped, and a value without a fixed size was left out. So trimBoth(s, 'x') and trimBoth(s, '0123456789'), or formatDateTime(d, '%Y') and formatDateTime(d, '%F %T'), shared an entry on master (not on 26.8 and 26.9). updateHash and serialize with for_cache_key now keep such a value up to 1 KiB; larger values and aggregate states are still left out.

The new test fails on master (five lines) and passes 50/50 randomized; its parallel replicas line fails with the serialized-DAG variant. 232 related tests, including the stateful test.hits ones, show no new failures.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1290-master (included in 26.11 and later)

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ Looking through ALIAS lets formatRow('JSONEachRow', a AS x) and the same call with another alias share automatic parallel replicas output-bytes statistics: FunctionFormatRow captures argument names but has no updateHash DISAGREE Master already shares this entry (the step hashed to 0 there). Keeping alias names is the serialized-DAG variant that breaks matching at default merging; hashing the captured names belongs to FunctionFormatRow::updateHash, which every build-independent hash lacks today. For GROUP BY preallocation the shared entry is right: an alias inside formatRow does not change the number of groups.
2 💡 The stateful automatic parallel replicas tests (test.hits) could not run locally on either binary noted Their queries have no layout-preserving computing step; CI runs them.
3 💡 A lambda that captures a column is not invariant under rename absorption noted At worst automatic parallel replicas declines such a shape; stated in the commit message.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261015-223400

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ae00155]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

Reviewed #126148 at ae001555ba1fce64f4341df746f29292a8002808. The change separates hash-table statistics for different same-type GROUP BY expressions and short literals while preserving rename-insensitive matching for automatic parallel replicas. The previous string-literal finding is fixed and covered by the regression test. No unresolved actionable findings remain.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @KochetovNicolai, could you review this? A row- and layout-preserving ExpressionStep that computes hashed to 0 in the hash table statistics key, so with the position-only key identity from #116781 GROUP BY a + 1 and GROUP BY intDiv(a, N) shared one entry; such a step now contributes a rename-invariant hash of what it computes (ActionsDAG::getComputedOutputsHash, built on a split of Node::updateHash).

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
A build-independent cache key drops every constant's name, and with
`with_variable_size_constant_values = false` it also dropped the value of
any constant without a fixed size. A string or array literal then had no
identity left in the key, so `GROUP BY trimBoth(s, 'x')` and
`GROUP BY trimBoth(s, '0123456789')` shared one hash-table statistics
entry, and so did `formatDateTime(d, '%Y')` and
`formatDateTime(d, '%F %T')`, whose step is keyed by its serialized form.
26.8 and 26.9 keep them apart: there the constant's name, which spells a
literal's value, was still in the key.

`isConstantValueInCacheKey` now decides for both `updateHash` and
`serialize` with `for_cache_key`: a value without a fixed size is kept
when it is at most 1 KiB, which covers ordinary literals and costs
nothing next to the rest of the key. Larger values are still left out, so
a heavy folded scalar subquery is not hashed on every execution, and so
is any value holding an aggregate function state, found by walking the
column rather than the type, since a `Dynamic` value hides it from the
type and `byteSize` does not count a state's foreign arenas. Sets and
lambdas keep their current handling.

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

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit ae001555ba1fce64f4341df746f29292a8002808 with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 45002a3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error: Left and right columns have same names (STID: 4752-3ae2) trunk bug, not from this PR: JoinStepLogical::deserialize in a distributed plan task infers the side of each input from its name and aborts on two __join_result_dummy inputs. This diff changes only the cache-key path of ActionsDAG::serialize; the same STID failed on 6 other PRs in 30 days #125071 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) / format_readable #0, #1 formatReadableSize / formatReadableQuantity +72.5% / +64.6%, reproduced after restart. This diff runs only at plan time, not in the per-row loop, but the slowdown is unique to this build among about 11k arm builds in 30 days, so per-build code placement against a real effect is still to be measured a fix task is created (investigating at full effort, fixing-PR link or measured conclusion to follow here)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #125071 and the fix task above (the owners of the first two rows)

Session id: cron:our-pr-ci-monitor:20261016-093007

@groeneai

Copy link
Copy Markdown
Collaborator Author

Measured conclusion for the format_readable #0/#1 row of the ledger above (arm Performance Comparison, 45002a3): it is a code placement flip of this one build, not this PR's code.

  • The whole per-row path (FunctionFormatReadable::executeImpl, formatReadable, DoubleToStringConverter::ToFixed, FastFixedDtoa, FillFractionals, CreateDecimalRepresentation and the call thunk) has identical machine code (address-normalized disassembly) in this build and in two fast builds of other PRs on the same master base, with the same stack depth. Compared with one of them, the callers sit at the same addresses and only the double_conversion block is 4 KiB lower.
  • On base a21868c the other 18 PR builds ran 1.04-1.06x against the reference, this one 1.72x / 1.65x, in the main run and after both restarts (three server processes). In 30 days (8324 arm runs) it is the only run of this query above 1.3x.
  • The diff only changes the hash table statistics key computed at planning, which these queries do not reach in the row loop.

There is nothing to fix in this PR, and I am not pushing again just to change the layout. How the gate should treat such single-build flips is the open question at #122350 (comment).

@fm4v

fm4v commented Oct 27, 2026

Copy link
Copy Markdown
Member

@groeneai the new test is too slow for the flaky check and fails the CH Inc sync check: in the private sync PR https://github.com/ClickHouse/clickhouse-private/pull/81821, Stateless tests (amd_asan_ubsan, flaky check, s3 storage, meta in keeper) fails 05401_hash_table_stats_key_same_type_expressions with Test runs too long (> 180s) (report). In the public flaky checks it already takes up to 153 s (amd_asan_ubsan) and 151 s (amd_tsan), so it is close to the limit there too. Please make it substantially faster, for example:

  • Use the fewest rows that keep each recorded group count above the 500e3 single-table threshold of getSizeHint (e.g. 600e3 rows, with a key like a * 2 instead of intDiv(a, 2) where a case needs the second run to preallocate), or drop cases that only repeat what another case already covers (the Nullable pair and the subquery pair each re-run a 1.2M-group aggregation twice).
  • Shrink s_05401 for the automatic parallel replicas line: repeat(a, 100) over 1e6 rows produces about 600 MB of strings across three replicas, while automatic_parallel_replicas_min_bytes_per_replica = 0 means a much smaller table should be enough to check that statistics are collected.

The other failures look unrelated: the Stress test (amd_debug) Left and right columns have same names (STID 4752-3ae2) also fails on master and other PRs in the last 30 days, the format_readable perf rows are explained in your measurement above, and the distributed cache Cannot increment size logical error in the private sync PR is in DistributedCacheTCPHandler.

On the overlap with #127882: both PRs change the same branch of calculateHashFromStep, and they merge without a textual conflict into wrong code, so whichever lands second needs a manual adjustment. This PR is the more complete fix for #125826 (rename-invariant hash, so query-based automatic parallel replicas keeps matching a projection that computes a same-type column, plus short string literals in the key), so I would land this one first and have #127882 keep only its optimizeTree change.

The test ran up to 153 s in the public ASan/TSan flaky checks and exceeded the 180 s limit in `Stateless tests (amd_asan_ubsan, flaky check, s3 storage, meta in keeper)` of the private sync PR ClickHouse/clickhouse-private#81821 (https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/praktika.html?PR=81821&sha=45002a340199a6cbe78206b82a3893656ad0dbd7&name_0=PR).

The tables now have 600e3 rows instead of 1.2e6, which still keeps every recorded entry above the 500e3 groups under which `getSizeHint` does not preallocate. Each shape records one entry with one group per row and checks the colliding expression with a single-group key such as `intDiv(a, 1000000)`, the reproducer of the issue, so the number of aggregations with many groups drops from about 17 to 7. The `Nullable` cases, the `formatDateTime` literal pair and the accepted 1 KiB collision are dropped, as they exercise the same key paths as the remaining cases. The table of the automatic parallel replicas line has 1e5 rows instead of 1e6.

Every check of a first run of a different expression still reads the entry of the query before it on master.

Related: ClickHouse#125826
@fm4v

fm4v commented Oct 27, 2026

Copy link
Copy Markdown
Member

Update: I made the test faster myself in ae73339, so please disregard my request to @groeneai above. The tables have 600e3 rows instead of 1.2e6, which keeps every recorded entry above the 500e3 threshold of getSizeHint. Each colliding expression is checked with a single-group key (intDiv(a, 1000000), the reproducer from #125826). The Nullable, formatDateTime and 1 KiB cases are dropped, and s_05401 has 1e5 rows. That leaves 7 aggregations with many groups instead of about 17.

On the master base binary (7055af3) the new version still fails on all four bug lines (q05401_plus3_1, q05401_div1m_1, q05401_string_trim_digits_1 and q05401_subquery_div1m_1 preallocate 600000 instead of 0). It runs in 1.1 s instead of 4.0 s on a release build. The PR's CI binaries have already expired, so the fixed side will be verified by CI.

`formatDateTime(d, '%Y')` after `formatDateTime(d, '%F %T')` is the only
case in the test where the computing step changes the column type, so the
step is keyed by `ActionsDAG::serialize` with `for_cache_key` and not by
`getComputedOutputsHash`. Without it, reverting the short-literal change in
`serialize` alone (keeping it in `updateOwnHash`) leaves the test green;
with it, `q05401_string_format_year_1` reads 600000. It costs one
aggregation with 600e3 groups and one with one group.

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

Copy link
Copy Markdown
Collaborator Author

Thanks. I checked ae73339 on a local debug build of this PR's source: it passes 50/50 under --flaky-check -j 16 with random settings. With 16 concurrent copies on a master ASan build, the median run drops from 19.6 s to 4.8 s.

I pushed one commit on top of it, ae00155, which brings back the formatDateTime(d, '%F %T') / formatDateTime(d, '%Y') pair: one aggregation with 600e3 groups and one with a single group. It is a different key path from trimBoth: the step changes the column type, so it is keyed by ActionsDAG::serialize with for_cache_key, not by getComputedOutputsHash. On a build with only the serialize half of the short-literal change reverted, ae73339 still passes, while with the pair back q05401_string_format_year_1 preallocates 600000. The pair costs about 1 s of the ASan median (4.8 s -> 5.7-6.1 s), and the test now fails five lines on master. If you would rather keep the test minimal, I will revert it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ae00155

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Logical error: Cannot write to canceled buffer (STID: 4158-2b4c) not from this PR (it changes only the hash table statistics key): the embedded web-terminal client rendered progress into its canceled terminal buffer, ClientEmbeddedRunner::clientRoutine -> ClientBase::onProfileEvents -> ProgressIndication::writeProgress. The same STID hit 3 other PRs and 2 master runs in 30 days #127834 (external, open)
Build profile diff infra, not from this PR: every readiness probe of the CI logs cluster failed, so the job ended with LogClusterNotReady: the endpoint never became ready in has_pr_data before comparing anything. 306 of 310 runs since 2026-10-26 22:00 UTC are red, on 242 PRs #126200 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #127834 and #126200 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head; 05401_hash_table_stats_key_same_type_expressions passed in every job that ran it.

Session id: cron:our-pr-ci-monitor:20261027-223005

@fm4v
fm4v added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit d1c8ad7 Nov 4, 2026
526 of 531 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
murphy-4o pushed a commit that referenced this pull request Nov 6, 2026
…ild loop

The conflict resolution of the cherry-pick (#129668) kept the old body of
Node::updateHash as the new updateOwnHash, so:

- updateOwnHash is defined in ActionsDAG.cpp but not declared in
  ActionsDAG.h (the declaration came with #126148, which is not on 26.10),
  and the build fails with "no member named 'updateOwnHash'".
- updateOwnHash still ends with the recursion over the children, so each
  per-node digest re-hashes the whole subtree and the planning hang of
  #126250 stays.

Add the declaration as on master and remove the loop. The tree now equals
26.10 + #129184 with only the #126148 updateOwnHash split, as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ild loop

The conflict resolution of the cherry-pick (#129668) kept the old body of
Node::updateHash as the new updateOwnHash, so:

- updateOwnHash is defined in ActionsDAG.cpp but not declared in
  ActionsDAG.h (the declaration came with #126148, which is not on 26.10),
  and the build fails with "no member named 'updateOwnHash'".
- updateOwnHash still ends with the recursion over the children, so each
  per-node digest re-hashes the whole subtree and the planning hang of
  #126250 stays.

Add the declaration as on master and remove the loop. The tree now equals
26.10 + #129184 with only the #126148 updateOwnHash split, as on master.

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

can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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.

Same-type GROUP BY key expressions share one hash-table stats entry Cache key ignores string literals: s = 'a' and s = 'b' share stats

5 participants