Skip to content

Do not copy a constant column to every row of a block in DISTINCT - #131870

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:distinct-constant-columns-no-copy
Nov 16, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:distinct-constant-columns-no-copy

Conversation

@groeneai

@groeneai groeneai commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131793
Related: #131625
Related: #131185

Changelog category (leave one):

  • Improvement

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

SELECT DISTINCT no longer copies a constant column to every row of a block when all DISTINCT columns are constants, or when the DISTINCT is done in order (optimize_distinct_in_order). For example, SELECT DISTINCT toFixedString('a', 1048577) FROM numbers(100000) no longer requests 64 GiB of memory with max_block_size = 65409.

Description

Failing job (server OOM-killed): AST fuzzer (amd_release, oracle) on #131793, SELECT DISTINCT toFixedString(<3 bytes>, 1048577) FROM clusterAllReplicas(..., system.text_log) ... LIMIT -2147483648, one ~8 GiB allocation per reading stream. No related open issue found.

A DISTINCT over constants only returns one row, but DistinctTransform::deduplicate converted the whole chunk to full columns before cutting it to that row, so each constant was first replicated to the chunk size. The conversion now runs after the cut; the emitted chunk is unchanged (one row, full columns).

DistinctSortedStreamTransform (optimize_distinct_in_order) materialized every column of every chunk too, header constants included. It now materializes only the non-constant columns, as DistinctSetFilter already does for the hashed path of the same step; a constant in the sorting prefix is compared through its single value.

Validation: each memory query of the new test fails on master with MEMORY_LIMIT_EXCEEDED (61 to 64 GiB requested; the FixedString query fails the same way on 25.3 and 26.8) and passes with the fix, 50 of 50 randomized runs; reverting either half reddens its own queries. The remote() and clusterAllReplicas shapes behave the same. The 762 stateless tests that use DISTINCT show no new failure (the 38 that fail locally, on stateful datasets and object storages, fail on master too).

The fuzzer server's max_server_memory_usage not stopping the last allocation is the MemoryTracker problem of #131625.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 3 commits November 15, 2026 19:37
A DISTINCT whose columns are all constants returns one row, but
DistinctTransform::deduplicate converted the whole chunk to full columns
before cutting it to that row, so a constant was replicated to the chunk
size first (65409 rows x 1 MiB = 64 GiB for `SELECT DISTINCT
toFixedString('a', 1048577) FROM numbers(100000)`). The fuzzed query
`SELECT DISTINCT toFixedString(.., 1048577) FROM clusterAllReplicas(..,
system.text_log)` made one such ~8 GiB allocation per reading stream and
the AST fuzzer server was OOM-killed. The conversion now runs after the
cut, so the emitted chunk is unchanged (one row, full columns).

DistinctSortedStreamTransform (optimize_distinct_in_order) materialized
every column of every chunk as well, although header constants are never
its keys. It now materializes the non-constant columns and the sorting
prefix (a constant can be the sorting prefix), and keeps the other header
constants compact, as DistinctSetFilter already does for the hashed path
of the same DistinctStep.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
DistinctSortedStreamTransform still materialized a header constant that
is part of the sorting prefix, e.g. the final in-order DISTINCT of
`SELECT DISTINCT number AS k, repeat('a', 1000000) AS s FROM
numbers(100000) ORDER BY s`, which requested 60.92 GiB with
max_block_size = 65409. Only the non-constant columns are materialized
now, exactly the DistinctSetFilter rule. The range search already treats
a constant as one run (ColumnConst::compareAt is always equal), and the
previous-chunk key is saved from, and compared against, the constant's
single nested value, so both sides of that comparison have the same
representation whether a chunk carries the column as a constant or not.

The test gets the constant-sorting-prefix query, and both in-order
queries get an EXPLAIN PIPELINE check that they run
DistinctSortedStreamTransform, so a plan change cannot turn them into
checks of the hashed path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the design note above materializeChunk in DistinctSortedStreamTransform::transform; the helper's own documentation already says only non-constant columns are returned.

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; 2 findings; 1 full pass + 1 fix round + 1 delta recheck with 0 findings).

# Sev Finding Verdict Evidence / action
1 ❌ A constant in the sorting prefix of an in-order DISTINCT was still copied to every row (SELECT DISTINCT number AS k, repeat('a', 1000000) AS s FROM numbers(100000) ORDER BY s, 60.92 GiB) AGREE, fixed @ 98eea29 DistinctSortedStreamTransform materializes only non-constant columns; the previous-chunk key is saved and compared through the constant's single value; test query 4
2 ⚠️ The in-order test query could silently fall back to the hashed path AGREE, fixed @ 98eea29 EXPLAIN PIPELINE checks before both in-order queries; they print 0 with optimize_distinct_in_order = 0

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

Session id: cron:clickhouse-review-slot-8:20261115-202802

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger, could you review this? A DISTINCT over constants only (and an in-order DISTINCT) materialized every constant column to the full block size before deduplicating, so a 1 MiB constant asked for ~64 GiB per block; the const-only path now converts after cutting to one row, and the in-order transform materializes only non-constant columns, as the hashed path already does.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT length(s) FROM (SELECT DISTINCT toFixedString('a', 1048577) AS s FROM numbers(100000)) SETTINGS max_memory_usage = '1Gi', max_block_size = 65409 fails on master with MEMORY_LIMIT_EXCEEDED (63.88 GiB requested) every run; the in-order variant over a MergeTree table with optimize_distinct_in_order = 1 fails with 61.04 GiB, and the in-order variant with a constant in the sorting prefix (... ORDER BY s LIMIT 1) with 60.92 GiB.
b Root cause explained? The const-only branch of DistinctTransform::deduplicate converted the whole chunk to full columns before cutting it to one row, so ColumnConst::convertToFullColumn replicated each constant to the chunk size. DistinctSortedStreamTransform::transform materialized every header constant on every chunk, including one in the sorting prefix. Stacks confirmed (convertToFullIfConst <- each transform).
c Fix matches root cause? Yes: the conversion moves after the cut (output unchanged), and the in-order transform materializes only the non-constant columns, the rule DistinctSetFilter already uses; a constant in the sorting prefix is compared through its single value. No limit, setting or guard is touched.
d Test intent preserved / new tests added? New stateless test 05812_distinct_constant_columns_memory: String and FixedString const-only queries, an in-order query with a constant outside the sorting prefix and one with a constant as the sorting prefix, each under max_memory_usage = '1Gi'; each in-order query is preceded by an EXPLAIN PIPELINE check that it runs DistinctSortedStreamTransform.
e Both directions demonstrated? Yes. Master binary: the test fails (Code: 241); fixed binary: passes, 50/50 randomized runs. Reverting only the DistinctTransform change fails the const-only queries; reverting only the in-order change fails the in-order query; materializing only the sorting prefix again fails the constant-sorting-prefix query and nothing else.
f Fix is general across code paths? Both transforms that copied constants are fixed. The hashed path (DistinctSetFilter) and the spill path already keep constants compact; const-only DISTINCT never spills; remote shards run the same transforms (remote() and clusterAllReplicas shapes verified, including shardNum() in the sorting prefix on the initiator).
g Fix generalizes across inputs (params/datatypes/wrappers)? Two A/B matrices match master: 89 queries over String, FixedString, Nullable, NULL, LowCardinality, Array, Tuple, Map constants, empty and 1-row inputs, LIMIT 0/1/-N, IN subqueries; 397 constant-sorting-prefix queries (prefix position, two constants, DESC, LIMIT) at block sizes 1/2/3, max_threads 1/4, over a 3-part MergeTree and numbers_mt.
h Backward compatible? (maintainer-approved exception only) Yes. No settings, format or protocol change. The const-only output is byte-identical; the in-order transform now emits header constants as ColumnConst, as the hashed path of the same step already does.
i Invariants and contracts preserved? Header constants stay constant, all other columns are full, and the columns of a chunk keep equal sizes. A constant in the sorting prefix is one run; the previous-chunk key is saved and compared through its single nested value, so both sides of the comparison match. 762 DISTINCT stateless tests and 127 Distinct* unit tests: no new failure.

Session id: cron:clickhouse-impl-slot-6:20261115-200300

@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [42dc29d]

Summary: ✅


AI Review

Summary

PR #131870 avoids expanding constant columns before constant-only deduplication and keeps header constants compact during in-order DISTINCT. Reviewed head 42dc29d4a7df0e9e4d10785a85fa12ab1aced070, including all prior discussion. No actionable findings. The new regression test passes on the PR-head CI binary and exactly matches its reference; an additional LIMIT ... WITH TIES query matches the hashed path. The fetched CI reports contain no failed tests.

Compact-column consumers traced:

  • DistinctSortedStreamTransform: range searches compare constants through IColumn; saved boundary keys use their nested values.
  • DistinctSetFilter and partition scattering: header constants are excluded from hashing keys; scattering supports constant columns.
  • Sorting, merging, and Squashing: constants are stripped/restored or materialized before representation-specific copying.
  • Expressions, filtering, LimitTransform, and ExtremesTransform: use constant-aware column operations; the focused ties query exercises the ordered consumer.
  • Set, HashJoin, Aggregator, and WindowTransform: normalize keys and arguments before representation-specific access.
  • MaterializingTransform and NativeWriter: materialize constants before output serialization.
Final Verdict

✅ Approve. No required changes or new inline findings.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 42dc29d4a with master 1be838e3c (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.

Compile time of recompiled translation units

9 translation units recompiled, 26 s compile time in total, 9 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 16, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit 009ed37 Nov 16, 2026
384 of 385 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 2026
yackushevas pushed a commit to yackushevas/ClickHouse that referenced this pull request Nov 20, 2026
`ColumnConst` had no `getEqualRangeEndAssumeSorted`, so the generic
galloping search compared the nested value with itself on every probe.
Since ClickHouse#131870 a constant stays a `ColumnConst` in the sorting prefix of
the in-order DISTINCT, and debug and sanitizer builds re-verify every run
(the `chassert` in `SortedKeyRuns::findRunEnd` re-searches each key column,
and `checkEqualRangeEndAssumeSorted` samples more probes). With a 1 MB
constant before a distinct column every run is one row, which is about 25
one-megabyte compares per row inside one `work()` call: the query could not
observe `max_execution_time` or KILL (51 s in a debug build, 1668 s in the
`Stress test (amd_tsan)` hung check).

Every row of a constant compares equal for any NaN direction hint, so the
run starting at `begin` ends at `end`, the same property behind the
identity `getPermutation` and the no-op `updatePermutation`.

The release build was not affected (it searches the constant once per
chunk), so this does not revert ClickHouse#131870, which would bring back the
per-row copy of the constant that it removed.

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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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